v8  3.14.5(node0.10.28)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
platform.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
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 // This module contains the platform-specific code. This make the rest of the
29 // code less dependent on operating system, compilers and runtime libraries.
30 // This module does specifically not deal with differences between different
31 // processor architecture.
32 // The platform classes have the same definition for all platforms. The
33 // implementation for a particular platform is put in platform_<os>.cc.
34 // The build system then uses the implementation for the target platform.
35 //
36 // This design has been chosen because it is simple and fast. Alternatively,
37 // the platform dependent classes could have been implemented using abstract
38 // superclasses with virtual methods and having specializations for each
39 // platform. This design was rejected because it was more complicated and
40 // slower. It would require factory methods for selecting the right
41 // implementation and the overhead of virtual methods for performance
42 // sensitive like mutex locking/unlocking.
43 
44 #ifndef V8_PLATFORM_H_
45 #define V8_PLATFORM_H_
46 
47 #ifdef __sun
48 # ifndef signbit
49 int signbit(double x);
50 # endif
51 #endif
52 
53 // GCC specific stuff
54 #ifdef __GNUC__
55 
56 // Needed for va_list on at least MinGW and Android.
57 #include <stdarg.h>
58 
59 #define __GNUC_VERSION__ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100)
60 
61 #endif // __GNUC__
62 
63 
64 // Windows specific stuff.
65 #ifdef WIN32
66 
67 // Microsoft Visual C++ specific stuff.
68 #ifdef _MSC_VER
69 
70 #include "win32-math.h"
71 
72 int strncasecmp(const char* s1, const char* s2, int n);
73 
74 inline int lrint(double flt) {
75  int intgr;
76 #if defined(V8_TARGET_ARCH_IA32)
77  __asm {
78  fld flt
79  fistp intgr
80  };
81 #else
82  intgr = static_cast<int>(flt + 0.5);
83  if ((intgr & 1) != 0 && intgr - flt == 0.5) {
84  // If the number is halfway between two integers, round to the even one.
85  intgr--;
86  }
87 #endif
88  return intgr;
89 }
90 
91 
92 #endif // _MSC_VER
93 
94 // Random is missing on both Visual Studio and MinGW.
95 int random();
96 
97 #endif // WIN32
98 
99 #include "atomicops.h"
100 #include "lazy-instance.h"
101 #include "platform-tls.h"
102 #include "utils.h"
103 #include "v8globals.h"
104 
105 namespace v8 {
106 namespace internal {
107 
108 // Use AtomicWord for a machine-sized pointer. It is assumed that
109 // reads and writes of naturally aligned values of this type are atomic.
110 #if defined(__OpenBSD__) && defined(__i386__)
111 typedef Atomic32 AtomicWord;
112 #else
113 typedef intptr_t AtomicWord;
114 #endif
115 
116 class Semaphore;
117 class Mutex;
118 
119 double ceiling(double x);
120 double modulo(double x, double y);
121 
122 // Custom implementation of sin, cos, tan and log.
123 double fast_sin(double input);
124 double fast_cos(double input);
125 double fast_tan(double input);
126 double fast_log(double input);
127 double fast_sqrt(double input);
128 
129 // Forward declarations.
130 class Socket;
131 
132 // ----------------------------------------------------------------------------
133 // OS
134 //
135 // This class has static methods for the different platform specific
136 // functions. Add methods here to cope with differences between the
137 // supported platforms.
138 
139 class OS {
140  public:
141  // Initializes the platform OS support. Called once at VM startup.
142  static void SetUp();
143 
144  // Initializes the platform OS support that depend on CPU features. This is
145  // called after CPU initialization.
146  static void PostSetUp();
147 
148  // Clean up platform-OS-related things. Called once at VM shutdown.
149  static void TearDown();
150 
151  // Returns the accumulated user time for thread. This routine
152  // can be used for profiling. The implementation should
153  // strive for high-precision timer resolution, preferable
154  // micro-second resolution.
155  static int GetUserTime(uint32_t* secs, uint32_t* usecs);
156 
157  // Get a tick counter normalized to one tick per microsecond.
158  // Used for calculating time intervals.
159  static int64_t Ticks();
160 
161  // Returns current time as the number of milliseconds since
162  // 00:00:00 UTC, January 1, 1970.
163  static double TimeCurrentMillis();
164 
165  // Returns a string identifying the current time zone. The
166  // timestamp is used for determining if DST is in effect.
167  static const char* LocalTimezone(double time);
168 
169  // Returns the local time offset in milliseconds east of UTC without
170  // taking daylight savings time into account.
171  static double LocalTimeOffset();
172 
173  // Returns the daylight savings offset for the given time.
174  static double DaylightSavingsOffset(double time);
175 
176  // Returns last OS error.
177  static int GetLastError();
178 
179  static FILE* FOpen(const char* path, const char* mode);
180  static bool Remove(const char* path);
181 
182  // Opens a temporary file, the file is auto removed on close.
183  static FILE* OpenTemporaryFile();
184 
185  // Log file open mode is platform-dependent due to line ends issues.
186  static const char* const LogFileOpenMode;
187 
188  // Print output to console. This is mostly used for debugging output.
189  // On platforms that has standard terminal output, the output
190  // should go to stdout.
191  static void Print(const char* format, ...);
192  static void VPrint(const char* format, va_list args);
193 
194  // Print output to a file. This is mostly used for debugging output.
195  static void FPrint(FILE* out, const char* format, ...);
196  static void VFPrint(FILE* out, const char* format, va_list args);
197 
198  // Print error output to console. This is mostly used for error message
199  // output. On platforms that has standard terminal output, the output
200  // should go to stderr.
201  static void PrintError(const char* format, ...);
202  static void VPrintError(const char* format, va_list args);
203 
204  // Allocate/Free memory used by JS heap. Pages are readable/writable, but
205  // they are not guaranteed to be executable unless 'executable' is true.
206  // Returns the address of allocated memory, or NULL if failed.
207  static void* Allocate(const size_t requested,
208  size_t* allocated,
209  bool is_executable);
210  static void Free(void* address, const size_t size);
211 
212  // This is the granularity at which the ProtectCode(...) call can set page
213  // permissions.
214  static intptr_t CommitPageSize();
215 
216  // Mark code segments non-writable.
217  static void ProtectCode(void* address, const size_t size);
218 
219  // Assign memory as a guard page so that access will cause an exception.
220  static void Guard(void* address, const size_t size);
221 
222  // Generate a random address to be used for hinting mmap().
223  static void* GetRandomMmapAddr();
224 
225  // Get the Alignment guaranteed by Allocate().
226  static size_t AllocateAlignment();
227 
228  // Returns an indication of whether a pointer is in a space that
229  // has been allocated by Allocate(). This method may conservatively
230  // always return false, but giving more accurate information may
231  // improve the robustness of the stack dump code in the presence of
232  // heap corruption.
233  static bool IsOutsideAllocatedSpace(void* pointer);
234 
235  // Sleep for a number of milliseconds.
236  static void Sleep(const int milliseconds);
237 
238  // Abort the current process.
239  static void Abort();
240 
241  // Debug break.
242  static void DebugBreak();
243 
244  // Walk the stack.
245  static const int kStackWalkError = -1;
246  static const int kStackWalkMaxNameLen = 256;
247  static const int kStackWalkMaxTextLen = 256;
248  struct StackFrame {
249  void* address;
251  };
252 
253  static int StackWalk(Vector<StackFrame> frames);
254 
255  // Factory method for creating platform dependent Mutex.
256  // Please use delete to reclaim the storage for the returned Mutex.
257  static Mutex* CreateMutex();
258 
259  // Factory method for creating platform dependent Semaphore.
260  // Please use delete to reclaim the storage for the returned Semaphore.
261  static Semaphore* CreateSemaphore(int count);
262 
263  // Factory method for creating platform dependent Socket.
264  // Please use delete to reclaim the storage for the returned Socket.
265  static Socket* CreateSocket();
266 
268  public:
269  static MemoryMappedFile* open(const char* name);
270  static MemoryMappedFile* create(const char* name, int size, void* initial);
271  virtual ~MemoryMappedFile() { }
272  virtual void* memory() = 0;
273  virtual int size() = 0;
274  };
275 
276  // Safe formatting print. Ensures that str is always null-terminated.
277  // Returns the number of chars written, or -1 if output was truncated.
278  static int SNPrintF(Vector<char> str, const char* format, ...);
279  static int VSNPrintF(Vector<char> str,
280  const char* format,
281  va_list args);
282 
283  static char* StrChr(char* str, int c);
284  static void StrNCpy(Vector<char> dest, const char* src, size_t n);
285 
286  // Support for the profiler. Can do nothing, in which case ticks
287  // occuring in shared libraries will not be properly accounted for.
288  static void LogSharedLibraryAddresses();
289 
290  // Support for the profiler. Notifies the external profiling
291  // process that a code moving garbage collection starts. Can do
292  // nothing, in which case the code objects must not move (e.g., by
293  // using --never-compact) if accurate profiling is desired.
294  static void SignalCodeMovingGC();
295 
296  // The return value indicates the CPU features we are sure of because of the
297  // OS. For example MacOSX doesn't run on any x86 CPUs that don't have SSE2
298  // instructions.
299  // This is a little messy because the interpretation is subject to the cross
300  // of the CPU and the OS. The bits in the answer correspond to the bit
301  // positions indicated by the members of the CpuFeature enum from globals.h
302  static uint64_t CpuFeaturesImpliedByPlatform();
303 
304  // Maximum size of the virtual memory. 0 means there is no artificial
305  // limit.
306  static intptr_t MaxVirtualMemory();
307 
308  // Returns the double constant NAN
309  static double nan_value();
310 
311  // Support runtime detection of Cpu implementer
313 
314  // Support runtime detection of VFP3 on ARM CPUs.
315  static bool ArmCpuHasFeature(CpuFeature feature);
316 
317  // Support runtime detection of whether the hard float option of the
318  // EABI is used.
319  static bool ArmUsingHardFloat();
320 
321  // Support runtime detection of FPU on MIPS CPUs.
322  static bool MipsCpuHasFeature(CpuFeature feature);
323 
324  // Returns the activation frame alignment constraint or zero if
325  // the platform doesn't care. Guaranteed to be a power of two.
326  static int ActivationFrameAlignment();
327 
328  static void ReleaseStore(volatile AtomicWord* ptr, AtomicWord value);
329 
330 #if defined(V8_TARGET_ARCH_IA32)
331  // Copy memory area to disjoint memory area.
332  static void MemCopy(void* dest, const void* src, size_t size);
333  // Limit below which the extra overhead of the MemCopy function is likely
334  // to outweigh the benefits of faster copying.
335  static const int kMinComplexMemCopy = 64;
336  typedef void (*MemCopyFunction)(void* dest, const void* src, size_t size);
337 
338 #else // V8_TARGET_ARCH_IA32
339  static void MemCopy(void* dest, const void* src, size_t size) {
340  memcpy(dest, src, size);
341  }
342  static const int kMinComplexMemCopy = 256;
343 #endif // V8_TARGET_ARCH_IA32
344 
345  static int GetCurrentProcessId();
346 
347  private:
348  static const int msPerSecond = 1000;
349 
350  DISALLOW_IMPLICIT_CONSTRUCTORS(OS);
351 };
352 
353 // Represents and controls an area of reserved memory.
354 // Control of the reserved memory can be assigned to another VirtualMemory
355 // object by assignment or copy-contructing. This removes the reserved memory
356 // from the original object.
358  public:
359  // Empty VirtualMemory object, controlling no reserved memory.
360  VirtualMemory();
361 
362  // Reserves virtual memory with size.
363  explicit VirtualMemory(size_t size);
364 
365  // Reserves virtual memory containing an area of the given size that
366  // is aligned per alignment. This may not be at the position returned
367  // by address().
368  VirtualMemory(size_t size, size_t alignment);
369 
370  // Releases the reserved memory, if any, controlled by this VirtualMemory
371  // object.
372  ~VirtualMemory();
373 
374  // Returns whether the memory has been reserved.
375  bool IsReserved();
376 
377  // Initialize or resets an embedded VirtualMemory object.
378  void Reset();
379 
380  // Returns the start address of the reserved memory.
381  // If the memory was reserved with an alignment, this address is not
382  // necessarily aligned. The user might need to round it up to a multiple of
383  // the alignment to get the start of the aligned block.
384  void* address() {
385  ASSERT(IsReserved());
386  return address_;
387  }
388 
389  // Returns the size of the reserved memory. The returned value is only
390  // meaningful when IsReserved() returns true.
391  // If the memory was reserved with an alignment, this size may be larger
392  // than the requested size.
393  size_t size() { return size_; }
394 
395  // Commits real memory. Returns whether the operation succeeded.
396  bool Commit(void* address, size_t size, bool is_executable);
397 
398  // Uncommit real memory. Returns whether the operation succeeded.
399  bool Uncommit(void* address, size_t size);
400 
401  // Creates a single guard page at the given address.
402  bool Guard(void* address);
403 
404  void Release() {
405  ASSERT(IsReserved());
406  // Notice: Order is important here. The VirtualMemory object might live
407  // inside the allocated region.
408  void* address = address_;
409  size_t size = size_;
410  Reset();
411  bool result = ReleaseRegion(address, size);
412  USE(result);
413  ASSERT(result);
414  }
415 
416  // Assign control of the reserved region to a different VirtualMemory object.
417  // The old object is no longer functional (IsReserved() returns false).
419  ASSERT(!IsReserved());
420  address_ = from->address_;
421  size_ = from->size_;
422  from->Reset();
423  }
424 
425  static void* ReserveRegion(size_t size);
426 
427  static bool CommitRegion(void* base, size_t size, bool is_executable);
428 
429  static bool UncommitRegion(void* base, size_t size);
430 
431  // Must be called with a base pointer that has been returned by ReserveRegion
432  // and the same size it was reserved with.
433  static bool ReleaseRegion(void* base, size_t size);
434 
435  private:
436  void* address_; // Start address of the virtual memory.
437  size_t size_; // Size of the virtual memory.
438 };
439 
440 
441 // ----------------------------------------------------------------------------
442 // Thread
443 //
444 // Thread objects are used for creating and running threads. When the start()
445 // method is called the new thread starts running the run() method in the new
446 // thread. The Thread object should not be deallocated before the thread has
447 // terminated.
448 
449 class Thread {
450  public:
451  // Opaque data type for thread-local storage keys.
452  // LOCAL_STORAGE_KEY_MIN_VALUE and LOCAL_STORAGE_KEY_MAX_VALUE are specified
453  // to ensure that enumeration type has correct value range (see Issue 830 for
454  // more details).
458  };
459 
460  class Options {
461  public:
462  Options() : name_("v8:<unknown>"), stack_size_(0) {}
463  Options(const char* name, int stack_size = 0)
464  : name_(name), stack_size_(stack_size) {}
465 
466  const char* name() const { return name_; }
467  int stack_size() const { return stack_size_; }
468 
469  private:
470  const char* name_;
471  int stack_size_;
472  };
473 
474  // Create new thread.
475  explicit Thread(const Options& options);
476  virtual ~Thread();
477 
478  // Start new thread by calling the Run() method in the new thread.
479  void Start();
480 
481  // Wait until thread terminates.
482  void Join();
483 
484  inline const char* name() const {
485  return name_;
486  }
487 
488  // Abstract method for run handler.
489  virtual void Run() = 0;
490 
491  // Thread-local storage.
493  static void DeleteThreadLocalKey(LocalStorageKey key);
494  static void* GetThreadLocal(LocalStorageKey key);
496  return static_cast<int>(reinterpret_cast<intptr_t>(GetThreadLocal(key)));
497  }
498  static void SetThreadLocal(LocalStorageKey key, void* value);
499  static void SetThreadLocalInt(LocalStorageKey key, int value) {
500  SetThreadLocal(key, reinterpret_cast<void*>(static_cast<intptr_t>(value)));
501  }
502  static bool HasThreadLocal(LocalStorageKey key) {
503  return GetThreadLocal(key) != NULL;
504  }
505 
506 #ifdef V8_FAST_TLS_SUPPORTED
507  static inline void* GetExistingThreadLocal(LocalStorageKey key) {
508  void* result = reinterpret_cast<void*>(
509  InternalGetExistingThreadLocal(static_cast<intptr_t>(key)));
510  ASSERT(result == GetThreadLocal(key));
511  return result;
512  }
513 #else
514  static inline void* GetExistingThreadLocal(LocalStorageKey key) {
515  return GetThreadLocal(key);
516  }
517 #endif
518 
519  // A hint to the scheduler to let another thread run.
520  static void YieldCPU();
521 
522 
523  // The thread name length is limited to 16 based on Linux's implementation of
524  // prctl().
525  static const int kMaxThreadNameLength = 16;
526 
527  class PlatformData;
528  PlatformData* data() { return data_; }
529 
530  private:
531  void set_name(const char* name);
532 
533  PlatformData* data_;
534 
535  char name_[kMaxThreadNameLength];
536  int stack_size_;
537 
539 };
540 
541 
542 // ----------------------------------------------------------------------------
543 // Mutex
544 //
545 // Mutexes are used for serializing access to non-reentrant sections of code.
546 // The implementations of mutex should allow for nested/recursive locking.
547 
548 class Mutex {
549  public:
550  virtual ~Mutex() {}
551 
552  // Locks the given mutex. If the mutex is currently unlocked, it becomes
553  // locked and owned by the calling thread, and immediately. If the mutex
554  // is already locked by another thread, suspends the calling thread until
555  // the mutex is unlocked.
556  virtual int Lock() = 0;
557 
558  // Unlocks the given mutex. The mutex is assumed to be locked and owned by
559  // the calling thread on entrance.
560  virtual int Unlock() = 0;
561 
562  // Tries to lock the given mutex. Returns whether the mutex was
563  // successfully locked.
564  virtual bool TryLock() = 0;
565 };
566 
568  static Mutex* Create() {
569  return OS::CreateMutex();
570  }
571 };
572 
573 // POD Mutex initialized lazily (i.e. the first time Pointer() is called).
574 // Usage:
575 // static LazyMutex my_mutex = LAZY_MUTEX_INITIALIZER;
576 //
577 // void my_function() {
578 // ScopedLock my_lock(my_mutex.Pointer());
579 // // Do something.
580 // }
581 //
582 typedef LazyDynamicInstance<
584 
585 #define LAZY_MUTEX_INITIALIZER LAZY_DYNAMIC_INSTANCE_INITIALIZER
586 
587 // ----------------------------------------------------------------------------
588 // ScopedLock
589 //
590 // Stack-allocated ScopedLocks provide block-scoped locking and
591 // unlocking of a mutex.
592 class ScopedLock {
593  public:
594  explicit ScopedLock(Mutex* mutex): mutex_(mutex) {
595  ASSERT(mutex_ != NULL);
596  mutex_->Lock();
597  }
599  mutex_->Unlock();
600  }
601 
602  private:
603  Mutex* mutex_;
604  DISALLOW_COPY_AND_ASSIGN(ScopedLock);
605 };
606 
607 
608 // ----------------------------------------------------------------------------
609 // Semaphore
610 //
611 // A semaphore object is a synchronization object that maintains a count. The
612 // count is decremented each time a thread completes a wait for the semaphore
613 // object and incremented each time a thread signals the semaphore. When the
614 // count reaches zero, threads waiting for the semaphore blocks until the
615 // count becomes non-zero.
616 
617 class Semaphore {
618  public:
619  virtual ~Semaphore() {}
620 
621  // Suspends the calling thread until the semaphore counter is non zero
622  // and then decrements the semaphore counter.
623  virtual void Wait() = 0;
624 
625  // Suspends the calling thread until the counter is non zero or the timeout
626  // time has passed. If timeout happens the return value is false and the
627  // counter is unchanged. Otherwise the semaphore counter is decremented and
628  // true is returned. The timeout value is specified in microseconds.
629  virtual bool Wait(int timeout) = 0;
630 
631  // Increments the semaphore counter.
632  virtual void Signal() = 0;
633 };
634 
635 template <int InitialValue>
637  static Semaphore* Create() {
638  return OS::CreateSemaphore(InitialValue);
639  }
640 };
641 
642 // POD Semaphore initialized lazily (i.e. the first time Pointer() is called).
643 // Usage:
644 // // The following semaphore starts at 0.
645 // static LazySemaphore<0>::type my_semaphore = LAZY_SEMAPHORE_INITIALIZER;
646 //
647 // void my_function() {
648 // // Do something with my_semaphore.Pointer().
649 // }
650 //
651 template <int InitialValue>
653  typedef typename LazyDynamicInstance<
656 };
657 
658 #define LAZY_SEMAPHORE_INITIALIZER LAZY_DYNAMIC_INSTANCE_INITIALIZER
659 
660 
661 // ----------------------------------------------------------------------------
662 // Socket
663 //
664 
665 class Socket {
666  public:
667  virtual ~Socket() {}
668 
669  // Server initialization.
670  virtual bool Bind(const int port) = 0;
671  virtual bool Listen(int backlog) const = 0;
672  virtual Socket* Accept() const = 0;
673 
674  // Client initialization.
675  virtual bool Connect(const char* host, const char* port) = 0;
676 
677  // Shutdown socket for both read and write. This causes blocking Send and
678  // Receive calls to exit. After Shutdown the Socket object cannot be used for
679  // any communication.
680  virtual bool Shutdown() = 0;
681 
682  // Data Transimission
683  // Return 0 on failure.
684  virtual int Send(const char* data, int len) const = 0;
685  virtual int Receive(char* data, int len) const = 0;
686 
687  // Set the value of the SO_REUSEADDR socket option.
688  virtual bool SetReuseAddress(bool reuse_address) = 0;
689 
690  virtual bool IsValid() const = 0;
691 
692  static bool SetUp();
693  static int LastError();
694  static uint16_t HToN(uint16_t value);
695  static uint16_t NToH(uint16_t value);
696  static uint32_t HToN(uint32_t value);
697  static uint32_t NToH(uint32_t value);
698 };
699 
700 
701 // ----------------------------------------------------------------------------
702 // Sampler
703 //
704 // A sampler periodically samples the state of the VM and optionally
705 // (if used for profiling) the program counter and stack pointer for
706 // the thread that created it.
707 
708 // TickSample captures the information collected for each sample.
709 class TickSample {
710  public:
712  : state(OTHER),
713  pc(NULL),
714  sp(NULL),
715  fp(NULL),
716  tos(NULL),
717  frames_count(0),
719  StateTag state; // The state of the VM.
720  Address pc; // Instruction pointer.
721  Address sp; // Stack pointer.
722  Address fp; // Frame pointer.
723  union {
724  Address tos; // Top stack value (*sp).
726  };
727  static const int kMaxFramesCount = 64;
728  Address stack[kMaxFramesCount]; // Call stack.
729  int frames_count : 8; // Number of captured frames.
731 };
732 
733 class Sampler {
734  public:
735  // Initialize sampler.
737  virtual ~Sampler();
738 
739  int interval() const { return interval_; }
740 
741  // Performs stack sampling.
743  DoSampleStack(sample);
744  IncSamplesTaken();
745  }
746 
747  // This method is called for each sampling period with the current
748  // program counter.
749  virtual void Tick(TickSample* sample) = 0;
750 
751  // Start and stop sampler.
752  void Start();
753  void Stop();
754 
755  // Is the sampler used for profiling?
756  bool IsProfiling() const { return NoBarrier_Load(&profiling_) > 0; }
759 
760  // Whether the sampler is running (that is, consumes resources).
761  bool IsActive() const { return NoBarrier_Load(&active_); }
762 
763  Isolate* isolate() { return isolate_; }
764 
765  // Used in tests to make sure that stack sampling is performed.
766  int samples_taken() const { return samples_taken_; }
767  void ResetSamplesTaken() { samples_taken_ = 0; }
768 
769  class PlatformData;
770  PlatformData* data() { return data_; }
771 
772  PlatformData* platform_data() { return data_; }
773 
774  protected:
775  virtual void DoSampleStack(TickSample* sample) = 0;
776 
777  private:
778  void SetActive(bool value) { NoBarrier_Store(&active_, value); }
779  void IncSamplesTaken() { if (++samples_taken_ < 0) samples_taken_ = 0; }
780 
781  Isolate* isolate_;
782  const int interval_;
783  Atomic32 profiling_;
784  Atomic32 active_;
785  PlatformData* data_; // Platform specific data.
786  int samples_taken_; // Counts stack samples taken.
788 };
789 
790 
791 } } // namespace v8::internal
792 
793 #endif // V8_PLATFORM_H_
byte * Address
Definition: globals.h:157
double fast_tan(double x)
const SwVfpRegister s2
const int kMinInt
Definition: globals.h:211
static void * GetThreadLocal(LocalStorageKey key)
static Semaphore * Create()
Definition: platform.h:637
static bool HasThreadLocal(LocalStorageKey key)
Definition: platform.h:502
int random()
static void Free(void *address, const size_t size)
virtual bool TryLock()=0
Thread(const Options &options)
PlatformData * platform_data()
Definition: platform.h:772
static int VSNPrintF(Vector< char > str, const char *format, va_list args)
static int64_t Ticks()
virtual void DoSampleStack(TickSample *sample)=0
static FILE * OpenTemporaryFile()
bool IsActive() const
Definition: platform.h:761
virtual void Run()=0
Isolate * isolate()
Definition: platform.h:763
static void SignalCodeMovingGC()
static void * GetRandomMmapAddr()
virtual bool SetReuseAddress(bool reuse_address)=0
virtual bool Listen(int backlog) const =0
double ceiling(double x)
static void * ReserveRegion(size_t size)
virtual bool Shutdown()=0
static bool IsOutsideAllocatedSpace(void *pointer)
static const char * LocalTimezone(double time)
double fast_sqrt(double input)
void TakeControl(VirtualMemory *from)
Definition: platform.h:418
void DecreaseProfilingDepth()
Definition: platform.h:758
static const int kStackWalkError
Definition: platform.h:245
static int GetUserTime(uint32_t *secs, uint32_t *usecs)
static const int kStackWalkMaxTextLen
Definition: platform.h:247
const int kMaxInt
Definition: globals.h:210
virtual int Receive(char *data, int len) const =0
TickSample * sample
virtual int Unlock()=0
#define ASSERT(condition)
Definition: checks.h:270
static void VFPrint(FILE *out, const char *format, va_list args)
int interval() const
Definition: platform.h:739
unsigned short uint16_t
Definition: unicode.cc:46
static Mutex * Create()
Definition: platform.h:568
virtual ~Mutex()
Definition: platform.h:550
double fast_sin(double x)
Address stack[kMaxFramesCount]
Definition: platform.h:728
static int GetThreadLocalInt(LocalStorageKey key)
Definition: platform.h:495
static MemoryMappedFile * open(const char *name)
virtual int Send(const char *data, int len) const =0
void NoBarrier_Store(volatile Atomic32 *ptr, Atomic32 value)
static const int kMinComplexMemCopy
Definition: platform.h:342
static void Abort()
void IncreaseProfilingDepth()
Definition: platform.h:757
static void ReleaseStore(volatile AtomicWord *ptr, AtomicWord value)
static void MemCopy(void *dest, const void *src, size_t size)
Definition: platform.h:339
bool IsProfiling() const
Definition: platform.h:756
static void ProtectCode(void *address, const size_t size)
static LocalStorageKey CreateThreadLocalKey()
static FILE * FOpen(const char *path, const char *mode)
static MemoryMappedFile * create(const char *name, int size, void *initial)
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName)
Definition: globals.h:318
double fast_log(double x)
bool Commit(void *address, size_t size, bool is_executable)
ScopedLock(Mutex *mutex)
Definition: platform.h:594
static void * GetExistingThreadLocal(LocalStorageKey key)
Definition: platform.h:514
static void VPrint(const char *format, va_list args)
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: globals.h:307
intptr_t AtomicWord
Definition: atomicops.h:75
static void Guard(void *address, const size_t size)
static void VPrintError(const char *format, va_list args)
double modulo(double x, double y)
static int GetCurrentProcessId()
static bool ArmCpuHasFeature(CpuFeature feature)
static uint16_t NToH(uint16_t value)
static Mutex * CreateMutex()
static double TimeCurrentMillis()
int samples_taken() const
Definition: platform.h:766
Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr, Atomic32 increment)
virtual Socket * Accept() const =0
static CpuImplementer GetCpuImplementer()
LazyDynamicInstance< Semaphore, CreateSemaphoreTrait< InitialValue >, ThreadSafeInitOnceTrait >::type type
Definition: platform.h:655
virtual bool Connect(const char *host, const char *port)=0
static uint16_t HToN(uint16_t value)
static bool MipsCpuHasFeature(CpuFeature feature)
static void DebugBreak()
activate correct semantics for inheriting readonliness false
Definition: flags.cc:141
static void DeleteThreadLocalKey(LocalStorageKey key)
static void Sleep(const int milliseconds)
LazyDynamicInstance< Mutex, CreateMutexTrait, ThreadSafeInitOnceTrait >::type LazyMutex
Definition: platform.h:583
static void Print(const char *format,...)
virtual bool IsValid() const =0
static void TearDown()
Atomic32 NoBarrier_Load(volatile const Atomic32 *ptr)
const SwVfpRegister s1
static int SNPrintF(Vector< char > str, const char *format,...)
virtual ~Socket()
Definition: platform.h:667
PlatformData * data()
Definition: platform.h:528
static Semaphore * CreateSemaphore(int count)
static const int kMaxThreadNameLength
Definition: platform.h:525
static const int kStackWalkMaxNameLen
Definition: platform.h:246
int signbit(double x)
static bool ReleaseRegion(void *base, size_t size)
static bool CommitRegion(void *base, size_t size, bool is_executable)
static double nan_value()
void ResetSamplesTaken()
Definition: platform.h:767
static const int kMaxFramesCount
Definition: platform.h:727
static void SetThreadLocal(LocalStorageKey key, void *value)
static void * Allocate(const size_t requested, size_t *allocated, bool is_executable)
static int StackWalk(Vector< StackFrame > frames)
static void PostSetUp()
virtual void Signal()=0
static void PrintError(const char *format,...)
void SampleStack(TickSample *sample)
Definition: platform.h:742
static bool UncommitRegion(void *base, size_t size)
static void LogSharedLibraryAddresses()
Options(const char *name, int stack_size=0)
Definition: platform.h:463
char text[kStackWalkMaxTextLen]
Definition: platform.h:250
static void SetUp()
void USE(T)
Definition: globals.h:289
static void StrNCpy(Vector< char > dest, const char *src, size_t n)
static int ActivationFrameAlignment()
virtual bool Bind(const int port)=0
const char * name() const
Definition: platform.h:466
virtual void Wait()=0
static double DaylightSavingsOffset(double time)
static size_t AllocateAlignment()
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if NULL
Definition: flags.cc:301
int32_t Atomic32
Definition: atomicops.h:57
Sampler(Isolate *isolate, int interval)
static uint64_t CpuFeaturesImpliedByPlatform()
virtual void Tick(TickSample *sample)=0
static bool Remove(const char *path)
static int GetLastError()
static intptr_t MaxVirtualMemory()
static void FPrint(FILE *out, const char *format,...)
double fast_cos(double x)
static double LocalTimeOffset()
virtual int Lock()=0
static bool ArmUsingHardFloat()
static intptr_t CommitPageSize()
static const char *const LogFileOpenMode
Definition: platform.h:186
static void SetThreadLocalInt(LocalStorageKey key, int value)
Definition: platform.h:499
PlatformData * data()
Definition: platform.h:770
static char * StrChr(char *str, int c)
static Socket * CreateSocket()
bool Uncommit(void *address, size_t size)
const char * name() const
Definition: platform.h:484