blob: 14f4551f372e2c5faed9e9f8312ad1ab84a0c519 [file] [log] [blame]
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001// Copyright 2012 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"
jkummerow@chromium.org1456e702012-03-30 08:38:13 +000082#include "lazy-instance.h"
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +000083#include "platform-tls.h"
ager@chromium.org5f0c45f2010-12-17 08:51:21 +000084#include "utils.h"
85#include "v8globals.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000086
kasperl@chromium.org71affb52009-05-26 05:44:31 +000087namespace v8 {
88namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000089
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000090// Use AtomicWord for a machine-sized pointer. It is assumed that
91// reads and writes of naturally aligned values of this type are atomic.
92typedef intptr_t AtomicWord;
93
ager@chromium.org3e875802009-06-29 08:26:34 +000094class Semaphore;
ager@chromium.org5f0c45f2010-12-17 08:51:21 +000095class Mutex;
ager@chromium.org3e875802009-06-29 08:26:34 +000096
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097double ceiling(double x);
ager@chromium.org3811b432009-10-28 14:53:37 +000098double modulo(double x, double y);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000099
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000100// Custom implementation of sin, cos, tan and log.
101double fast_sin(double input);
102double fast_cos(double input);
103double fast_tan(double input);
104double fast_log(double input);
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000105double fast_sqrt(double input);
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000106
ager@chromium.org381abbb2009-02-25 13:23:22 +0000107// Forward declarations.
108class Socket;
109
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000110// ----------------------------------------------------------------------------
111// OS
112//
113// This class has static methods for the different platform specific
114// functions. Add methods here to cope with differences between the
115// supported platforms.
116
117class OS {
118 public:
119 // Initializes the platform OS support. Called once at VM startup.
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000120 static void SetUp();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000121
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000122 // Initializes the platform OS support that depend on CPU features. This is
123 // called after CPU initialization.
124 static void PostSetUp();
125
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000126 // Clean up platform-OS-related things. Called once at VM shutdown.
127 static void TearDown();
128
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129 // Returns the accumulated user time for thread. This routine
130 // can be used for profiling. The implementation should
131 // strive for high-precision timer resolution, preferable
132 // micro-second resolution.
133 static int GetUserTime(uint32_t* secs, uint32_t* usecs);
134
135 // Get a tick counter normalized to one tick per microsecond.
136 // Used for calculating time intervals.
137 static int64_t Ticks();
138
139 // Returns current time as the number of milliseconds since
140 // 00:00:00 UTC, January 1, 1970.
141 static double TimeCurrentMillis();
142
143 // Returns a string identifying the current time zone. The
144 // timestamp is used for determining if DST is in effect.
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000145 static const char* LocalTimezone(double time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000146
147 // Returns the local time offset in milliseconds east of UTC without
148 // taking daylight savings time into account.
149 static double LocalTimeOffset();
150
151 // Returns the daylight savings offset for the given time.
152 static double DaylightSavingsOffset(double time);
153
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000154 // Returns last OS error.
155 static int GetLastError();
156
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000157 static FILE* FOpen(const char* path, const char* mode);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000158 static bool Remove(const char* path);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000159
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000160 // Opens a temporary file, the file is auto removed on close.
161 static FILE* OpenTemporaryFile();
162
ager@chromium.org71daaf62009-04-01 07:22:49 +0000163 // Log file open mode is platform-dependent due to line ends issues.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000164 static const char* const LogFileOpenMode;
ager@chromium.org71daaf62009-04-01 07:22:49 +0000165
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000166 // Print output to console. This is mostly used for debugging output.
167 // On platforms that has standard terminal output, the output
168 // should go to stdout.
169 static void Print(const char* format, ...);
170 static void VPrint(const char* format, va_list args);
171
whesse@chromium.org023421e2010-12-21 12:19:12 +0000172 // Print output to a file. This is mostly used for debugging output.
173 static void FPrint(FILE* out, const char* format, ...);
174 static void VFPrint(FILE* out, const char* format, va_list args);
175
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000176 // Print error output to console. This is mostly used for error message
177 // output. On platforms that has standard terminal output, the output
178 // should go to stderr.
179 static void PrintError(const char* format, ...);
180 static void VPrintError(const char* format, va_list args);
181
ager@chromium.org32912102009-01-16 10:38:43 +0000182 // Allocate/Free memory used by JS heap. Pages are readable/writable, but
kasper.lund7276f142008-07-30 08:49:36 +0000183 // they are not guaranteed to be executable unless 'executable' is true.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000184 // Returns the address of allocated memory, or NULL if failed.
kasper.lund7276f142008-07-30 08:49:36 +0000185 static void* Allocate(const size_t requested,
186 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000187 bool is_executable);
188 static void Free(void* address, const size_t size);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000189
ricow@chromium.org64e3a4b2011-12-13 08:07:27 +0000190 // This is the granularity at which the ProtectCode(...) call can set page
191 // permissions.
192 static intptr_t CommitPageSize();
193
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000194 // Mark code segments non-writable.
195 static void ProtectCode(void* address, const size_t size);
196
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000197 // Assign memory as a guard page so that access will cause an exception.
198 static void Guard(void* address, const size_t size);
199
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000200 // Generate a random address to be used for hinting mmap().
201 static void* GetRandomMmapAddr();
202
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000203 // Get the Alignment guaranteed by Allocate().
204 static size_t AllocateAlignment();
205
206 // Returns an indication of whether a pointer is in a space that
207 // has been allocated by Allocate(). This method may conservatively
208 // always return false, but giving more accurate information may
209 // improve the robustness of the stack dump code in the presence of
210 // heap corruption.
211 static bool IsOutsideAllocatedSpace(void* pointer);
212
ager@chromium.org32912102009-01-16 10:38:43 +0000213 // Sleep for a number of milliseconds.
214 static void Sleep(const int milliseconds);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000215
216 // Abort the current process.
217 static void Abort();
218
kasper.lund7276f142008-07-30 08:49:36 +0000219 // Debug break.
220 static void DebugBreak();
221
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222 // Walk the stack.
223 static const int kStackWalkError = -1;
224 static const int kStackWalkMaxNameLen = 256;
225 static const int kStackWalkMaxTextLen = 256;
226 struct StackFrame {
227 void* address;
228 char text[kStackWalkMaxTextLen];
229 };
230
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000231 static int StackWalk(Vector<StackFrame> frames);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000232
233 // Factory method for creating platform dependent Mutex.
234 // Please use delete to reclaim the storage for the returned Mutex.
235 static Mutex* CreateMutex();
236
237 // Factory method for creating platform dependent Semaphore.
238 // Please use delete to reclaim the storage for the returned Semaphore.
239 static Semaphore* CreateSemaphore(int count);
240
ager@chromium.org381abbb2009-02-25 13:23:22 +0000241 // Factory method for creating platform dependent Socket.
242 // Please use delete to reclaim the storage for the returned Socket.
243 static Socket* CreateSocket();
244
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245 class MemoryMappedFile {
246 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000247 static MemoryMappedFile* open(const char* name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000248 static MemoryMappedFile* create(const char* name, int size, void* initial);
249 virtual ~MemoryMappedFile() { }
250 virtual void* memory() = 0;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000251 virtual int size() = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252 };
253
kasper.lund7276f142008-07-30 08:49:36 +0000254 // Safe formatting print. Ensures that str is always null-terminated.
255 // Returns the number of chars written, or -1 if output was truncated.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000256 static int SNPrintF(Vector<char> str, const char* format, ...);
257 static int VSNPrintF(Vector<char> str,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000258 const char* format,
259 va_list args);
260
ager@chromium.org381abbb2009-02-25 13:23:22 +0000261 static char* StrChr(char* str, int c);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000262 static void StrNCpy(Vector<char> dest, const char* src, size_t n);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000263
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000264 // Support for the profiler. Can do nothing, in which case ticks
265 // occuring in shared libraries will not be properly accounted for.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000266 static void LogSharedLibraryAddresses();
267
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000268 // Support for the profiler. Notifies the external profiling
269 // process that a code moving garbage collection starts. Can do
270 // nothing, in which case the code objects must not move (e.g., by
271 // using --never-compact) if accurate profiling is desired.
272 static void SignalCodeMovingGC();
273
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000274 // The return value indicates the CPU features we are sure of because of the
275 // OS. For example MacOSX doesn't run on any x86 CPUs that don't have SSE2
276 // instructions.
277 // This is a little messy because the interpretation is subject to the cross
278 // of the CPU and the OS. The bits in the answer correspond to the bit
279 // positions indicated by the members of the CpuFeature enum from globals.h
280 static uint64_t CpuFeaturesImpliedByPlatform();
281
lrn@chromium.orgac2828d2011-06-23 06:29:21 +0000282 // Maximum size of the virtual memory. 0 means there is no artificial
283 // limit.
284 static intptr_t MaxVirtualMemory();
285
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000286 // Returns the double constant NAN
287 static double nan_value();
288
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000289 // Support runtime detection of VFP3 on ARM CPUs.
290 static bool ArmCpuHasFeature(CpuFeature feature);
291
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000292 // Support runtime detection of whether the hard float option of the
293 // EABI is used.
294 static bool ArmUsingHardFloat();
295
lrn@chromium.org7516f052011-03-30 08:52:27 +0000296 // Support runtime detection of FPU on MIPS CPUs.
297 static bool MipsCpuHasFeature(CpuFeature feature);
298
ager@chromium.org236ad962008-09-25 09:45:57 +0000299 // Returns the activation frame alignment constraint or zero if
300 // the platform doesn't care. Guaranteed to be a power of two.
301 static int ActivationFrameAlignment();
302
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000303 static void ReleaseStore(volatile AtomicWord* ptr, AtomicWord value);
304
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000305#if defined(V8_TARGET_ARCH_IA32)
306 // Copy memory area to disjoint memory area.
307 static void MemCopy(void* dest, const void* src, size_t size);
308 // Limit below which the extra overhead of the MemCopy function is likely
309 // to outweigh the benefits of faster copying.
310 static const int kMinComplexMemCopy = 64;
311 typedef void (*MemCopyFunction)(void* dest, const void* src, size_t size);
312
313#else // V8_TARGET_ARCH_IA32
314 static void MemCopy(void* dest, const void* src, size_t size) {
315 memcpy(dest, src, size);
316 }
317 static const int kMinComplexMemCopy = 256;
318#endif // V8_TARGET_ARCH_IA32
319
rossberg@chromium.org657d53b2012-07-12 11:06:03 +0000320 static int GetCurrentProcessId();
321
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000322 private:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323 static const int msPerSecond = 1000;
mads.s.ager31e71382008-08-13 09:32:07 +0000324
325 DISALLOW_IMPLICIT_CONSTRUCTORS(OS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000326};
327
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000328// Represents and controls an area of reserved memory.
329// Control of the reserved memory can be assigned to another VirtualMemory
330// object by assignment or copy-contructing. This removes the reserved memory
331// from the original object.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000332class VirtualMemory {
333 public:
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000334 // Empty VirtualMemory object, controlling no reserved memory.
335 VirtualMemory();
336
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000337 // Reserves virtual memory with size.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000338 explicit VirtualMemory(size_t size);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000339
340 // Reserves virtual memory containing an area of the given size that
341 // is aligned per alignment. This may not be at the position returned
342 // by address().
343 VirtualMemory(size_t size, size_t alignment);
344
345 // Releases the reserved memory, if any, controlled by this VirtualMemory
346 // object.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000347 ~VirtualMemory();
348
349 // Returns whether the memory has been reserved.
350 bool IsReserved();
351
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000352 // Initialize or resets an embedded VirtualMemory object.
353 void Reset();
354
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 // Returns the start address of the reserved memory.
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000356 // If the memory was reserved with an alignment, this address is not
357 // necessarily aligned. The user might need to round it up to a multiple of
358 // the alignment to get the start of the aligned block.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000359 void* address() {
360 ASSERT(IsReserved());
361 return address_;
kmillikin@chromium.org3cdd9e12010-09-06 11:39:48 +0000362 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000363
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000364 // Returns the size of the reserved memory. The returned value is only
365 // meaningful when IsReserved() returns true.
366 // If the memory was reserved with an alignment, this size may be larger
367 // than the requested size.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368 size_t size() { return size_; }
369
370 // Commits real memory. Returns whether the operation succeeded.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000371 bool Commit(void* address, size_t size, bool is_executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000372
373 // Uncommit real memory. Returns whether the operation succeeded.
374 bool Uncommit(void* address, size_t size);
375
yangguo@chromium.orgab30bb82012-02-24 14:41:46 +0000376 // Creates a single guard page at the given address.
377 bool Guard(void* address);
378
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000379 void Release() {
380 ASSERT(IsReserved());
381 // Notice: Order is important here. The VirtualMemory object might live
382 // inside the allocated region.
383 void* address = address_;
384 size_t size = size_;
385 Reset();
386 bool result = ReleaseRegion(address, size);
387 USE(result);
388 ASSERT(result);
389 }
390
391 // Assign control of the reserved region to a different VirtualMemory object.
392 // The old object is no longer functional (IsReserved() returns false).
393 void TakeControl(VirtualMemory* from) {
394 ASSERT(!IsReserved());
395 address_ = from->address_;
396 size_ = from->size_;
397 from->Reset();
398 }
399
400 static void* ReserveRegion(size_t size);
401
402 static bool CommitRegion(void* base, size_t size, bool is_executable);
403
404 static bool UncommitRegion(void* base, size_t size);
405
406 // Must be called with a base pointer that has been returned by ReserveRegion
407 // and the same size it was reserved with.
408 static bool ReleaseRegion(void* base, size_t size);
409
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410 private:
411 void* address_; // Start address of the virtual memory.
412 size_t size_; // Size of the virtual memory.
413};
414
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000415
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000416// ----------------------------------------------------------------------------
417// Thread
418//
419// Thread objects are used for creating and running threads. When the start()
420// method is called the new thread starts running the run() method in the new
421// thread. The Thread object should not be deallocated before the thread has
422// terminated.
423
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000424class Thread {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000425 public:
426 // Opaque data type for thread-local storage keys.
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000427 // LOCAL_STORAGE_KEY_MIN_VALUE and LOCAL_STORAGE_KEY_MAX_VALUE are specified
428 // to ensure that enumeration type has correct value range (see Issue 830 for
429 // more details).
430 enum LocalStorageKey {
431 LOCAL_STORAGE_KEY_MIN_VALUE = kMinInt,
432 LOCAL_STORAGE_KEY_MAX_VALUE = kMaxInt
433 };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000434
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000435 class Options {
436 public:
437 Options() : name_("v8:<unknown>"), stack_size_(0) {}
438 Options(const char* name, int stack_size = 0)
439 : name_(name), stack_size_(stack_size) {}
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000440
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000441 const char* name() const { return name_; }
442 int stack_size() const { return stack_size_; }
443
444 private:
445 const char* name_;
446 int stack_size_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000447 };
448
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000449 // Create new thread.
450 explicit Thread(const Options& options);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000451 virtual ~Thread();
452
453 // Start new thread by calling the Run() method in the new thread.
454 void Start();
455
456 // Wait until thread terminates.
457 void Join();
458
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000459 inline const char* name() const {
460 return name_;
461 }
462
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000463 // Abstract method for run handler.
464 virtual void Run() = 0;
465
466 // Thread-local storage.
467 static LocalStorageKey CreateThreadLocalKey();
468 static void DeleteThreadLocalKey(LocalStorageKey key);
469 static void* GetThreadLocal(LocalStorageKey key);
ager@chromium.org9085a012009-05-11 19:22:57 +0000470 static int GetThreadLocalInt(LocalStorageKey key) {
471 return static_cast<int>(reinterpret_cast<intptr_t>(GetThreadLocal(key)));
472 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473 static void SetThreadLocal(LocalStorageKey key, void* value);
ager@chromium.org9085a012009-05-11 19:22:57 +0000474 static void SetThreadLocalInt(LocalStorageKey key, int value) {
475 SetThreadLocal(key, reinterpret_cast<void*>(static_cast<intptr_t>(value)));
476 }
477 static bool HasThreadLocal(LocalStorageKey key) {
478 return GetThreadLocal(key) != NULL;
479 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +0000481#ifdef V8_FAST_TLS_SUPPORTED
482 static inline void* GetExistingThreadLocal(LocalStorageKey key) {
483 void* result = reinterpret_cast<void*>(
484 InternalGetExistingThreadLocal(static_cast<intptr_t>(key)));
485 ASSERT(result == GetThreadLocal(key));
486 return result;
487 }
488#else
489 static inline void* GetExistingThreadLocal(LocalStorageKey key) {
490 return GetThreadLocal(key);
491 }
492#endif
493
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000494 // A hint to the scheduler to let another thread run.
495 static void YieldCPU();
496
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000497
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000498 // The thread name length is limited to 16 based on Linux's implementation of
499 // prctl().
500 static const int kMaxThreadNameLength = 16;
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000501
502 class PlatformData;
503 PlatformData* data() { return data_; }
504
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000505 private:
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000506 void set_name(const char* name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000507
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000508 PlatformData* data_;
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000509
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000510 char name_[kMaxThreadNameLength];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000511 int stack_size_;
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000512
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000513 DISALLOW_COPY_AND_ASSIGN(Thread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514};
515
516
517// ----------------------------------------------------------------------------
518// Mutex
519//
520// Mutexes are used for serializing access to non-reentrant sections of code.
521// The implementations of mutex should allow for nested/recursive locking.
522
523class Mutex {
524 public:
525 virtual ~Mutex() {}
526
527 // Locks the given mutex. If the mutex is currently unlocked, it becomes
528 // locked and owned by the calling thread, and immediately. If the mutex
529 // is already locked by another thread, suspends the calling thread until
530 // the mutex is unlocked.
531 virtual int Lock() = 0;
532
533 // Unlocks the given mutex. The mutex is assumed to be locked and owned by
534 // the calling thread on entrance.
535 virtual int Unlock() = 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000536
537 // Tries to lock the given mutex. Returns whether the mutex was
538 // successfully locked.
539 virtual bool TryLock() = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000540};
541
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000542struct CreateMutexTrait {
543 static Mutex* Create() {
544 return OS::CreateMutex();
545 }
546};
547
548// POD Mutex initialized lazily (i.e. the first time Pointer() is called).
549// Usage:
550// static LazyMutex my_mutex = LAZY_MUTEX_INITIALIZER;
551//
552// void my_function() {
553// ScopedLock my_lock(my_mutex.Pointer());
554// // Do something.
555// }
556//
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000557typedef LazyDynamicInstance<
558 Mutex, CreateMutexTrait, ThreadSafeInitOnceTrait>::type LazyMutex;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000559
560#define LAZY_MUTEX_INITIALIZER LAZY_DYNAMIC_INSTANCE_INITIALIZER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000561
562// ----------------------------------------------------------------------------
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000563// ScopedLock
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564//
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000565// Stack-allocated ScopedLocks provide block-scoped locking and
566// unlocking of a mutex.
kasper.lund7276f142008-07-30 08:49:36 +0000567class ScopedLock {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 public:
kasper.lund7276f142008-07-30 08:49:36 +0000569 explicit ScopedLock(Mutex* mutex): mutex_(mutex) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000570 ASSERT(mutex_ != NULL);
kasper.lund7276f142008-07-30 08:49:36 +0000571 mutex_->Lock();
572 }
573 ~ScopedLock() {
574 mutex_->Unlock();
575 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576
577 private:
kasper.lund7276f142008-07-30 08:49:36 +0000578 Mutex* mutex_;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000579 DISALLOW_COPY_AND_ASSIGN(ScopedLock);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000580};
581
582
583// ----------------------------------------------------------------------------
584// Semaphore
585//
586// A semaphore object is a synchronization object that maintains a count. The
587// count is decremented each time a thread completes a wait for the semaphore
588// object and incremented each time a thread signals the semaphore. When the
589// count reaches zero, threads waiting for the semaphore blocks until the
590// count becomes non-zero.
591
592class Semaphore {
593 public:
594 virtual ~Semaphore() {}
595
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000596 // Suspends the calling thread until the semaphore counter is non zero
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597 // and then decrements the semaphore counter.
598 virtual void Wait() = 0;
599
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000600 // Suspends the calling thread until the counter is non zero or the timeout
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000601 // time has passed. If timeout happens the return value is false and the
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000602 // counter is unchanged. Otherwise the semaphore counter is decremented and
603 // true is returned. The timeout value is specified in microseconds.
604 virtual bool Wait(int timeout) = 0;
605
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606 // Increments the semaphore counter.
607 virtual void Signal() = 0;
608};
609
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000610template <int InitialValue>
611struct CreateSemaphoreTrait {
612 static Semaphore* Create() {
613 return OS::CreateSemaphore(InitialValue);
614 }
615};
616
617// POD Semaphore initialized lazily (i.e. the first time Pointer() is called).
618// Usage:
619// // The following semaphore starts at 0.
620// static LazySemaphore<0>::type my_semaphore = LAZY_SEMAPHORE_INITIALIZER;
621//
622// void my_function() {
623// // Do something with my_semaphore.Pointer().
624// }
625//
626template <int InitialValue>
627struct LazySemaphore {
628 typedef typename LazyDynamicInstance<
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000629 Semaphore, CreateSemaphoreTrait<InitialValue>,
630 ThreadSafeInitOnceTrait>::type type;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000631};
632
633#define LAZY_SEMAPHORE_INITIALIZER LAZY_DYNAMIC_INSTANCE_INITIALIZER
634
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000635
ager@chromium.org381abbb2009-02-25 13:23:22 +0000636// ----------------------------------------------------------------------------
637// Socket
638//
639
640class Socket {
641 public:
642 virtual ~Socket() {}
643
644 // Server initialization.
645 virtual bool Bind(const int port) = 0;
646 virtual bool Listen(int backlog) const = 0;
647 virtual Socket* Accept() const = 0;
648
649 // Client initialization.
650 virtual bool Connect(const char* host, const char* port) = 0;
651
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000652 // Shutdown socket for both read and write. This causes blocking Send and
653 // Receive calls to exit. After Shutdown the Socket object cannot be used for
654 // any communication.
655 virtual bool Shutdown() = 0;
656
ager@chromium.org381abbb2009-02-25 13:23:22 +0000657 // Data Transimission
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +0000658 // Return 0 on failure.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000659 virtual int Send(const char* data, int len) const = 0;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000660 virtual int Receive(char* data, int len) const = 0;
661
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000662 // Set the value of the SO_REUSEADDR socket option.
663 virtual bool SetReuseAddress(bool reuse_address) = 0;
664
ager@chromium.org381abbb2009-02-25 13:23:22 +0000665 virtual bool IsValid() const = 0;
666
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000667 static bool SetUp();
ager@chromium.org381abbb2009-02-25 13:23:22 +0000668 static int LastError();
669 static uint16_t HToN(uint16_t value);
670 static uint16_t NToH(uint16_t value);
671 static uint32_t HToN(uint32_t value);
672 static uint32_t NToH(uint32_t value);
673};
674
675
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000676// ----------------------------------------------------------------------------
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000677// Sampler
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678//
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000679// A sampler periodically samples the state of the VM and optionally
680// (if used for profiling) the program counter and stack pointer for
681// the thread that created it.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000682
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000683// TickSample captures the information collected for each sample.
684class TickSample {
685 public:
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000686 TickSample()
ager@chromium.org357bf652010-04-12 11:30:10 +0000687 : state(OTHER),
688 pc(NULL),
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000689 sp(NULL),
690 fp(NULL),
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000691 tos(NULL),
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000692 frames_count(0),
693 has_external_callback(false) {}
ager@chromium.org357bf652010-04-12 11:30:10 +0000694 StateTag state; // The state of the VM.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000695 Address pc; // Instruction pointer.
696 Address sp; // Stack pointer.
697 Address fp; // Frame pointer.
698 union {
699 Address tos; // Top stack value (*sp).
700 Address external_callback;
701 };
lrn@chromium.org25156de2010-04-06 13:10:27 +0000702 static const int kMaxFramesCount = 64;
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000703 Address stack[kMaxFramesCount]; // Call stack.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000704 int frames_count : 8; // Number of captured frames.
705 bool has_external_callback : 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706};
707
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000708class Sampler {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000709 public:
710 // Initialize sampler.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000711 Sampler(Isolate* isolate, int interval);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000712 virtual ~Sampler();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000714 int interval() const { return interval_; }
715
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000716 // Performs stack sampling.
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000717 void SampleStack(TickSample* sample) {
718 DoSampleStack(sample);
719 IncSamplesTaken();
720 }
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000721
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000722 // This method is called for each sampling period with the current
723 // program counter.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000724 virtual void Tick(TickSample* sample) = 0;
725
726 // Start and stop sampler.
727 void Start();
728 void Stop();
729
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000730 // Is the sampler used for profiling?
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000731 bool IsProfiling() const { return NoBarrier_Load(&profiling_) > 0; }
732 void IncreaseProfilingDepth() { NoBarrier_AtomicIncrement(&profiling_, 1); }
733 void DecreaseProfilingDepth() { NoBarrier_AtomicIncrement(&profiling_, -1); }
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000734
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000735 // Whether the sampler is running (that is, consumes resources).
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000736 bool IsActive() const { return NoBarrier_Load(&active_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000737
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000738 Isolate* isolate() { return isolate_; }
739
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000740 // Used in tests to make sure that stack sampling is performed.
741 int samples_taken() const { return samples_taken_; }
742 void ResetSamplesTaken() { samples_taken_ = 0; }
743
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000744 class PlatformData;
ricow@chromium.orgbadaffc2011-03-17 12:15:27 +0000745 PlatformData* data() { return data_; }
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000746
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000747 PlatformData* platform_data() { return data_; }
748
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000749 protected:
750 virtual void DoSampleStack(TickSample* sample) = 0;
751
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000752 private:
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000753 void SetActive(bool value) { NoBarrier_Store(&active_, value); }
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000754 void IncSamplesTaken() { if (++samples_taken_ < 0) samples_taken_ = 0; }
755
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000756 Isolate* isolate_;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000757 const int interval_;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000758 Atomic32 profiling_;
759 Atomic32 active_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000760 PlatformData* data_; // Platform specific data.
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000761 int samples_taken_; // Counts stack samples taken.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000762 DISALLOW_IMPLICIT_CONSTRUCTORS(Sampler);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000763};
764
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000765
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766} } // namespace v8::internal
767
768#endif // V8_PLATFORM_H_