blob: 27754533a3edc8f04e4d02e588128d30e4e709ea [file] [log] [blame]
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +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// Platform specific code for Win32.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000029
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +000030// Secure API functions are not available using MinGW with msvcrt.dll
31// on Windows XP. Make sure MINGW_HAS_SECURE_API is not defined to
32// disable definition of secure API functions in standard headers that
33// would conflict with our own implementation.
34#ifdef __MINGW32__
35#include <_mingw.h>
36#ifdef MINGW_HAS_SECURE_API
37#undef MINGW_HAS_SECURE_API
38#endif // MINGW_HAS_SECURE_API
39#endif // __MINGW32__
40
kasperl@chromium.orga5551262010-12-07 12:49:48 +000041#include "win32-headers.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000042
43#include "v8.h"
44
ulan@chromium.org9a21ec42012-03-06 08:42:24 +000045#include "codegen.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046#include "platform.h"
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +000047#include "simulator.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000048#include "vm-state-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049
iposva@chromium.org245aa852009-02-10 00:49:54 +000050#ifdef _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052// Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
53// defined in strings.h.
54int strncasecmp(const char* s1, const char* s2, int n) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000055 return _strnicmp(s1, s2, n);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000056}
57
iposva@chromium.org245aa852009-02-10 00:49:54 +000058#endif // _MSC_VER
59
60
61// Extra functions for MinGW. Most of these are the _s functions which are in
62// the Microsoft Visual Studio C++ CRT.
63#ifdef __MINGW32__
64
svenpanne@chromium.orgfb046332012-04-19 12:02:44 +000065
66#ifndef __MINGW64_VERSION_MAJOR
67
68#define _TRUNCATE 0
69#define STRUNCATE 80
70
71inline void MemoryBarrier() {
72 int barrier = 0;
73 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
74}
75
76#endif // __MINGW64_VERSION_MAJOR
77
78
iposva@chromium.org245aa852009-02-10 00:49:54 +000079int localtime_s(tm* out_tm, const time_t* time) {
80 tm* posix_local_time_struct = localtime(time);
81 if (posix_local_time_struct == NULL) return 1;
82 *out_tm = *posix_local_time_struct;
83 return 0;
84}
85
86
iposva@chromium.org245aa852009-02-10 00:49:54 +000087int fopen_s(FILE** pFile, const char* filename, const char* mode) {
88 *pFile = fopen(filename, mode);
89 return *pFile != NULL ? 0 : 1;
90}
91
iposva@chromium.org245aa852009-02-10 00:49:54 +000092int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
93 const char* format, va_list argptr) {
sgjesse@chromium.org6db88712011-07-11 11:41:22 +000094 ASSERT(count == _TRUNCATE);
iposva@chromium.org245aa852009-02-10 00:49:54 +000095 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
96}
iposva@chromium.org245aa852009-02-10 00:49:54 +000097
98
sgjesse@chromium.org6db88712011-07-11 11:41:22 +000099int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
100 CHECK(source != NULL);
101 CHECK(dest != NULL);
102 CHECK_GT(dest_size, 0);
103
104 if (count == _TRUNCATE) {
105 while (dest_size > 0 && *source != 0) {
106 *(dest++) = *(source++);
107 --dest_size;
108 }
109 if (dest_size == 0) {
110 *(dest - 1) = 0;
111 return STRUNCATE;
112 }
113 } else {
114 while (dest_size > 0 && count > 0 && *source != 0) {
115 *(dest++) = *(source++);
116 --dest_size;
117 --count;
118 }
119 }
120 CHECK_GT(dest_size, 0);
121 *dest = 0;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000122 return 0;
123}
124
125#endif // __MINGW32__
126
127// Generate a pseudo-random number in the range 0-2^31-1. Usually
128// defined in stdlib.h. Missing in both Microsoft Visual Studio C++ and MinGW.
129int random() {
130 return rand();
131}
132
133
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000134namespace v8 {
135namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000136
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000137intptr_t OS::MaxVirtualMemory() {
138 return 0;
139}
140
141
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000142double ceiling(double x) {
143 return ceil(x);
144}
145
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000146
147static Mutex* limit_mutex = NULL;
148
jkummerow@chromium.org93a47f42013-07-02 14:43:41 +0000149#if V8_TARGET_ARCH_IA32
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000150static void MemMoveWrapper(void* dest, const void* src, size_t size) {
151 memmove(dest, src, size);
152}
153
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +0000154
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000155// Initialize to library version so we can call this at any time during startup.
156static OS::MemMoveFunction memmove_function = &MemMoveWrapper;
157
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000158// Defined in codegen-ia32.cc.
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000159OS::MemMoveFunction CreateMemMoveFunction();
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000160
161// Copy memory area to disjoint memory area.
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000162void OS::MemMove(void* dest, const void* src, size_t size) {
ulan@chromium.org77ca49a2013-04-22 09:43:56 +0000163 if (size == 0) return;
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000164 // Note: here we rely on dependent reads being ordered. This is true
165 // on all architectures we currently support.
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000166 (*memmove_function)(dest, src, size);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000167}
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000168
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000169#endif // V8_TARGET_ARCH_IA32
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000170
ager@chromium.org3811b432009-10-28 14:53:37 +0000171#ifdef _WIN64
172typedef double (*ModuloFunction)(double, double);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000173static ModuloFunction modulo_function = NULL;
ager@chromium.org3811b432009-10-28 14:53:37 +0000174// Defined in codegen-x64.cc.
175ModuloFunction CreateModuloFunction();
176
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000177void init_modulo_function() {
178 modulo_function = CreateModuloFunction();
179}
180
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +0000181
ager@chromium.org3811b432009-10-28 14:53:37 +0000182double modulo(double x, double y) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000183 // Note: here we rely on dependent reads being ordered. This is true
184 // on all architectures we currently support.
185 return (*modulo_function)(x, y);
ager@chromium.org3811b432009-10-28 14:53:37 +0000186}
187#else // Win32
188
189double modulo(double x, double y) {
190 // Workaround MS fmod bugs. ECMA-262 says:
191 // dividend is finite and divisor is an infinity => result equals dividend
192 // dividend is a zero and divisor is nonzero finite => result equals dividend
ulan@chromium.org77ca49a2013-04-22 09:43:56 +0000193 if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) &&
194 !(x == 0 && (y != 0 && std::isfinite(y)))) {
ager@chromium.org3811b432009-10-28 14:53:37 +0000195 x = fmod(x, y);
196 }
197 return x;
198}
199
200#endif // _WIN64
201
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000202
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000203#define UNARY_MATH_FUNCTION(name, generator) \
204static UnaryMathFunction fast_##name##_function = NULL; \
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000205void init_fast_##name##_function() { \
206 fast_##name##_function = generator; \
207} \
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000208double fast_##name(double x) { \
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000209 return (*fast_##name##_function)(x); \
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000210}
211
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000212UNARY_MATH_FUNCTION(sin, CreateTranscendentalFunction(TranscendentalCache::SIN))
213UNARY_MATH_FUNCTION(cos, CreateTranscendentalFunction(TranscendentalCache::COS))
214UNARY_MATH_FUNCTION(tan, CreateTranscendentalFunction(TranscendentalCache::TAN))
215UNARY_MATH_FUNCTION(log, CreateTranscendentalFunction(TranscendentalCache::LOG))
danno@chromium.org1f34ad32012-11-26 14:53:56 +0000216UNARY_MATH_FUNCTION(exp, CreateExpFunction())
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000217UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000218
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +0000219#undef UNARY_MATH_FUNCTION
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000220
221
danno@chromium.org1f34ad32012-11-26 14:53:56 +0000222void lazily_initialize_fast_exp() {
223 if (fast_exp_function == NULL) {
224 init_fast_exp_function();
225 }
226}
227
228
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000229void MathSetup() {
230#ifdef _WIN64
231 init_modulo_function();
232#endif
233 init_fast_sin_function();
234 init_fast_cos_function();
235 init_fast_tan_function();
236 init_fast_log_function();
danno@chromium.org1f34ad32012-11-26 14:53:56 +0000237 // fast_exp is initialized lazily.
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000238 init_fast_sqrt_function();
239}
240
241
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000242// ----------------------------------------------------------------------------
243// The Time class represents time on win32. A timestamp is represented as
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000244// a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
246// January 1, 1970.
247
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000248class Win32Time {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000249 public:
250 // Constructors.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000251 explicit Win32Time(double jstime);
252 Win32Time(int year, int mon, int day, int hour, int min, int sec);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000253
254 // Convert timestamp to JavaScript representation.
255 double ToJSTime();
256
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000257 // Returns the local timezone offset in milliseconds east of UTC. This is
258 // the number of milliseconds you must add to UTC to get local time, i.e.
259 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
260 // routine also takes into account whether daylight saving is effect
261 // at the time.
262 int64_t LocalOffset();
263
264 // Returns the daylight savings time offset for the time in milliseconds.
265 int64_t DaylightSavingsOffset();
266
267 // Returns a string identifying the current timezone for the
268 // timestamp taking into account daylight saving.
269 char* LocalTimezone();
270
271 private:
272 // Constants for time conversion.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000273 static const int64_t kTimeEpoc = 116444736000000000LL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000274 static const int64_t kTimeScaler = 10000;
275 static const int64_t kMsPerMinute = 60000;
276
277 // Constants for timezone information.
278 static const int kTzNameSize = 128;
279 static const bool kShortTzNames = false;
280
281 // Timezone information. We need to have static buffers for the
282 // timezone names because we return pointers to these in
283 // LocalTimezone().
284 static bool tz_initialized_;
285 static TIME_ZONE_INFORMATION tzinfo_;
286 static char std_tz_name_[kTzNameSize];
287 static char dst_tz_name_[kTzNameSize];
288
289 // Initialize the timezone information (if not already done).
290 static void TzSet();
291
292 // Guess the name of the timezone from the bias.
293 static const char* GuessTimezoneNameFromBias(int bias);
294
295 // Return whether or not daylight savings time is in effect at this time.
296 bool InDST();
297
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000298 // Accessor for FILETIME representation.
299 FILETIME& ft() { return time_.ft_; }
300
301 // Accessor for integer representation.
302 int64_t& t() { return time_.t_; }
303
304 // Although win32 uses 64-bit integers for representing timestamps,
305 // these are packed into a FILETIME structure. The FILETIME structure
306 // is just a struct representing a 64-bit integer. The TimeStamp union
307 // allows access to both a FILETIME and an integer representation of
308 // the timestamp.
309 union TimeStamp {
310 FILETIME ft_;
311 int64_t t_;
312 };
313
314 TimeStamp time_;
315};
316
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +0000317
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318// Static variables.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000319bool Win32Time::tz_initialized_ = false;
320TIME_ZONE_INFORMATION Win32Time::tzinfo_;
321char Win32Time::std_tz_name_[kTzNameSize];
322char Win32Time::dst_tz_name_[kTzNameSize];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323
324
325// Initialize timestamp from a JavaScript timestamp.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000326Win32Time::Win32Time(double jstime) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000327 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000328}
329
330
331// Initialize timestamp from date/time components.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000332Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333 SYSTEMTIME st;
334 st.wYear = year;
335 st.wMonth = mon;
336 st.wDay = day;
337 st.wHour = hour;
338 st.wMinute = min;
339 st.wSecond = sec;
340 st.wMilliseconds = 0;
341 SystemTimeToFileTime(&st, &ft());
342}
343
344
345// Convert timestamp to JavaScript timestamp.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000346double Win32Time::ToJSTime() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000347 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
348}
349
350
351// Guess the name of the timezone from the bias.
352// The guess is very biased towards the northern hemisphere.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000353const char* Win32Time::GuessTimezoneNameFromBias(int bias) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000354 static const int kHour = 60;
355 switch (-bias) {
356 case -9*kHour: return "Alaska";
357 case -8*kHour: return "Pacific";
358 case -7*kHour: return "Mountain";
359 case -6*kHour: return "Central";
360 case -5*kHour: return "Eastern";
361 case -4*kHour: return "Atlantic";
362 case 0*kHour: return "GMT";
363 case +1*kHour: return "Central Europe";
364 case +2*kHour: return "Eastern Europe";
365 case +3*kHour: return "Russia";
366 case +5*kHour + 30: return "India";
367 case +8*kHour: return "China";
368 case +9*kHour: return "Japan";
369 case +12*kHour: return "New Zealand";
370 default: return "Local";
371 }
372}
373
374
375// Initialize timezone information. The timezone information is obtained from
376// windows. If we cannot get the timezone information we fall back to CET.
377// Please notice that this code is not thread-safe.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000378void Win32Time::TzSet() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379 // Just return if timezone information has already been initialized.
380 if (tz_initialized_) return;
381
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000382 // Initialize POSIX time zone data.
383 _tzset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384 // Obtain timezone information from operating system.
385 memset(&tzinfo_, 0, sizeof(tzinfo_));
386 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
387 // If we cannot get timezone information we fall back to CET.
388 tzinfo_.Bias = -60;
389 tzinfo_.StandardDate.wMonth = 10;
390 tzinfo_.StandardDate.wDay = 5;
391 tzinfo_.StandardDate.wHour = 3;
392 tzinfo_.StandardBias = 0;
393 tzinfo_.DaylightDate.wMonth = 3;
394 tzinfo_.DaylightDate.wDay = 5;
395 tzinfo_.DaylightDate.wHour = 2;
396 tzinfo_.DaylightBias = -60;
397 }
398
399 // Make standard and DST timezone names.
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000400 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
401 std_tz_name_, kTzNameSize, NULL, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000402 std_tz_name_[kTzNameSize - 1] = '\0';
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000403 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
404 dst_tz_name_, kTzNameSize, NULL, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000405 dst_tz_name_[kTzNameSize - 1] = '\0';
406
407 // If OS returned empty string or resource id (like "@tzres.dll,-211")
408 // simply guess the name from the UTC bias of the timezone.
409 // To properly resolve the resource identifier requires a library load,
410 // which is not possible in a sandbox.
411 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000412 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
413 "%s Standard Time",
414 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000415 }
416 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000417 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
418 "%s Daylight Time",
419 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 }
421
422 // Timezone information initialized.
423 tz_initialized_ = true;
424}
425
426
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427// Return the local timezone offset in milliseconds east of UTC. This
428// takes into account whether daylight saving is in effect at the time.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000429// Only times in the 32-bit Unix range may be passed to this function.
430// Also, adding the time-zone offset to the input must not overflow.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000431// The function EquivalentTime() in date.js guarantees this.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000432int64_t Win32Time::LocalOffset() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000433 // Initialize timezone information, if needed.
434 TzSet();
435
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000436 Win32Time rounded_to_second(*this);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000437 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
438 1000 * kTimeScaler;
439 // Convert to local time using POSIX localtime function.
440 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
441 // very slow. Other browsers use localtime().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000442
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000443 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
444 // POSIX seconds past 1/1/1970 0:00:00.
445 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
446 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
447 return 0;
448 }
449 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
450 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000451
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000452 // Convert to local time, as struct with fields for day, hour, year, etc.
453 tm posix_local_time_struct;
454 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000455
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000456 if (posix_local_time_struct.tm_isdst > 0) {
457 return (tzinfo_.Bias + tzinfo_.DaylightBias) * -kMsPerMinute;
458 } else if (posix_local_time_struct.tm_isdst == 0) {
459 return (tzinfo_.Bias + tzinfo_.StandardBias) * -kMsPerMinute;
460 } else {
461 return tzinfo_.Bias * -kMsPerMinute;
462 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000463}
464
465
466// Return whether or not daylight savings time is in effect at this time.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000467bool Win32Time::InDST() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468 // Initialize timezone information, if needed.
469 TzSet();
470
471 // Determine if DST is in effect at the specified time.
472 bool in_dst = false;
473 if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) {
474 // Get the local timezone offset for the timestamp in milliseconds.
475 int64_t offset = LocalOffset();
476
477 // Compute the offset for DST. The bias parameters in the timezone info
478 // are specified in minutes. These must be converted to milliseconds.
479 int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute;
480
481 // If the local time offset equals the timezone bias plus the daylight
482 // bias then DST is in effect.
483 in_dst = offset == dstofs;
484 }
485
486 return in_dst;
487}
488
489
ager@chromium.org32912102009-01-16 10:38:43 +0000490// Return the daylight savings time offset for this time.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000491int64_t Win32Time::DaylightSavingsOffset() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492 return InDST() ? 60 * kMsPerMinute : 0;
493}
494
495
496// Returns a string identifying the current timezone for the
497// timestamp taking into account daylight saving.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000498char* Win32Time::LocalTimezone() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000499 // Return the standard or DST time zone name based on whether daylight
500 // saving is in effect at the given time.
501 return InDST() ? dst_tz_name_ : std_tz_name_;
502}
503
504
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000505void OS::PostSetUp() {
506 // Math functions depend on CPU features therefore they are initialized after
507 // CPU.
508 MathSetup();
jkummerow@chromium.org93a47f42013-07-02 14:43:41 +0000509#if V8_TARGET_ARCH_IA32
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000510 OS::MemMoveFunction generated_memmove = CreateMemMoveFunction();
511 if (generated_memmove != NULL) {
512 memmove_function = generated_memmove;
513 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000514#endif
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000515}
516
517
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000518// Returns the accumulated user time for thread.
519int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
520 FILETIME dummy;
521 uint64_t usertime;
522
523 // Get the amount of time that the thread has executed in user mode.
524 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
525 reinterpret_cast<FILETIME*>(&usertime))) return -1;
526
527 // Adjust the resolution to micro-seconds.
528 usertime /= 10;
529
530 // Convert to seconds and microseconds
531 *secs = static_cast<uint32_t>(usertime / 1000000);
532 *usecs = static_cast<uint32_t>(usertime % 1000000);
533 return 0;
534}
535
536
537// Returns current time as the number of milliseconds since
538// 00:00:00 UTC, January 1, 1970.
539double OS::TimeCurrentMillis() {
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000540 return Time::Now().ToJsTime();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000541}
542
543
544// Returns a string identifying the current timezone taking into
545// account daylight saving.
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000546const char* OS::LocalTimezone(double time) {
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000547 return Win32Time(time).LocalTimezone();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548}
549
550
kasper.lund7276f142008-07-30 08:49:36 +0000551// Returns the local time offset in milliseconds east of UTC without
552// taking daylight savings time into account.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000553double OS::LocalTimeOffset() {
kasper.lund7276f142008-07-30 08:49:36 +0000554 // Use current time, rounded to the millisecond.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000555 Win32Time t(TimeCurrentMillis());
kasper.lund7276f142008-07-30 08:49:36 +0000556 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
557 return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000558}
559
560
561// Returns the daylight savings offset in milliseconds for the given
562// time.
563double OS::DaylightSavingsOffset(double time) {
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000564 int64_t offset = Win32Time(time).DaylightSavingsOffset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000565 return static_cast<double>(offset);
566}
567
568
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000569int OS::GetLastError() {
570 return ::GetLastError();
571}
572
573
rossberg@chromium.org657d53b2012-07-12 11:06:03 +0000574int OS::GetCurrentProcessId() {
575 return static_cast<int>(::GetCurrentProcessId());
576}
577
578
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579// ----------------------------------------------------------------------------
580// Win32 console output.
581//
582// If a Win32 application is linked as a console application it has a normal
583// standard output and standard error. In this case normal printf works fine
584// for output. However, if the application is linked as a GUI application,
585// the process doesn't have a console, and therefore (debugging) output is lost.
586// This is the case if we are embedded in a windows program (like a browser).
587// In order to be able to get debug output in this case the the debugging
588// facility using OutputDebugString. This output goes to the active debugger
589// for the process (if any). Else the output can be monitored using DBMON.EXE.
590
591enum OutputMode {
592 UNKNOWN, // Output method has not yet been determined.
593 CONSOLE, // Output is written to stdout.
594 ODS // Output is written to debug facility.
595};
596
597static OutputMode output_mode = UNKNOWN; // Current output mode.
598
599
600// Determine if the process has a console for output.
601static bool HasConsole() {
602 // Only check the first time. Eventual race conditions are not a problem,
603 // because all threads will eventually determine the same mode.
604 if (output_mode == UNKNOWN) {
605 // We cannot just check that the standard output is attached to a console
606 // because this would fail if output is redirected to a file. Therefore we
607 // say that a process does not have an output console if either the
608 // standard output handle is invalid or its file type is unknown.
609 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
610 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
611 output_mode = CONSOLE;
612 else
613 output_mode = ODS;
614 }
615 return output_mode == CONSOLE;
616}
617
618
619static void VPrintHelper(FILE* stream, const char* format, va_list args) {
620 if (HasConsole()) {
621 vfprintf(stream, format, args);
622 } else {
623 // It is important to use safe print here in order to avoid
624 // overflowing the buffer. We might truncate the output, but this
625 // does not crash.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000626 EmbeddedVector<char, 4096> buffer;
627 OS::VSNPrintF(buffer, format, args);
628 OutputDebugStringA(buffer.start());
629 }
630}
631
632
633FILE* OS::FOpen(const char* path, const char* mode) {
634 FILE* result;
635 if (fopen_s(&result, path, mode) == 0) {
636 return result;
637 } else {
638 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000639 }
640}
641
642
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000643bool OS::Remove(const char* path) {
644 return (DeleteFileA(path) != 0);
645}
646
647
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000648FILE* OS::OpenTemporaryFile() {
649 // tmpfile_s tries to use the root dir, don't use it.
650 char tempPathBuffer[MAX_PATH];
651 DWORD path_result = 0;
652 path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
653 if (path_result > MAX_PATH || path_result == 0) return NULL;
654 UINT name_result = 0;
655 char tempNameBuffer[MAX_PATH];
656 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
657 if (name_result == 0) return NULL;
658 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
659 if (result != NULL) {
660 Remove(tempNameBuffer); // Delete on close.
661 }
662 return result;
663}
664
665
ager@chromium.org71daaf62009-04-01 07:22:49 +0000666// Open log file in binary mode to avoid /n -> /r/n conversion.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000667const char* const OS::LogFileOpenMode = "wb";
ager@chromium.org71daaf62009-04-01 07:22:49 +0000668
669
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000670// Print (debug) message to console.
671void OS::Print(const char* format, ...) {
672 va_list args;
673 va_start(args, format);
674 VPrint(format, args);
675 va_end(args);
676}
677
678
679void OS::VPrint(const char* format, va_list args) {
680 VPrintHelper(stdout, format, args);
681}
682
683
whesse@chromium.org023421e2010-12-21 12:19:12 +0000684void OS::FPrint(FILE* out, const char* format, ...) {
685 va_list args;
686 va_start(args, format);
687 VFPrint(out, format, args);
688 va_end(args);
689}
690
691
692void OS::VFPrint(FILE* out, const char* format, va_list args) {
693 VPrintHelper(out, format, args);
694}
695
696
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697// Print error message to console.
698void OS::PrintError(const char* format, ...) {
699 va_list args;
700 va_start(args, format);
701 VPrintError(format, args);
702 va_end(args);
703}
704
705
706void OS::VPrintError(const char* format, va_list args) {
707 VPrintHelper(stderr, format, args);
708}
709
710
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000711int OS::SNPrintF(Vector<char> str, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000712 va_list args;
713 va_start(args, format);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000714 int result = VSNPrintF(str, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000715 va_end(args);
716 return result;
717}
718
719
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000720int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
721 int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000722 // Make sure to zero-terminate the string if the output was
723 // truncated or if there was an error.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000724 if (n < 0 || n >= str.length()) {
whesse@chromium.org023421e2010-12-21 12:19:12 +0000725 if (str.length() > 0)
726 str[str.length() - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000727 return -1;
728 } else {
729 return n;
730 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000731}
732
733
ager@chromium.org381abbb2009-02-25 13:23:22 +0000734char* OS::StrChr(char* str, int c) {
735 return const_cast<char*>(strchr(str, c));
736}
737
738
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000739void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000740 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
741 size_t buffer_size = static_cast<size_t>(dest.length());
742 if (n + 1 > buffer_size) // count for trailing '\0'
743 n = _TRUNCATE;
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000744 int result = strncpy_s(dest.start(), dest.length(), src, n);
745 USE(result);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000746 ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000747}
748
749
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +0000750#undef _TRUNCATE
751#undef STRUNCATE
752
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000753// We keep the lowest and highest addresses mapped as a quick way of
754// determining that pointers are outside the heap (used mostly in assertions
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000755// and verification). The estimate is conservative, i.e., not all addresses in
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000756// 'allocated' space are actually allocated to our heap. The range is
757// [lowest, highest), inclusive on the low and and exclusive on the high end.
758static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
759static void* highest_ever_allocated = reinterpret_cast<void*>(0);
760
761
762static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000763 ASSERT(limit_mutex != NULL);
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000764 LockGuard<Mutex> lock_guard(limit_mutex);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000765
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 lowest_ever_allocated = Min(lowest_ever_allocated, address);
767 highest_ever_allocated =
768 Max(highest_ever_allocated,
769 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
770}
771
772
773bool OS::IsOutsideAllocatedSpace(void* pointer) {
774 if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated)
775 return true;
776 // Ask the Windows API
777 if (IsBadWritePtr(pointer, 1))
778 return true;
779 return false;
780}
781
782
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000783// Get the system's page size used by VirtualAlloc() or the next power
784// of two. The reason for always returning a power of two is that the
785// rounding up in OS::Allocate expects that.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786static size_t GetPageSize() {
787 static size_t page_size = 0;
788 if (page_size == 0) {
789 SYSTEM_INFO info;
790 GetSystemInfo(&info);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000791 page_size = RoundUpToPowerOf2(info.dwPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000792 }
793 return page_size;
794}
795
796
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000797// The allocation alignment is the guaranteed alignment for
798// VirtualAlloc'ed blocks of memory.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000799size_t OS::AllocateAlignment() {
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000800 static size_t allocate_alignment = 0;
801 if (allocate_alignment == 0) {
802 SYSTEM_INFO info;
803 GetSystemInfo(&info);
804 allocate_alignment = info.dwAllocationGranularity;
805 }
806 return allocate_alignment;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807}
808
809
danno@chromium.orgd3c42102013-08-01 16:58:23 +0000810void* OS::GetRandomMmapAddr() {
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000811 Isolate* isolate = Isolate::UncheckedCurrent();
812 // Note that the current isolate isn't set up in a call path via
813 // CpuFeatures::Probe. We don't care about randomization in this case because
814 // the code page is immediately freed.
815 if (isolate != NULL) {
816 // The address range used to randomize RWX allocations in OS::Allocate
817 // Try not to map pages into the default range that windows loads DLLs
818 // Use a multiple of 64k to prevent committing unused memory.
819 // Note: This does not guarantee RWX regions will be within the
820 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
821#ifdef V8_HOST_ARCH_64_BIT
822 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
823 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
824#else
825 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
826 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
827#endif
828 uintptr_t address = (V8::RandomPrivate(isolate) << kPageSizeBits)
829 | kAllocationRandomAddressMin;
830 address &= kAllocationRandomAddressMax;
831 return reinterpret_cast<void *>(address);
832 }
833 return NULL;
834}
835
836
837static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
838 LPVOID base = NULL;
839
840 if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
841 // For exectutable pages try and randomize the allocation address
842 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
danno@chromium.orgd3c42102013-08-01 16:58:23 +0000843 base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection);
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000844 }
845 }
846
847 // After three attempts give up and let the OS find an address to use.
848 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
849
850 return base;
851}
852
853
kasper.lund7276f142008-07-30 08:49:36 +0000854void* OS::Allocate(const size_t requested,
855 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000856 bool is_executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000857 // VirtualAlloc rounds allocated size to page size automatically.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000858 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000859
860 // Windows XP SP2 allows Data Excution Prevention (DEP).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000861 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000862
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000863 LPVOID mbase = RandomizedVirtualAlloc(msize,
864 MEM_COMMIT | MEM_RESERVE,
865 prot);
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000866
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000867 if (mbase == NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000868 LOG(ISOLATE, StringEvent("OS::Allocate", "VirtualAlloc failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000869 return NULL;
870 }
871
872 ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
873
874 *allocated = msize;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000875 UpdateAllocatedSpaceLimits(mbase, static_cast<int>(msize));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000876 return mbase;
877}
878
879
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000880void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000881 // TODO(1240712): VirtualFree has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000882 VirtualFree(address, 0, MEM_RELEASE);
883 USE(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000884}
885
886
ricow@chromium.org64e3a4b2011-12-13 08:07:27 +0000887intptr_t OS::CommitPageSize() {
888 return 4096;
889}
890
891
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000892void OS::ProtectCode(void* address, const size_t size) {
893 DWORD old_protect;
894 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
895}
896
897
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000898void OS::Guard(void* address, const size_t size) {
899 DWORD oldprotect;
900 VirtualProtect(address, size, PAGE_READONLY | PAGE_GUARD, &oldprotect);
901}
902
903
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000904void OS::Sleep(int milliseconds) {
905 ::Sleep(milliseconds);
906}
907
908
909void OS::Abort() {
rossberg@chromium.org2c067b12012-03-19 11:01:52 +0000910 if (IsDebuggerPresent() || FLAG_break_on_abort) {
911 DebugBreak();
912 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000913 // Make the MSVCRT do a silent abort.
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000914 raise(SIGABRT);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000915 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000916}
917
918
kasper.lund7276f142008-07-30 08:49:36 +0000919void OS::DebugBreak() {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000920#ifdef _MSC_VER
rossberg@chromium.org92597162013-08-23 13:28:00 +0000921 // To avoid Visual Studio runtime support the following code can be used
922 // instead
923 // __asm { int 3 }
kasper.lund7276f142008-07-30 08:49:36 +0000924 __debugbreak();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000925#else
926 ::DebugBreak();
927#endif
kasper.lund7276f142008-07-30 08:49:36 +0000928}
929
930
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000931void OS::DumpBacktrace() {
932 // Currently unsupported.
933}
934
935
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000936class Win32MemoryMappedFile : public OS::MemoryMappedFile {
937 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000938 Win32MemoryMappedFile(HANDLE file,
939 HANDLE file_mapping,
940 void* memory,
941 int size)
942 : file_(file),
943 file_mapping_(file_mapping),
944 memory_(memory),
945 size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000946 virtual ~Win32MemoryMappedFile();
947 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000948 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000949 private:
950 HANDLE file_;
951 HANDLE file_mapping_;
952 void* memory_;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000953 int size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000954};
955
956
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000957OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
958 // Open a physical file
959 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
960 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000961 if (file == INVALID_HANDLE_VALUE) return NULL;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000962
963 int size = static_cast<int>(GetFileSize(file, NULL));
964
965 // Create a file mapping for the physical file
966 HANDLE file_mapping = CreateFileMapping(file, NULL,
967 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
968 if (file_mapping == NULL) return NULL;
969
970 // Map a view of the file into memory
971 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
972 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
973}
974
975
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000976OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
977 void* initial) {
978 // Open a physical file
979 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
980 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
981 if (file == NULL) return NULL;
982 // Create a file mapping for the physical file
983 HANDLE file_mapping = CreateFileMapping(file, NULL,
984 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
985 if (file_mapping == NULL) return NULL;
986 // Map a view of the file into memory
987 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000988 if (memory) OS::MemMove(memory, initial, size);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000989 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000990}
991
992
993Win32MemoryMappedFile::~Win32MemoryMappedFile() {
994 if (memory_ != NULL)
995 UnmapViewOfFile(memory_);
996 CloseHandle(file_mapping_);
997 CloseHandle(file_);
998}
999
1000
1001// The following code loads functions defined in DbhHelp.h and TlHelp32.h
ager@chromium.org32912102009-01-16 10:38:43 +00001002// dynamically. This is to avoid being depending on dbghelp.dll and
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001003// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
1004// kernel32.dll at some point so loading functions defines in TlHelp32.h
1005// dynamically might not be necessary any more - for some versions of Windows?).
1006
1007// Function pointers to functions dynamically loaded from dbghelp.dll.
1008#define DBGHELP_FUNCTION_LIST(V) \
1009 V(SymInitialize) \
1010 V(SymGetOptions) \
1011 V(SymSetOptions) \
1012 V(SymGetSearchPath) \
1013 V(SymLoadModule64) \
1014 V(StackWalk64) \
1015 V(SymGetSymFromAddr64) \
1016 V(SymGetLineFromAddr64) \
1017 V(SymFunctionTableAccess64) \
1018 V(SymGetModuleBase64)
1019
1020// Function pointers to functions dynamically loaded from dbghelp.dll.
1021#define TLHELP32_FUNCTION_LIST(V) \
1022 V(CreateToolhelp32Snapshot) \
1023 V(Module32FirstW) \
1024 V(Module32NextW)
1025
1026// Define the decoration to use for the type and variable name used for
1027// dynamically loaded DLL function..
1028#define DLL_FUNC_TYPE(name) _##name##_
1029#define DLL_FUNC_VAR(name) _##name
1030
1031// Define the type for each dynamically loaded DLL function. The function
1032// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1033// from the Windows include files are redefined here to have the function
1034// definitions to be as close to the ones in the original .h files as possible.
1035#ifndef IN
1036#define IN
1037#endif
1038#ifndef VOID
1039#define VOID void
1040#endif
1041
iposva@chromium.org245aa852009-02-10 00:49:54 +00001042// DbgHelp isn't supported on MinGW yet
1043#ifndef __MINGW32__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001044// DbgHelp.h functions.
1045typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
1046 IN PSTR UserSearchPath,
1047 IN BOOL fInvadeProcess);
1048typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
1049typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
1050typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
1051 IN HANDLE hProcess,
1052 OUT PSTR SearchPath,
1053 IN DWORD SearchPathLength);
1054typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
1055 IN HANDLE hProcess,
1056 IN HANDLE hFile,
1057 IN PSTR ImageName,
1058 IN PSTR ModuleName,
1059 IN DWORD64 BaseOfDll,
1060 IN DWORD SizeOfDll);
1061typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
1062 DWORD MachineType,
1063 HANDLE hProcess,
1064 HANDLE hThread,
1065 LPSTACKFRAME64 StackFrame,
1066 PVOID ContextRecord,
1067 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1068 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1069 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1070 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1071typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
1072 IN HANDLE hProcess,
1073 IN DWORD64 qwAddr,
1074 OUT PDWORD64 pdwDisplacement,
1075 OUT PIMAGEHLP_SYMBOL64 Symbol);
1076typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
1077 IN HANDLE hProcess,
1078 IN DWORD64 qwAddr,
1079 OUT PDWORD pdwDisplacement,
1080 OUT PIMAGEHLP_LINE64 Line64);
1081// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1082typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
1083 HANDLE hProcess,
1084 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1085typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1086 HANDLE hProcess,
1087 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1088
1089// TlHelp32.h functions.
1090typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1091 DWORD dwFlags,
1092 DWORD th32ProcessID);
1093typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1094 LPMODULEENTRY32W lpme);
1095typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1096 LPMODULEENTRY32W lpme);
1097
1098#undef IN
1099#undef VOID
1100
1101// Declare a variable for each dynamically loaded DLL function.
1102#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1103DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1104TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1105#undef DEF_DLL_FUNCTION
1106
1107// Load the functions. This function has a lot of "ugly" macros in order to
1108// keep down code duplication.
1109
1110static bool LoadDbgHelpAndTlHelp32() {
1111 static bool dbghelp_loaded = false;
1112
1113 if (dbghelp_loaded) return true;
1114
1115 HMODULE module;
1116
1117 // Load functions from the dbghelp.dll module.
1118 module = LoadLibrary(TEXT("dbghelp.dll"));
1119 if (module == NULL) {
1120 return false;
1121 }
1122
1123#define LOAD_DLL_FUNC(name) \
1124 DLL_FUNC_VAR(name) = \
1125 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1126
1127DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1128
1129#undef LOAD_DLL_FUNC
1130
1131 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1132 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1133 module = LoadLibrary(TEXT("kernel32.dll"));
1134 if (module == NULL) {
1135 return false;
1136 }
1137
1138#define LOAD_DLL_FUNC(name) \
1139 DLL_FUNC_VAR(name) = \
1140 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1141
1142TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1143
1144#undef LOAD_DLL_FUNC
1145
1146 // Check that all functions where loaded.
1147 bool result =
1148#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1149
1150DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1151TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1152
1153#undef DLL_FUNC_LOADED
1154 true;
1155
1156 dbghelp_loaded = result;
1157 return result;
ager@chromium.org32912102009-01-16 10:38:43 +00001158 // NOTE: The modules are never unloaded and will stay around until the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001159 // application is closed.
1160}
1161
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00001162#undef DBGHELP_FUNCTION_LIST
1163#undef TLHELP32_FUNCTION_LIST
1164#undef DLL_FUNC_VAR
1165#undef DLL_FUNC_TYPE
1166
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001167
1168// Load the symbols for generating stack traces.
1169static bool LoadSymbols(HANDLE process_handle) {
1170 static bool symbols_loaded = false;
1171
1172 if (symbols_loaded) return true;
1173
1174 BOOL ok;
1175
1176 // Initialize the symbol engine.
1177 ok = _SymInitialize(process_handle, // hProcess
1178 NULL, // UserSearchPath
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001179 false); // fInvadeProcess
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001180 if (!ok) return false;
1181
1182 DWORD options = _SymGetOptions();
1183 options |= SYMOPT_LOAD_LINES;
1184 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1185 options = _SymSetOptions(options);
1186
1187 char buf[OS::kStackWalkMaxNameLen] = {0};
1188 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1189 if (!ok) {
1190 int err = GetLastError();
1191 PrintF("%d\n", err);
1192 return false;
1193 }
1194
1195 HANDLE snapshot = _CreateToolhelp32Snapshot(
1196 TH32CS_SNAPMODULE, // dwFlags
1197 GetCurrentProcessId()); // th32ProcessId
1198 if (snapshot == INVALID_HANDLE_VALUE) return false;
1199 MODULEENTRY32W module_entry;
1200 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1201 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1202 while (cont) {
1203 DWORD64 base;
1204 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1205 // both unicode and ASCII strings even though the parameter is PSTR.
1206 base = _SymLoadModule64(
1207 process_handle, // hProcess
1208 0, // hFile
1209 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1210 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1211 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1212 module_entry.modBaseSize); // SizeOfDll
1213 if (base == 0) {
1214 int err = GetLastError();
1215 if (err != ERROR_MOD_NOT_FOUND &&
1216 err != ERROR_INVALID_HANDLE) return false;
1217 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001218 LOG(i::Isolate::Current(),
1219 SharedLibraryEvent(
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001220 module_entry.szExePath,
1221 reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1222 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1223 module_entry.modBaseSize)));
1224 cont = _Module32NextW(snapshot, &module_entry);
1225 }
1226 CloseHandle(snapshot);
1227
1228 symbols_loaded = true;
1229 return true;
1230}
1231
1232
1233void OS::LogSharedLibraryAddresses() {
1234 // SharedLibraryEvents are logged when loading symbol information.
1235 // Only the shared libraries loaded at the time of the call to
1236 // LogSharedLibraryAddresses are logged. DLLs loaded after
1237 // initialization are not accounted for.
1238 if (!LoadDbgHelpAndTlHelp32()) return;
1239 HANDLE process_handle = GetCurrentProcess();
1240 LoadSymbols(process_handle);
1241}
1242
1243
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00001244void OS::SignalCodeMovingGC() {
1245}
1246
1247
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001248// Walk the stack using the facilities in dbghelp.dll and tlhelp32.dll
1249
1250// Switch off warning 4748 (/GS can not protect parameters and local variables
1251// from local buffer overrun because optimizations are disabled in function) as
1252// it is triggered by the use of inline assembler.
1253#pragma warning(push)
1254#pragma warning(disable : 4748)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001255int OS::StackWalk(Vector<OS::StackFrame> frames) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001256 BOOL ok;
1257
1258 // Load the required functions from DLL's.
1259 if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError;
1260
1261 // Get the process and thread handles.
1262 HANDLE process_handle = GetCurrentProcess();
1263 HANDLE thread_handle = GetCurrentThread();
1264
1265 // Read the symbols.
1266 if (!LoadSymbols(process_handle)) return kStackWalkError;
1267
1268 // Capture current context.
1269 CONTEXT context;
ager@chromium.org3811b432009-10-28 14:53:37 +00001270 RtlCaptureContext(&context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001271
1272 // Initialize the stack walking
1273 STACKFRAME64 stack_frame;
1274 memset(&stack_frame, 0, sizeof(stack_frame));
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001275#ifdef _WIN64
1276 stack_frame.AddrPC.Offset = context.Rip;
1277 stack_frame.AddrFrame.Offset = context.Rbp;
1278 stack_frame.AddrStack.Offset = context.Rsp;
1279#else
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001280 stack_frame.AddrPC.Offset = context.Eip;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001281 stack_frame.AddrFrame.Offset = context.Ebp;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001282 stack_frame.AddrStack.Offset = context.Esp;
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001283#endif
1284 stack_frame.AddrPC.Mode = AddrModeFlat;
1285 stack_frame.AddrFrame.Mode = AddrModeFlat;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001286 stack_frame.AddrStack.Mode = AddrModeFlat;
1287 int frames_count = 0;
1288
1289 // Collect stack frames.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001290 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001291 while (frames_count < frames_size) {
1292 ok = _StackWalk64(
1293 IMAGE_FILE_MACHINE_I386, // MachineType
1294 process_handle, // hProcess
1295 thread_handle, // hThread
1296 &stack_frame, // StackFrame
1297 &context, // ContextRecord
1298 NULL, // ReadMemoryRoutine
1299 _SymFunctionTableAccess64, // FunctionTableAccessRoutine
1300 _SymGetModuleBase64, // GetModuleBaseRoutine
1301 NULL); // TranslateAddress
1302 if (!ok) break;
1303
1304 // Store the address.
1305 ASSERT((stack_frame.AddrPC.Offset >> 32) == 0); // 32-bit address.
1306 frames[frames_count].address =
1307 reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
1308
1309 // Try to locate a symbol for this frame.
1310 DWORD64 symbol_displacement;
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001311 SmartArrayPointer<IMAGEHLP_SYMBOL64> symbol(
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001312 NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen));
1313 if (symbol.is_empty()) return kStackWalkError; // Out of memory.
1314 memset(*symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
1315 (*symbol)->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
1316 (*symbol)->MaxNameLength = kStackWalkMaxNameLen;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001317 ok = _SymGetSymFromAddr64(process_handle, // hProcess
1318 stack_frame.AddrPC.Offset, // Address
1319 &symbol_displacement, // Displacement
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001320 *symbol); // Symbol
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001321 if (ok) {
1322 // Try to locate more source information for the symbol.
1323 IMAGEHLP_LINE64 Line;
1324 memset(&Line, 0, sizeof(Line));
1325 Line.SizeOfStruct = sizeof(Line);
1326 DWORD line_displacement;
1327 ok = _SymGetLineFromAddr64(
1328 process_handle, // hProcess
1329 stack_frame.AddrPC.Offset, // dwAddr
1330 &line_displacement, // pdwDisplacement
1331 &Line); // Line
1332 // Format a text representation of the frame based on the information
1333 // available.
1334 if (ok) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001335 SNPrintF(MutableCStrVector(frames[frames_count].text,
1336 kStackWalkMaxTextLen),
1337 "%s %s:%d:%d",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001338 (*symbol)->Name, Line.FileName, Line.LineNumber,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001339 line_displacement);
1340 } else {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001341 SNPrintF(MutableCStrVector(frames[frames_count].text,
1342 kStackWalkMaxTextLen),
1343 "%s",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001344 (*symbol)->Name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001345 }
1346 // Make sure line termination is in place.
1347 frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
1348 } else {
1349 // No text representation of this frame
1350 frames[frames_count].text[0] = '\0';
1351
1352 // Continue if we are just missing a module (for non C/C++ frames a
1353 // module will never be found).
1354 int err = GetLastError();
1355 if (err != ERROR_MOD_NOT_FOUND) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001356 break;
1357 }
1358 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001359
1360 frames_count++;
1361 }
1362
1363 // Return the number of frames filled in.
1364 return frames_count;
1365}
1366
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +00001367
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001368// Restore warnings to previous settings.
1369#pragma warning(pop)
1370
iposva@chromium.org245aa852009-02-10 00:49:54 +00001371#else // __MINGW32__
1372void OS::LogSharedLibraryAddresses() { }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001373void OS::SignalCodeMovingGC() { }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001374int OS::StackWalk(Vector<OS::StackFrame> frames) { return 0; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001375#endif // __MINGW32__
1376
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001377
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001378uint64_t OS::CpuFeaturesImpliedByPlatform() {
1379 return 0; // Windows runs on anything.
1380}
1381
1382
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001383double OS::nan_value() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001384#ifdef _MSC_VER
ager@chromium.org3811b432009-10-28 14:53:37 +00001385 // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
1386 // in mask set, so value equals mask.
1387 static const __int64 nanval = kQuietNaNMask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001388 return *reinterpret_cast<const double*>(&nanval);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001389#else // _MSC_VER
1390 return NAN;
1391#endif // _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001392}
1393
ager@chromium.org236ad962008-09-25 09:45:57 +00001394
1395int OS::ActivationFrameAlignment() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001396#ifdef _WIN64
1397 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +00001398#elif defined(__MINGW32__)
1399 // With gcc 4.4 the tree vectorization optimizer can generate code
1400 // that requires 16 byte alignment such as movdqa on x86.
1401 return 16;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001402#else
1403 return 8; // Floating-point math runs faster with 8-byte alignment.
1404#endif
ager@chromium.org236ad962008-09-25 09:45:57 +00001405}
1406
1407
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001408VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409
1410
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001411VirtualMemory::VirtualMemory(size_t size)
1412 : address_(ReserveRegion(size)), size_(size) { }
1413
1414
1415VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1416 : address_(NULL), size_(0) {
1417 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
1418 size_t request_size = RoundUp(size + alignment,
1419 static_cast<intptr_t>(OS::AllocateAlignment()));
1420 void* address = ReserveRegion(request_size);
1421 if (address == NULL) return;
1422 Address base = RoundUp(static_cast<Address>(address), alignment);
1423 // Try reducing the size by freeing and then reallocating a specific area.
1424 bool result = ReleaseRegion(address, request_size);
1425 USE(result);
1426 ASSERT(result);
1427 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1428 if (address != NULL) {
1429 request_size = size;
1430 ASSERT(base == static_cast<Address>(address));
1431 } else {
1432 // Resizing failed, just go with a bigger area.
1433 address = ReserveRegion(request_size);
1434 if (address == NULL) return;
1435 }
1436 address_ = address;
1437 size_ = request_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001438}
1439
1440
1441VirtualMemory::~VirtualMemory() {
1442 if (IsReserved()) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001443 bool result = ReleaseRegion(address(), size());
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001444 ASSERT(result);
1445 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001446 }
1447}
1448
1449
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001450bool VirtualMemory::IsReserved() {
1451 return address_ != NULL;
1452}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001453
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001454
1455void VirtualMemory::Reset() {
1456 address_ = NULL;
1457 size_ = 0;
1458}
1459
1460
1461bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001462 return CommitRegion(address, size, is_executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463}
1464
1465
1466bool VirtualMemory::Uncommit(void* address, size_t size) {
1467 ASSERT(IsReserved());
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001468 return UncommitRegion(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001469}
1470
1471
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001472bool VirtualMemory::Guard(void* address) {
1473 if (NULL == VirtualAlloc(address,
1474 OS::CommitPageSize(),
1475 MEM_COMMIT,
1476 PAGE_READONLY | PAGE_GUARD)) {
1477 return false;
1478 }
1479 return true;
1480}
1481
1482
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001483void* VirtualMemory::ReserveRegion(size_t size) {
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +00001484 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001485}
1486
1487
1488bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1489 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1490 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1491 return false;
1492 }
1493
1494 UpdateAllocatedSpaceLimits(base, static_cast<int>(size));
1495 return true;
1496}
1497
1498
1499bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1500 return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1501}
1502
1503
1504bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1505 return VirtualFree(base, 0, MEM_RELEASE) != 0;
1506}
1507
1508
danno@chromium.org72204d52012-10-31 10:02:10 +00001509bool VirtualMemory::HasLazyCommits() {
1510 // TODO(alph): implement for the platform.
1511 return false;
1512}
1513
1514
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001515// ----------------------------------------------------------------------------
1516// Win32 thread support.
1517
1518// Definition of invalid thread handle and id.
1519static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001520
1521// Entry point for threads. The supplied argument is a pointer to the thread
1522// object. The entry function dispatches to the run method in the thread
1523// object. It is important that this function has __stdcall calling
1524// convention.
1525static unsigned int __stdcall ThreadEntry(void* arg) {
1526 Thread* thread = reinterpret_cast<Thread*>(arg);
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001527 thread->NotifyStartedAndRun();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001528 return 0;
1529}
1530
1531
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001532class Thread::PlatformData : public Malloced {
1533 public:
1534 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1535 HANDLE thread_;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001536 unsigned thread_id_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001537};
1538
1539
1540// Initialize a Win32 thread object. The thread has an invalid thread
1541// handle until it is started.
1542
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001543Thread::Thread(const Options& options)
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001544 : stack_size_(options.stack_size()),
1545 start_semaphore_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001546 data_ = new PlatformData(kNoThread);
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00001547 set_name(options.name());
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001548}
1549
1550
1551void Thread::set_name(const char* name) {
erik.corry@gmail.com0511e242011-01-19 11:11:08 +00001552 OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001553 name_[sizeof(name_) - 1] = '\0';
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554}
1555
1556
1557// Close our own handle for the thread.
1558Thread::~Thread() {
1559 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1560 delete data_;
1561}
1562
1563
1564// Create a new thread. It is important to use _beginthreadex() instead of
1565// the Win32 function CreateThread(), because the CreateThread() does not
1566// initialize thread specific structures in the C runtime library.
1567void Thread::Start() {
1568 data_->thread_ = reinterpret_cast<HANDLE>(
1569 _beginthreadex(NULL,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001570 static_cast<unsigned>(stack_size_),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001571 ThreadEntry,
1572 this,
1573 0,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001574 &data_->thread_id_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001575}
1576
1577
1578// Wait for thread to terminate.
1579void Thread::Join() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001580 if (data_->thread_id_ != GetCurrentThreadId()) {
1581 WaitForSingleObject(data_->thread_, INFINITE);
1582 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001583}
1584
1585
1586Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1587 DWORD result = TlsAlloc();
1588 ASSERT(result != TLS_OUT_OF_INDEXES);
1589 return static_cast<LocalStorageKey>(result);
1590}
1591
1592
1593void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1594 BOOL result = TlsFree(static_cast<DWORD>(key));
1595 USE(result);
1596 ASSERT(result);
1597}
1598
1599
1600void* Thread::GetThreadLocal(LocalStorageKey key) {
1601 return TlsGetValue(static_cast<DWORD>(key));
1602}
1603
1604
1605void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1606 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1607 USE(result);
1608 ASSERT(result);
1609}
1610
1611
1612
1613void Thread::YieldCPU() {
1614 Sleep(0);
1615}
1616
1617
1618// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001619// Win32 semaphore support.
1620//
1621// On Win32 semaphores are implemented using Win32 Semaphore objects. The
1622// semaphores are anonymous. Also, the semaphores are initialized to have
1623// no upper limit on count.
1624
1625
1626class Win32Semaphore : public Semaphore {
1627 public:
1628 explicit Win32Semaphore(int count) {
1629 sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
1630 }
1631
1632 ~Win32Semaphore() {
1633 CloseHandle(sem);
1634 }
1635
1636 void Wait() {
1637 WaitForSingleObject(sem, INFINITE);
1638 }
1639
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001640 bool Wait(int timeout) {
1641 // Timeout in Windows API is in milliseconds.
1642 DWORD millis_timeout = timeout / 1000;
1643 return WaitForSingleObject(sem, millis_timeout) != WAIT_TIMEOUT;
1644 }
1645
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001646 void Signal() {
1647 LONG dummy;
1648 ReleaseSemaphore(sem, 1, &dummy);
1649 }
1650
1651 private:
1652 HANDLE sem;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001653};
1654
1655
1656Semaphore* OS::CreateSemaphore(int count) {
1657 return new Win32Semaphore(count);
1658}
1659
ager@chromium.org381abbb2009-02-25 13:23:22 +00001660
1661// ----------------------------------------------------------------------------
1662// Win32 socket support.
1663//
1664
1665class Win32Socket : public Socket {
1666 public:
1667 explicit Win32Socket() {
1668 // Create the socket.
1669 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1670 }
1671 explicit Win32Socket(SOCKET socket): socket_(socket) { }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001672 virtual ~Win32Socket() { Shutdown(); }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001673
1674 // Server initialization.
1675 bool Bind(const int port);
1676 bool Listen(int backlog) const;
1677 Socket* Accept() const;
1678
1679 // Client initialization.
1680 bool Connect(const char* host, const char* port);
1681
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001682 // Shutdown socket for both read and write.
1683 bool Shutdown();
1684
ager@chromium.org381abbb2009-02-25 13:23:22 +00001685 // Data Transimission
1686 int Send(const char* data, int len) const;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001687 int Receive(char* data, int len) const;
1688
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001689 bool SetReuseAddress(bool reuse_address);
1690
ager@chromium.org381abbb2009-02-25 13:23:22 +00001691 bool IsValid() const { return socket_ != INVALID_SOCKET; }
1692
1693 private:
1694 SOCKET socket_;
1695};
1696
1697
1698bool Win32Socket::Bind(const int port) {
1699 if (!IsValid()) {
1700 return false;
1701 }
1702
1703 sockaddr_in addr;
1704 memset(&addr, 0, sizeof(addr));
1705 addr.sin_family = AF_INET;
1706 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1707 addr.sin_port = htons(port);
1708 int status = bind(socket_,
1709 reinterpret_cast<struct sockaddr *>(&addr),
1710 sizeof(addr));
1711 return status == 0;
1712}
1713
1714
1715bool Win32Socket::Listen(int backlog) const {
1716 if (!IsValid()) {
1717 return false;
1718 }
1719
1720 int status = listen(socket_, backlog);
1721 return status == 0;
1722}
1723
1724
1725Socket* Win32Socket::Accept() const {
1726 if (!IsValid()) {
1727 return NULL;
1728 }
1729
1730 SOCKET socket = accept(socket_, NULL, NULL);
1731 if (socket == INVALID_SOCKET) {
1732 return NULL;
1733 } else {
1734 return new Win32Socket(socket);
1735 }
1736}
1737
1738
1739bool Win32Socket::Connect(const char* host, const char* port) {
1740 if (!IsValid()) {
1741 return false;
1742 }
1743
1744 // Lookup host and port.
1745 struct addrinfo *result = NULL;
1746 struct addrinfo hints;
1747 memset(&hints, 0, sizeof(addrinfo));
1748 hints.ai_family = AF_INET;
1749 hints.ai_socktype = SOCK_STREAM;
1750 hints.ai_protocol = IPPROTO_TCP;
1751 int status = getaddrinfo(host, port, &hints, &result);
1752 if (status != 0) {
1753 return false;
1754 }
1755
1756 // Connect.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001757 status = connect(socket_,
1758 result->ai_addr,
1759 static_cast<int>(result->ai_addrlen));
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001760 freeaddrinfo(result);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001761 return status == 0;
1762}
1763
1764
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001765bool Win32Socket::Shutdown() {
1766 if (IsValid()) {
1767 // Shutdown socket for both read and write.
1768 int status = shutdown(socket_, SD_BOTH);
1769 closesocket(socket_);
1770 socket_ = INVALID_SOCKET;
1771 return status == SOCKET_ERROR;
1772 }
1773 return true;
1774}
1775
1776
ager@chromium.org381abbb2009-02-25 13:23:22 +00001777int Win32Socket::Send(const char* data, int len) const {
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001778 if (len <= 0) return 0;
1779 int written = 0;
1780 while (written < len) {
1781 int status = send(socket_, data + written, len - written, 0);
1782 if (status == 0) {
1783 break;
1784 } else if (status > 0) {
1785 written += status;
1786 } else {
1787 return 0;
1788 }
1789 }
1790 return written;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001791}
1792
1793
ager@chromium.org381abbb2009-02-25 13:23:22 +00001794int Win32Socket::Receive(char* data, int len) const {
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001795 if (len <= 0) return 0;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001796 int status = recv(socket_, data, len, 0);
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001797 return (status == SOCKET_ERROR) ? 0 : status;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001798}
1799
1800
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001801bool Win32Socket::SetReuseAddress(bool reuse_address) {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001802 BOOL on = reuse_address ? true : false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001803 int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
1804 reinterpret_cast<char*>(&on), sizeof(on));
1805 return status == SOCKET_ERROR;
1806}
1807
1808
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001809bool Socket::SetUp() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001810 // Initialize Winsock32
1811 int err;
1812 WSADATA winsock_data;
1813 WORD version_requested = MAKEWORD(1, 0);
1814 err = WSAStartup(version_requested, &winsock_data);
1815 if (err != 0) {
1816 PrintF("Unable to initialize Winsock, err = %d\n", Socket::LastError());
1817 }
1818
1819 return err == 0;
1820}
1821
1822
1823int Socket::LastError() {
1824 return WSAGetLastError();
1825}
1826
1827
1828uint16_t Socket::HToN(uint16_t value) {
1829 return htons(value);
1830}
1831
1832
1833uint16_t Socket::NToH(uint16_t value) {
1834 return ntohs(value);
1835}
1836
1837
1838uint32_t Socket::HToN(uint32_t value) {
1839 return htonl(value);
1840}
1841
1842
1843uint32_t Socket::NToH(uint32_t value) {
1844 return ntohl(value);
1845}
1846
1847
1848Socket* OS::CreateSocket() {
1849 return new Win32Socket();
1850}
1851
1852
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001853void OS::SetUp() {
1854 // Seed the random number generator.
1855 // Convert the current time to a 64-bit integer first, before converting it
1856 // to an unsigned. Going directly can cause an overflow and the seed to be
1857 // set to all ones. The seed will be identical for different instances that
1858 // call this setup code within the same millisecond.
1859 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
1860 srand(static_cast<unsigned int>(seed));
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +00001861 limit_mutex = new Mutex();
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001862}
1863
1864
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00001865void OS::TearDown() {
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00001866 delete limit_mutex;
1867}
1868
1869
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001870} } // namespace v8::internal