blob: 99deb1bef02394d97eaa2f687f10b16dbca8992b [file] [log] [blame]
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +00001// Copyright 2011 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
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//
ager@chromium.org32912102009-01-16 10:38:43 +000036// This design has been chosen because it is simple and fast. Alternatively,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037// 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
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000047#ifdef __sun
48# ifndef signbit
49int signbit(double x);
50# endif
51#endif
52
iposva@chromium.org245aa852009-02-10 00:49:54 +000053// GCC specific stuff
54#ifdef __GNUC__
ager@chromium.org3e875802009-06-29 08:26:34 +000055
56// Needed for va_list on at least MinGW and Android.
57#include <stdarg.h>
58
iposva@chromium.org245aa852009-02-10 00:49:54 +000059#define __GNUC_VERSION__ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060
iposva@chromium.org245aa852009-02-10 00:49:54 +000061#endif // __GNUC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000062
ricow@chromium.org55ee8072011-09-08 16:33:10 +000063
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
72int strncasecmp(const char* s1, const char* s2, int n);
73
74#endif // _MSC_VER
75
76// Random is missing on both Visual Studio and MinGW.
77int random();
78
79#endif // WIN32
80
kasperl@chromium.orga5551262010-12-07 12:49:48 +000081#include "atomicops.h"
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +000082#include "platform-tls.h"
ager@chromium.org5f0c45f2010-12-17 08:51:21 +000083#include "utils.h"
84#include "v8globals.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000085
kasperl@chromium.org71affb52009-05-26 05:44:31 +000086namespace v8 {
87namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000088
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000089// Use AtomicWord for a machine-sized pointer. It is assumed that
90// reads and writes of naturally aligned values of this type are atomic.
91typedef intptr_t AtomicWord;
92
ager@chromium.org3e875802009-06-29 08:26:34 +000093class Semaphore;
ager@chromium.org5f0c45f2010-12-17 08:51:21 +000094class Mutex;
ager@chromium.org3e875802009-06-29 08:26:34 +000095
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000096double ceiling(double x);
ager@chromium.org3811b432009-10-28 14:53:37 +000097double modulo(double x, double y);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000098
ager@chromium.org381abbb2009-02-25 13:23:22 +000099// Forward declarations.
100class Socket;
101
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000102// ----------------------------------------------------------------------------
103// OS
104//
105// This class has static methods for the different platform specific
106// functions. Add methods here to cope with differences between the
107// supported platforms.
108
109class OS {
110 public:
111 // Initializes the platform OS support. Called once at VM startup.
112 static void Setup();
113
114 // Returns the accumulated user time for thread. This routine
115 // can be used for profiling. The implementation should
116 // strive for high-precision timer resolution, preferable
117 // micro-second resolution.
118 static int GetUserTime(uint32_t* secs, uint32_t* usecs);
119
120 // Get a tick counter normalized to one tick per microsecond.
121 // Used for calculating time intervals.
122 static int64_t Ticks();
123
124 // Returns current time as the number of milliseconds since
125 // 00:00:00 UTC, January 1, 1970.
126 static double TimeCurrentMillis();
127
128 // Returns a string identifying the current time zone. The
129 // timestamp is used for determining if DST is in effect.
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000130 static const char* LocalTimezone(double time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000131
132 // Returns the local time offset in milliseconds east of UTC without
133 // taking daylight savings time into account.
134 static double LocalTimeOffset();
135
136 // Returns the daylight savings offset for the given time.
137 static double DaylightSavingsOffset(double time);
138
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000139 // Returns last OS error.
140 static int GetLastError();
141
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000142 static FILE* FOpen(const char* path, const char* mode);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000143 static bool Remove(const char* path);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000144
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000145 // Opens a temporary file, the file is auto removed on close.
146 static FILE* OpenTemporaryFile();
147
ager@chromium.org71daaf62009-04-01 07:22:49 +0000148 // Log file open mode is platform-dependent due to line ends issues.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000149 static const char* const LogFileOpenMode;
ager@chromium.org71daaf62009-04-01 07:22:49 +0000150
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000151 // Print output to console. This is mostly used for debugging output.
152 // On platforms that has standard terminal output, the output
153 // should go to stdout.
154 static void Print(const char* format, ...);
155 static void VPrint(const char* format, va_list args);
156
whesse@chromium.org023421e2010-12-21 12:19:12 +0000157 // Print output to a file. This is mostly used for debugging output.
158 static void FPrint(FILE* out, const char* format, ...);
159 static void VFPrint(FILE* out, const char* format, va_list args);
160
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000161 // Print error output to console. This is mostly used for error message
162 // output. On platforms that has standard terminal output, the output
163 // should go to stderr.
164 static void PrintError(const char* format, ...);
165 static void VPrintError(const char* format, va_list args);
166
ager@chromium.org32912102009-01-16 10:38:43 +0000167 // Allocate/Free memory used by JS heap. Pages are readable/writable, but
kasper.lund7276f142008-07-30 08:49:36 +0000168 // they are not guaranteed to be executable unless 'executable' is true.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000169 // Returns the address of allocated memory, or NULL if failed.
kasper.lund7276f142008-07-30 08:49:36 +0000170 static void* Allocate(const size_t requested,
171 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000172 bool is_executable);
173 static void Free(void* address, const size_t size);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000174
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000175 // Mark code segments non-writable.
176 static void ProtectCode(void* address, const size_t size);
177
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000178 // Assign memory as a guard page so that access will cause an exception.
179 static void Guard(void* address, const size_t size);
180
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000181 // Get the Alignment guaranteed by Allocate().
182 static size_t AllocateAlignment();
183
184 // Returns an indication of whether a pointer is in a space that
185 // has been allocated by Allocate(). This method may conservatively
186 // always return false, but giving more accurate information may
187 // improve the robustness of the stack dump code in the presence of
188 // heap corruption.
189 static bool IsOutsideAllocatedSpace(void* pointer);
190
ager@chromium.org32912102009-01-16 10:38:43 +0000191 // Sleep for a number of milliseconds.
192 static void Sleep(const int milliseconds);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193
194 // Abort the current process.
195 static void Abort();
196
kasper.lund7276f142008-07-30 08:49:36 +0000197 // Debug break.
198 static void DebugBreak();
199
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200 // Walk the stack.
201 static const int kStackWalkError = -1;
202 static const int kStackWalkMaxNameLen = 256;
203 static const int kStackWalkMaxTextLen = 256;
204 struct StackFrame {
205 void* address;
206 char text[kStackWalkMaxTextLen];
207 };
208
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000209 static int StackWalk(Vector<StackFrame> frames);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000210
211 // Factory method for creating platform dependent Mutex.
212 // Please use delete to reclaim the storage for the returned Mutex.
213 static Mutex* CreateMutex();
214
215 // Factory method for creating platform dependent Semaphore.
216 // Please use delete to reclaim the storage for the returned Semaphore.
217 static Semaphore* CreateSemaphore(int count);
218
ager@chromium.org381abbb2009-02-25 13:23:22 +0000219 // Factory method for creating platform dependent Socket.
220 // Please use delete to reclaim the storage for the returned Socket.
221 static Socket* CreateSocket();
222
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000223 class MemoryMappedFile {
224 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000225 static MemoryMappedFile* open(const char* name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226 static MemoryMappedFile* create(const char* name, int size, void* initial);
227 virtual ~MemoryMappedFile() { }
228 virtual void* memory() = 0;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000229 virtual int size() = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000230 };
231
kasper.lund7276f142008-07-30 08:49:36 +0000232 // Safe formatting print. Ensures that str is always null-terminated.
233 // Returns the number of chars written, or -1 if output was truncated.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000234 static int SNPrintF(Vector<char> str, const char* format, ...);
235 static int VSNPrintF(Vector<char> str,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236 const char* format,
237 va_list args);
238
ager@chromium.org381abbb2009-02-25 13:23:22 +0000239 static char* StrChr(char* str, int c);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000240 static void StrNCpy(Vector<char> dest, const char* src, size_t n);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000241
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000242 // Support for the profiler. Can do nothing, in which case ticks
243 // occuring in shared libraries will not be properly accounted for.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000244 static void LogSharedLibraryAddresses();
245
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000246 // Support for the profiler. Notifies the external profiling
247 // process that a code moving garbage collection starts. Can do
248 // nothing, in which case the code objects must not move (e.g., by
249 // using --never-compact) if accurate profiling is desired.
250 static void SignalCodeMovingGC();
251
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000252 // The return value indicates the CPU features we are sure of because of the
253 // OS. For example MacOSX doesn't run on any x86 CPUs that don't have SSE2
254 // instructions.
255 // This is a little messy because the interpretation is subject to the cross
256 // of the CPU and the OS. The bits in the answer correspond to the bit
257 // positions indicated by the members of the CpuFeature enum from globals.h
258 static uint64_t CpuFeaturesImpliedByPlatform();
259
lrn@chromium.orgac2828d2011-06-23 06:29:21 +0000260 // Maximum size of the virtual memory. 0 means there is no artificial
261 // limit.
262 static intptr_t MaxVirtualMemory();
263
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000264 // Returns the double constant NAN
265 static double nan_value();
266
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000267 // Support runtime detection of VFP3 on ARM CPUs.
268 static bool ArmCpuHasFeature(CpuFeature feature);
269
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000270 // Support runtime detection of whether the hard float option of the
271 // EABI is used.
272 static bool ArmUsingHardFloat();
273
lrn@chromium.org7516f052011-03-30 08:52:27 +0000274 // Support runtime detection of FPU on MIPS CPUs.
275 static bool MipsCpuHasFeature(CpuFeature feature);
276
ager@chromium.org236ad962008-09-25 09:45:57 +0000277 // Returns the activation frame alignment constraint or zero if
278 // the platform doesn't care. Guaranteed to be a power of two.
279 static int ActivationFrameAlignment();
280
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000281 static void ReleaseStore(volatile AtomicWord* ptr, AtomicWord value);
282
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000283#if defined(V8_TARGET_ARCH_IA32)
284 // Copy memory area to disjoint memory area.
285 static void MemCopy(void* dest, const void* src, size_t size);
286 // Limit below which the extra overhead of the MemCopy function is likely
287 // to outweigh the benefits of faster copying.
288 static const int kMinComplexMemCopy = 64;
289 typedef void (*MemCopyFunction)(void* dest, const void* src, size_t size);
290
291#else // V8_TARGET_ARCH_IA32
292 static void MemCopy(void* dest, const void* src, size_t size) {
293 memcpy(dest, src, size);
294 }
295 static const int kMinComplexMemCopy = 256;
296#endif // V8_TARGET_ARCH_IA32
297
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000298 private:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000299 static const int msPerSecond = 1000;
mads.s.ager31e71382008-08-13 09:32:07 +0000300
301 DISALLOW_IMPLICIT_CONSTRUCTORS(OS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000302};
303
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000304// Represents and controls an area of reserved memory.
305// Control of the reserved memory can be assigned to another VirtualMemory
306// object by assignment or copy-contructing. This removes the reserved memory
307// from the original object.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000308class VirtualMemory {
309 public:
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000310 // Empty VirtualMemory object, controlling no reserved memory.
311 VirtualMemory();
312
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313 // Reserves virtual memory with size.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000314 explicit VirtualMemory(size_t size);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000315
316 // Reserves virtual memory containing an area of the given size that
317 // is aligned per alignment. This may not be at the position returned
318 // by address().
319 VirtualMemory(size_t size, size_t alignment);
320
321 // Releases the reserved memory, if any, controlled by this VirtualMemory
322 // object.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323 ~VirtualMemory();
324
325 // Returns whether the memory has been reserved.
326 bool IsReserved();
327
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000328 // Initialize or resets an embedded VirtualMemory object.
329 void Reset();
330
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000331 // Returns the start address of the reserved memory.
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000332 // If the memory was reserved with an alignment, this address is not
333 // necessarily aligned. The user might need to round it up to a multiple of
334 // the alignment to get the start of the aligned block.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335 void* address() {
336 ASSERT(IsReserved());
337 return address_;
kmillikin@chromium.org3cdd9e12010-09-06 11:39:48 +0000338 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000340 // Returns the size of the reserved memory. The returned value is only
341 // meaningful when IsReserved() returns true.
342 // If the memory was reserved with an alignment, this size may be larger
343 // than the requested size.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000344 size_t size() { return size_; }
345
346 // Commits real memory. Returns whether the operation succeeded.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000347 bool Commit(void* address, size_t size, bool is_executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000348
349 // Uncommit real memory. Returns whether the operation succeeded.
350 bool Uncommit(void* address, size_t size);
351
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000352 void Release() {
353 ASSERT(IsReserved());
354 // Notice: Order is important here. The VirtualMemory object might live
355 // inside the allocated region.
356 void* address = address_;
357 size_t size = size_;
358 Reset();
359 bool result = ReleaseRegion(address, size);
360 USE(result);
361 ASSERT(result);
362 }
363
364 // Assign control of the reserved region to a different VirtualMemory object.
365 // The old object is no longer functional (IsReserved() returns false).
366 void TakeControl(VirtualMemory* from) {
367 ASSERT(!IsReserved());
368 address_ = from->address_;
369 size_ = from->size_;
370 from->Reset();
371 }
372
373 static void* ReserveRegion(size_t size);
374
375 static bool CommitRegion(void* base, size_t size, bool is_executable);
376
377 static bool UncommitRegion(void* base, size_t size);
378
379 // Must be called with a base pointer that has been returned by ReserveRegion
380 // and the same size it was reserved with.
381 static bool ReleaseRegion(void* base, size_t size);
382
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000383 private:
384 void* address_; // Start address of the virtual memory.
385 size_t size_; // Size of the virtual memory.
386};
387
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000388
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000389// ----------------------------------------------------------------------------
390// Thread
391//
392// Thread objects are used for creating and running threads. When the start()
393// method is called the new thread starts running the run() method in the new
394// thread. The Thread object should not be deallocated before the thread has
395// terminated.
396
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000397class Thread {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000398 public:
399 // Opaque data type for thread-local storage keys.
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000400 // LOCAL_STORAGE_KEY_MIN_VALUE and LOCAL_STORAGE_KEY_MAX_VALUE are specified
401 // to ensure that enumeration type has correct value range (see Issue 830 for
402 // more details).
403 enum LocalStorageKey {
404 LOCAL_STORAGE_KEY_MIN_VALUE = kMinInt,
405 LOCAL_STORAGE_KEY_MAX_VALUE = kMaxInt
406 };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000407
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000408 struct Options {
409 Options() : name("v8:<unknown>"), stack_size(0) {}
410
411 const char* name;
412 int stack_size;
413 };
414
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000415 // Create new thread.
416 explicit Thread(const Options& options);
417 explicit Thread(const char* name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418 virtual ~Thread();
419
420 // Start new thread by calling the Run() method in the new thread.
421 void Start();
422
423 // Wait until thread terminates.
424 void Join();
425
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000426 inline const char* name() const {
427 return name_;
428 }
429
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000430 // Abstract method for run handler.
431 virtual void Run() = 0;
432
433 // Thread-local storage.
434 static LocalStorageKey CreateThreadLocalKey();
435 static void DeleteThreadLocalKey(LocalStorageKey key);
436 static void* GetThreadLocal(LocalStorageKey key);
ager@chromium.org9085a012009-05-11 19:22:57 +0000437 static int GetThreadLocalInt(LocalStorageKey key) {
438 return static_cast<int>(reinterpret_cast<intptr_t>(GetThreadLocal(key)));
439 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000440 static void SetThreadLocal(LocalStorageKey key, void* value);
ager@chromium.org9085a012009-05-11 19:22:57 +0000441 static void SetThreadLocalInt(LocalStorageKey key, int value) {
442 SetThreadLocal(key, reinterpret_cast<void*>(static_cast<intptr_t>(value)));
443 }
444 static bool HasThreadLocal(LocalStorageKey key) {
445 return GetThreadLocal(key) != NULL;
446 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000447
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +0000448#ifdef V8_FAST_TLS_SUPPORTED
449 static inline void* GetExistingThreadLocal(LocalStorageKey key) {
450 void* result = reinterpret_cast<void*>(
451 InternalGetExistingThreadLocal(static_cast<intptr_t>(key)));
452 ASSERT(result == GetThreadLocal(key));
453 return result;
454 }
455#else
456 static inline void* GetExistingThreadLocal(LocalStorageKey key) {
457 return GetThreadLocal(key);
458 }
459#endif
460
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461 // A hint to the scheduler to let another thread run.
462 static void YieldCPU();
463
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000464
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000465 // The thread name length is limited to 16 based on Linux's implementation of
466 // prctl().
467 static const int kMaxThreadNameLength = 16;
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000468
469 class PlatformData;
470 PlatformData* data() { return data_; }
471
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472 private:
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000473 void set_name(const char *name);
474
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475 PlatformData* data_;
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000476
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000477 char name_[kMaxThreadNameLength];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000478 int stack_size_;
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000479
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000480 DISALLOW_COPY_AND_ASSIGN(Thread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000481};
482
483
484// ----------------------------------------------------------------------------
485// Mutex
486//
487// Mutexes are used for serializing access to non-reentrant sections of code.
488// The implementations of mutex should allow for nested/recursive locking.
489
490class Mutex {
491 public:
492 virtual ~Mutex() {}
493
494 // Locks the given mutex. If the mutex is currently unlocked, it becomes
495 // locked and owned by the calling thread, and immediately. If the mutex
496 // is already locked by another thread, suspends the calling thread until
497 // the mutex is unlocked.
498 virtual int Lock() = 0;
499
500 // Unlocks the given mutex. The mutex is assumed to be locked and owned by
501 // the calling thread on entrance.
502 virtual int Unlock() = 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000503
504 // Tries to lock the given mutex. Returns whether the mutex was
505 // successfully locked.
506 virtual bool TryLock() = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507};
508
509
510// ----------------------------------------------------------------------------
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000511// ScopedLock
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000512//
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000513// Stack-allocated ScopedLocks provide block-scoped locking and
514// unlocking of a mutex.
kasper.lund7276f142008-07-30 08:49:36 +0000515class ScopedLock {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000516 public:
kasper.lund7276f142008-07-30 08:49:36 +0000517 explicit ScopedLock(Mutex* mutex): mutex_(mutex) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000518 ASSERT(mutex_ != NULL);
kasper.lund7276f142008-07-30 08:49:36 +0000519 mutex_->Lock();
520 }
521 ~ScopedLock() {
522 mutex_->Unlock();
523 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524
525 private:
kasper.lund7276f142008-07-30 08:49:36 +0000526 Mutex* mutex_;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000527 DISALLOW_COPY_AND_ASSIGN(ScopedLock);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528};
529
530
531// ----------------------------------------------------------------------------
532// Semaphore
533//
534// A semaphore object is a synchronization object that maintains a count. The
535// count is decremented each time a thread completes a wait for the semaphore
536// object and incremented each time a thread signals the semaphore. When the
537// count reaches zero, threads waiting for the semaphore blocks until the
538// count becomes non-zero.
539
540class Semaphore {
541 public:
542 virtual ~Semaphore() {}
543
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000544 // Suspends the calling thread until the semaphore counter is non zero
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000545 // and then decrements the semaphore counter.
546 virtual void Wait() = 0;
547
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000548 // Suspends the calling thread until the counter is non zero or the timeout
549 // time has passsed. If timeout happens the return value is false and the
550 // counter is unchanged. Otherwise the semaphore counter is decremented and
551 // true is returned. The timeout value is specified in microseconds.
552 virtual bool Wait(int timeout) = 0;
553
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000554 // Increments the semaphore counter.
555 virtual void Signal() = 0;
556};
557
558
ager@chromium.org381abbb2009-02-25 13:23:22 +0000559// ----------------------------------------------------------------------------
560// Socket
561//
562
563class Socket {
564 public:
565 virtual ~Socket() {}
566
567 // Server initialization.
568 virtual bool Bind(const int port) = 0;
569 virtual bool Listen(int backlog) const = 0;
570 virtual Socket* Accept() const = 0;
571
572 // Client initialization.
573 virtual bool Connect(const char* host, const char* port) = 0;
574
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000575 // Shutdown socket for both read and write. This causes blocking Send and
576 // Receive calls to exit. After Shutdown the Socket object cannot be used for
577 // any communication.
578 virtual bool Shutdown() = 0;
579
ager@chromium.org381abbb2009-02-25 13:23:22 +0000580 // Data Transimission
581 virtual int Send(const char* data, int len) const = 0;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000582 virtual int Receive(char* data, int len) const = 0;
583
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000584 // Set the value of the SO_REUSEADDR socket option.
585 virtual bool SetReuseAddress(bool reuse_address) = 0;
586
ager@chromium.org381abbb2009-02-25 13:23:22 +0000587 virtual bool IsValid() const = 0;
588
589 static bool Setup();
590 static int LastError();
591 static uint16_t HToN(uint16_t value);
592 static uint16_t NToH(uint16_t value);
593 static uint32_t HToN(uint32_t value);
594 static uint32_t NToH(uint32_t value);
595};
596
597
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598// ----------------------------------------------------------------------------
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000599// Sampler
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000600//
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000601// A sampler periodically samples the state of the VM and optionally
602// (if used for profiling) the program counter and stack pointer for
603// the thread that created it.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000605// TickSample captures the information collected for each sample.
606class TickSample {
607 public:
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000608 TickSample()
ager@chromium.org357bf652010-04-12 11:30:10 +0000609 : state(OTHER),
610 pc(NULL),
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000611 sp(NULL),
612 fp(NULL),
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000613 tos(NULL),
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000614 frames_count(0),
615 has_external_callback(false) {}
ager@chromium.org357bf652010-04-12 11:30:10 +0000616 StateTag state; // The state of the VM.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000617 Address pc; // Instruction pointer.
618 Address sp; // Stack pointer.
619 Address fp; // Frame pointer.
620 union {
621 Address tos; // Top stack value (*sp).
622 Address external_callback;
623 };
lrn@chromium.org25156de2010-04-06 13:10:27 +0000624 static const int kMaxFramesCount = 64;
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000625 Address stack[kMaxFramesCount]; // Call stack.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000626 int frames_count : 8; // Number of captured frames.
627 bool has_external_callback : 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000628};
629
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000630class Sampler {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631 public:
632 // Initialize sampler.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000633 Sampler(Isolate* isolate, int interval);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000634 virtual ~Sampler();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000635
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000636 int interval() const { return interval_; }
637
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000638 // Performs stack sampling.
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000639 void SampleStack(TickSample* sample) {
640 DoSampleStack(sample);
641 IncSamplesTaken();
642 }
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000643
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000644 // This method is called for each sampling period with the current
645 // program counter.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000646 virtual void Tick(TickSample* sample) = 0;
647
648 // Start and stop sampler.
649 void Start();
650 void Stop();
651
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000652 // Is the sampler used for profiling?
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000653 bool IsProfiling() const { return NoBarrier_Load(&profiling_) > 0; }
654 void IncreaseProfilingDepth() { NoBarrier_AtomicIncrement(&profiling_, 1); }
655 void DecreaseProfilingDepth() { NoBarrier_AtomicIncrement(&profiling_, -1); }
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000656
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000657 // Whether the sampler is running (that is, consumes resources).
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000658 bool IsActive() const { return NoBarrier_Load(&active_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000659
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000660 Isolate* isolate() { return isolate_; }
661
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000662 // Used in tests to make sure that stack sampling is performed.
663 int samples_taken() const { return samples_taken_; }
664 void ResetSamplesTaken() { samples_taken_ = 0; }
665
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000666 class PlatformData;
ricow@chromium.orgbadaffc2011-03-17 12:15:27 +0000667 PlatformData* data() { return data_; }
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000668
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000669 PlatformData* platform_data() { return data_; }
670
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000671 protected:
672 virtual void DoSampleStack(TickSample* sample) = 0;
673
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000674 private:
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000675 void SetActive(bool value) { NoBarrier_Store(&active_, value); }
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000676 void IncSamplesTaken() { if (++samples_taken_ < 0) samples_taken_ = 0; }
677
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000678 Isolate* isolate_;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000679 const int interval_;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000680 Atomic32 profiling_;
681 Atomic32 active_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000682 PlatformData* data_; // Platform specific data.
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000683 int samples_taken_; // Counts stack samples taken.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000684 DISALLOW_IMPLICIT_CONSTRUCTORS(Sampler);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000685};
686
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000687
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000688} } // namespace v8::internal
689
690#endif // V8_PLATFORM_H_