blob: e5df5ff3bf5dd2eb360ab67c13d83456206d66b2 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 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
kasperl@chromium.orga5551262010-12-07 12:49:48 +000030#define V8_WIN32_HEADERS_FULL
31#include "win32-headers.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032
33#include "v8.h"
34
35#include "platform.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000036#include "vm-state-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037
iposva@chromium.org245aa852009-02-10 00:49:54 +000038// Extra POSIX/ANSI routines for Win32 when when using Visual Studio C++. Please
39// refer to The Open Group Base Specification for specification of the correct
40// semantics for these functions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000041// (http://www.opengroup.org/onlinepubs/000095399/)
iposva@chromium.org245aa852009-02-10 00:49:54 +000042#ifdef _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044namespace v8 {
45namespace internal {
46
iposva@chromium.org245aa852009-02-10 00:49:54 +000047// Test for finite value - usually defined in math.h
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000048int isfinite(double x) {
49 return _finite(x);
50}
51
52} // namespace v8
53} // namespace internal
54
55// Test for a NaN (not a number) value - usually defined in math.h
56int isnan(double x) {
57 return _isnan(x);
58}
59
60
61// Test for infinity - usually defined in math.h
62int isinf(double x) {
63 return (_fpclass(x) & (_FPCLASS_PINF | _FPCLASS_NINF)) != 0;
64}
65
66
67// Test if x is less than y and both nominal - usually defined in math.h
68int isless(double x, double y) {
69 return isnan(x) || isnan(y) ? 0 : x < y;
70}
71
72
73// Test if x is greater than y and both nominal - usually defined in math.h
74int isgreater(double x, double y) {
75 return isnan(x) || isnan(y) ? 0 : x > y;
76}
77
78
79// Classify floating point number - usually defined in math.h
80int fpclassify(double x) {
81 // Use the MS-specific _fpclass() for classification.
82 int flags = _fpclass(x);
83
84 // Determine class. We cannot use a switch statement because
85 // the _FPCLASS_ constants are defined as flags.
86 if (flags & (_FPCLASS_PN | _FPCLASS_NN)) return FP_NORMAL;
87 if (flags & (_FPCLASS_PZ | _FPCLASS_NZ)) return FP_ZERO;
88 if (flags & (_FPCLASS_PD | _FPCLASS_ND)) return FP_SUBNORMAL;
89 if (flags & (_FPCLASS_PINF | _FPCLASS_NINF)) return FP_INFINITE;
90
91 // All cases should be covered by the code above.
92 ASSERT(flags & (_FPCLASS_SNAN | _FPCLASS_QNAN));
93 return FP_NAN;
94}
95
96
97// Test sign - usually defined in math.h
98int signbit(double x) {
99 // We need to take care of the special case of both positive
100 // and negative versions of zero.
101 if (x == 0)
102 return _fpclass(x) & _FPCLASS_NZ;
103 else
104 return x < 0;
105}
106
107
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000108// Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
109// defined in strings.h.
110int strncasecmp(const char* s1, const char* s2, int n) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000111 return _strnicmp(s1, s2, n);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000112}
113
iposva@chromium.org245aa852009-02-10 00:49:54 +0000114#endif // _MSC_VER
115
116
117// Extra functions for MinGW. Most of these are the _s functions which are in
118// the Microsoft Visual Studio C++ CRT.
119#ifdef __MINGW32__
120
121int localtime_s(tm* out_tm, const time_t* time) {
122 tm* posix_local_time_struct = localtime(time);
123 if (posix_local_time_struct == NULL) return 1;
124 *out_tm = *posix_local_time_struct;
125 return 0;
126}
127
128
129// Not sure this the correct interpretation of _mkgmtime
130time_t _mkgmtime(tm* timeptr) {
131 return mktime(timeptr);
132}
133
134
135int fopen_s(FILE** pFile, const char* filename, const char* mode) {
136 *pFile = fopen(filename, mode);
137 return *pFile != NULL ? 0 : 1;
138}
139
140
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000141#define _TRUNCATE 0
142#define STRUNCATE 80
143
iposva@chromium.org245aa852009-02-10 00:49:54 +0000144int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
145 const char* format, va_list argptr) {
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000146 ASSERT(count == _TRUNCATE);
iposva@chromium.org245aa852009-02-10 00:49:54 +0000147 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
148}
iposva@chromium.org245aa852009-02-10 00:49:54 +0000149
150
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000151int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
152 CHECK(source != NULL);
153 CHECK(dest != NULL);
154 CHECK_GT(dest_size, 0);
155
156 if (count == _TRUNCATE) {
157 while (dest_size > 0 && *source != 0) {
158 *(dest++) = *(source++);
159 --dest_size;
160 }
161 if (dest_size == 0) {
162 *(dest - 1) = 0;
163 return STRUNCATE;
164 }
165 } else {
166 while (dest_size > 0 && count > 0 && *source != 0) {
167 *(dest++) = *(source++);
168 --dest_size;
169 --count;
170 }
171 }
172 CHECK_GT(dest_size, 0);
173 *dest = 0;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000174 return 0;
175}
176
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000177
178inline void MemoryBarrier() {
179 int barrier = 0;
180 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
181}
182
iposva@chromium.org245aa852009-02-10 00:49:54 +0000183#endif // __MINGW32__
184
185// Generate a pseudo-random number in the range 0-2^31-1. Usually
186// defined in stdlib.h. Missing in both Microsoft Visual Studio C++ and MinGW.
187int random() {
188 return rand();
189}
190
191
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000192namespace v8 {
193namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000194
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000195intptr_t OS::MaxVirtualMemory() {
196 return 0;
197}
198
199
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200double ceiling(double x) {
201 return ceil(x);
202}
203
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000204
205static Mutex* limit_mutex = NULL;
206
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000207#if defined(V8_TARGET_ARCH_IA32)
208static OS::MemCopyFunction memcopy_function = NULL;
209static Mutex* memcopy_function_mutex = OS::CreateMutex();
210// Defined in codegen-ia32.cc.
211OS::MemCopyFunction CreateMemCopyFunction();
212
213// Copy memory area to disjoint memory area.
214void OS::MemCopy(void* dest, const void* src, size_t size) {
215 if (memcopy_function == NULL) {
216 ScopedLock lock(memcopy_function_mutex);
217 if (memcopy_function == NULL) {
218 OS::MemCopyFunction temp = CreateMemCopyFunction();
219 MemoryBarrier();
220 memcopy_function = temp;
221 }
222 }
223 // Note: here we rely on dependent reads being ordered. This is true
224 // on all architectures we currently support.
225 (*memcopy_function)(dest, src, size);
226#ifdef DEBUG
227 CHECK_EQ(0, memcmp(dest, src, size));
228#endif
229}
230#endif // V8_TARGET_ARCH_IA32
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000231
ager@chromium.org3811b432009-10-28 14:53:37 +0000232#ifdef _WIN64
233typedef double (*ModuloFunction)(double, double);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000234static ModuloFunction modulo_function = NULL;
235static Mutex* modulo_function_mutex = OS::CreateMutex();
ager@chromium.org3811b432009-10-28 14:53:37 +0000236// Defined in codegen-x64.cc.
237ModuloFunction CreateModuloFunction();
238
239double modulo(double x, double y) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000240 if (modulo_function == NULL) {
241 ScopedLock lock(modulo_function_mutex);
242 if (modulo_function == NULL) {
243 ModuloFunction temp = CreateModuloFunction();
244 MemoryBarrier();
245 modulo_function = temp;
246 }
247 }
248 // Note: here we rely on dependent reads being ordered. This is true
249 // on all architectures we currently support.
250 return (*modulo_function)(x, y);
ager@chromium.org3811b432009-10-28 14:53:37 +0000251}
252#else // Win32
253
254double modulo(double x, double y) {
255 // Workaround MS fmod bugs. ECMA-262 says:
256 // dividend is finite and divisor is an infinity => result equals dividend
257 // dividend is a zero and divisor is nonzero finite => result equals dividend
258 if (!(isfinite(x) && (!isfinite(y) && !isnan(y))) &&
259 !(x == 0 && (y != 0 && isfinite(y)))) {
260 x = fmod(x, y);
261 }
262 return x;
263}
264
265#endif // _WIN64
266
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000267// ----------------------------------------------------------------------------
268// The Time class represents time on win32. A timestamp is represented as
269// a 64-bit integer in 100 nano-seconds since January 1, 1601 (UTC). JavaScript
270// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
271// January 1, 1970.
272
273class Time {
274 public:
275 // Constructors.
276 Time();
277 explicit Time(double jstime);
278 Time(int year, int mon, int day, int hour, int min, int sec);
279
280 // Convert timestamp to JavaScript representation.
281 double ToJSTime();
282
283 // Set timestamp to current time.
284 void SetToCurrentTime();
285
286 // Returns the local timezone offset in milliseconds east of UTC. This is
287 // the number of milliseconds you must add to UTC to get local time, i.e.
288 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
289 // routine also takes into account whether daylight saving is effect
290 // at the time.
291 int64_t LocalOffset();
292
293 // Returns the daylight savings time offset for the time in milliseconds.
294 int64_t DaylightSavingsOffset();
295
296 // Returns a string identifying the current timezone for the
297 // timestamp taking into account daylight saving.
298 char* LocalTimezone();
299
300 private:
301 // Constants for time conversion.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000302 static const int64_t kTimeEpoc = 116444736000000000LL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000303 static const int64_t kTimeScaler = 10000;
304 static const int64_t kMsPerMinute = 60000;
305
306 // Constants for timezone information.
307 static const int kTzNameSize = 128;
308 static const bool kShortTzNames = false;
309
310 // Timezone information. We need to have static buffers for the
311 // timezone names because we return pointers to these in
312 // LocalTimezone().
313 static bool tz_initialized_;
314 static TIME_ZONE_INFORMATION tzinfo_;
315 static char std_tz_name_[kTzNameSize];
316 static char dst_tz_name_[kTzNameSize];
317
318 // Initialize the timezone information (if not already done).
319 static void TzSet();
320
321 // Guess the name of the timezone from the bias.
322 static const char* GuessTimezoneNameFromBias(int bias);
323
324 // Return whether or not daylight savings time is in effect at this time.
325 bool InDST();
326
327 // Return the difference (in milliseconds) between this timestamp and
328 // another timestamp.
329 int64_t Diff(Time* other);
330
331 // Accessor for FILETIME representation.
332 FILETIME& ft() { return time_.ft_; }
333
334 // Accessor for integer representation.
335 int64_t& t() { return time_.t_; }
336
337 // Although win32 uses 64-bit integers for representing timestamps,
338 // these are packed into a FILETIME structure. The FILETIME structure
339 // is just a struct representing a 64-bit integer. The TimeStamp union
340 // allows access to both a FILETIME and an integer representation of
341 // the timestamp.
342 union TimeStamp {
343 FILETIME ft_;
344 int64_t t_;
345 };
346
347 TimeStamp time_;
348};
349
350// Static variables.
351bool Time::tz_initialized_ = false;
352TIME_ZONE_INFORMATION Time::tzinfo_;
353char Time::std_tz_name_[kTzNameSize];
354char Time::dst_tz_name_[kTzNameSize];
355
356
357// Initialize timestamp to start of epoc.
358Time::Time() {
359 t() = 0;
360}
361
362
363// Initialize timestamp from a JavaScript timestamp.
364Time::Time(double jstime) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000365 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000366}
367
368
369// Initialize timestamp from date/time components.
370Time::Time(int year, int mon, int day, int hour, int min, int sec) {
371 SYSTEMTIME st;
372 st.wYear = year;
373 st.wMonth = mon;
374 st.wDay = day;
375 st.wHour = hour;
376 st.wMinute = min;
377 st.wSecond = sec;
378 st.wMilliseconds = 0;
379 SystemTimeToFileTime(&st, &ft());
380}
381
382
383// Convert timestamp to JavaScript timestamp.
384double Time::ToJSTime() {
385 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
386}
387
388
389// Guess the name of the timezone from the bias.
390// The guess is very biased towards the northern hemisphere.
391const char* Time::GuessTimezoneNameFromBias(int bias) {
392 static const int kHour = 60;
393 switch (-bias) {
394 case -9*kHour: return "Alaska";
395 case -8*kHour: return "Pacific";
396 case -7*kHour: return "Mountain";
397 case -6*kHour: return "Central";
398 case -5*kHour: return "Eastern";
399 case -4*kHour: return "Atlantic";
400 case 0*kHour: return "GMT";
401 case +1*kHour: return "Central Europe";
402 case +2*kHour: return "Eastern Europe";
403 case +3*kHour: return "Russia";
404 case +5*kHour + 30: return "India";
405 case +8*kHour: return "China";
406 case +9*kHour: return "Japan";
407 case +12*kHour: return "New Zealand";
408 default: return "Local";
409 }
410}
411
412
413// Initialize timezone information. The timezone information is obtained from
414// windows. If we cannot get the timezone information we fall back to CET.
415// Please notice that this code is not thread-safe.
416void Time::TzSet() {
417 // Just return if timezone information has already been initialized.
418 if (tz_initialized_) return;
419
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000420 // Initialize POSIX time zone data.
421 _tzset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000422 // Obtain timezone information from operating system.
423 memset(&tzinfo_, 0, sizeof(tzinfo_));
424 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
425 // If we cannot get timezone information we fall back to CET.
426 tzinfo_.Bias = -60;
427 tzinfo_.StandardDate.wMonth = 10;
428 tzinfo_.StandardDate.wDay = 5;
429 tzinfo_.StandardDate.wHour = 3;
430 tzinfo_.StandardBias = 0;
431 tzinfo_.DaylightDate.wMonth = 3;
432 tzinfo_.DaylightDate.wDay = 5;
433 tzinfo_.DaylightDate.wHour = 2;
434 tzinfo_.DaylightBias = -60;
435 }
436
437 // Make standard and DST timezone names.
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000438 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
439 std_tz_name_, kTzNameSize, NULL, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000440 std_tz_name_[kTzNameSize - 1] = '\0';
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000441 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
442 dst_tz_name_, kTzNameSize, NULL, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443 dst_tz_name_[kTzNameSize - 1] = '\0';
444
445 // If OS returned empty string or resource id (like "@tzres.dll,-211")
446 // simply guess the name from the UTC bias of the timezone.
447 // To properly resolve the resource identifier requires a library load,
448 // which is not possible in a sandbox.
449 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000450 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
451 "%s Standard Time",
452 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000453 }
454 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000455 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
456 "%s Daylight Time",
457 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000458 }
459
460 // Timezone information initialized.
461 tz_initialized_ = true;
462}
463
464
465// Return the difference in milliseconds between this and another timestamp.
466int64_t Time::Diff(Time* other) {
467 return (t() - other->t()) / kTimeScaler;
468}
469
470
471// Set timestamp to current time.
472void Time::SetToCurrentTime() {
473 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
474 // Because we're fast, we like fast timers which have at least a
475 // 1ms resolution.
476 //
477 // timeGetTime() provides 1ms granularity when combined with
478 // timeBeginPeriod(). If the host application for v8 wants fast
479 // timers, it can use timeBeginPeriod to increase the resolution.
480 //
481 // Using timeGetTime() has a drawback because it is a 32bit value
482 // and hence rolls-over every ~49days.
483 //
484 // To use the clock, we use GetSystemTimeAsFileTime as our base;
485 // and then use timeGetTime to extrapolate current time from the
486 // start time. To deal with rollovers, we resync the clock
487 // any time when more than kMaxClockElapsedTime has passed or
488 // whenever timeGetTime creates a rollover.
489
490 static bool initialized = false;
491 static TimeStamp init_time;
492 static DWORD init_ticks;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000493 static const int64_t kHundredNanosecondsPerSecond = 10000000;
494 static const int64_t kMaxClockElapsedTime =
495 60*kHundredNanosecondsPerSecond; // 1 minute
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000496
497 // If we are uninitialized, we need to resync the clock.
498 bool needs_resync = !initialized;
499
500 // Get the current time.
501 TimeStamp time_now;
502 GetSystemTimeAsFileTime(&time_now.ft_);
503 DWORD ticks_now = timeGetTime();
504
505 // Check if we need to resync due to clock rollover.
506 needs_resync |= ticks_now < init_ticks;
507
508 // Check if we need to resync due to elapsed time.
509 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
510
511 // Resync the clock if necessary.
512 if (needs_resync) {
513 GetSystemTimeAsFileTime(&init_time.ft_);
514 init_ticks = ticks_now = timeGetTime();
515 initialized = true;
516 }
517
518 // Finally, compute the actual time. Why is this so hard.
519 DWORD elapsed = ticks_now - init_ticks;
520 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
521}
522
523
524// Return the local timezone offset in milliseconds east of UTC. This
525// takes into account whether daylight saving is in effect at the time.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000526// Only times in the 32-bit Unix range may be passed to this function.
527// Also, adding the time-zone offset to the input must not overflow.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000528// The function EquivalentTime() in date.js guarantees this.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000529int64_t Time::LocalOffset() {
530 // Initialize timezone information, if needed.
531 TzSet();
532
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000533 Time rounded_to_second(*this);
534 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
535 1000 * kTimeScaler;
536 // Convert to local time using POSIX localtime function.
537 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
538 // very slow. Other browsers use localtime().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000539
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000540 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
541 // POSIX seconds past 1/1/1970 0:00:00.
542 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
543 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
544 return 0;
545 }
546 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
547 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000549 // Convert to local time, as struct with fields for day, hour, year, etc.
550 tm posix_local_time_struct;
551 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
552 // Convert local time in struct to POSIX time as if it were a UTC time.
553 time_t local_posix_time = _mkgmtime(&posix_local_time_struct);
554 Time localtime(1000.0 * local_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000556 return localtime.Diff(&rounded_to_second);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557}
558
559
560// Return whether or not daylight savings time is in effect at this time.
561bool Time::InDST() {
562 // Initialize timezone information, if needed.
563 TzSet();
564
565 // Determine if DST is in effect at the specified time.
566 bool in_dst = false;
567 if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) {
568 // Get the local timezone offset for the timestamp in milliseconds.
569 int64_t offset = LocalOffset();
570
571 // Compute the offset for DST. The bias parameters in the timezone info
572 // are specified in minutes. These must be converted to milliseconds.
573 int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute;
574
575 // If the local time offset equals the timezone bias plus the daylight
576 // bias then DST is in effect.
577 in_dst = offset == dstofs;
578 }
579
580 return in_dst;
581}
582
583
ager@chromium.org32912102009-01-16 10:38:43 +0000584// Return the daylight savings time offset for this time.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585int64_t Time::DaylightSavingsOffset() {
586 return InDST() ? 60 * kMsPerMinute : 0;
587}
588
589
590// Returns a string identifying the current timezone for the
591// timestamp taking into account daylight saving.
592char* Time::LocalTimezone() {
593 // Return the standard or DST time zone name based on whether daylight
594 // saving is in effect at the given time.
595 return InDST() ? dst_tz_name_ : std_tz_name_;
596}
597
598
599void OS::Setup() {
600 // Seed the random number generator.
ager@chromium.orgef7cd1f2010-11-29 14:33:17 +0000601 // Convert the current time to a 64-bit integer first, before converting it
602 // to an unsigned. Going directly can cause an overflow and the seed to be
603 // set to all ones. The seed will be identical for different instances that
604 // call this setup code within the same millisecond.
605 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000606 srand(static_cast<unsigned int>(seed));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000607 limit_mutex = CreateMutex();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000608}
609
610
611// Returns the accumulated user time for thread.
612int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
613 FILETIME dummy;
614 uint64_t usertime;
615
616 // Get the amount of time that the thread has executed in user mode.
617 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
618 reinterpret_cast<FILETIME*>(&usertime))) return -1;
619
620 // Adjust the resolution to micro-seconds.
621 usertime /= 10;
622
623 // Convert to seconds and microseconds
624 *secs = static_cast<uint32_t>(usertime / 1000000);
625 *usecs = static_cast<uint32_t>(usertime % 1000000);
626 return 0;
627}
628
629
630// Returns current time as the number of milliseconds since
631// 00:00:00 UTC, January 1, 1970.
632double OS::TimeCurrentMillis() {
633 Time t;
634 t.SetToCurrentTime();
635 return t.ToJSTime();
636}
637
638// Returns the tickcounter based on timeGetTime.
639int64_t OS::Ticks() {
640 return timeGetTime() * 1000; // Convert to microseconds.
641}
642
643
644// Returns a string identifying the current timezone taking into
645// account daylight saving.
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000646const char* OS::LocalTimezone(double time) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000647 return Time(time).LocalTimezone();
648}
649
650
kasper.lund7276f142008-07-30 08:49:36 +0000651// Returns the local time offset in milliseconds east of UTC without
652// taking daylight savings time into account.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653double OS::LocalTimeOffset() {
kasper.lund7276f142008-07-30 08:49:36 +0000654 // Use current time, rounded to the millisecond.
655 Time t(TimeCurrentMillis());
656 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
657 return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000658}
659
660
661// Returns the daylight savings offset in milliseconds for the given
662// time.
663double OS::DaylightSavingsOffset(double time) {
664 int64_t offset = Time(time).DaylightSavingsOffset();
665 return static_cast<double>(offset);
666}
667
668
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000669int OS::GetLastError() {
670 return ::GetLastError();
671}
672
673
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000674// ----------------------------------------------------------------------------
675// Win32 console output.
676//
677// If a Win32 application is linked as a console application it has a normal
678// standard output and standard error. In this case normal printf works fine
679// for output. However, if the application is linked as a GUI application,
680// the process doesn't have a console, and therefore (debugging) output is lost.
681// This is the case if we are embedded in a windows program (like a browser).
682// In order to be able to get debug output in this case the the debugging
683// facility using OutputDebugString. This output goes to the active debugger
684// for the process (if any). Else the output can be monitored using DBMON.EXE.
685
686enum OutputMode {
687 UNKNOWN, // Output method has not yet been determined.
688 CONSOLE, // Output is written to stdout.
689 ODS // Output is written to debug facility.
690};
691
692static OutputMode output_mode = UNKNOWN; // Current output mode.
693
694
695// Determine if the process has a console for output.
696static bool HasConsole() {
697 // Only check the first time. Eventual race conditions are not a problem,
698 // because all threads will eventually determine the same mode.
699 if (output_mode == UNKNOWN) {
700 // We cannot just check that the standard output is attached to a console
701 // because this would fail if output is redirected to a file. Therefore we
702 // say that a process does not have an output console if either the
703 // standard output handle is invalid or its file type is unknown.
704 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
705 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
706 output_mode = CONSOLE;
707 else
708 output_mode = ODS;
709 }
710 return output_mode == CONSOLE;
711}
712
713
714static void VPrintHelper(FILE* stream, const char* format, va_list args) {
715 if (HasConsole()) {
716 vfprintf(stream, format, args);
717 } else {
718 // It is important to use safe print here in order to avoid
719 // overflowing the buffer. We might truncate the output, but this
720 // does not crash.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000721 EmbeddedVector<char, 4096> buffer;
722 OS::VSNPrintF(buffer, format, args);
723 OutputDebugStringA(buffer.start());
724 }
725}
726
727
728FILE* OS::FOpen(const char* path, const char* mode) {
729 FILE* result;
730 if (fopen_s(&result, path, mode) == 0) {
731 return result;
732 } else {
733 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000734 }
735}
736
737
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000738bool OS::Remove(const char* path) {
739 return (DeleteFileA(path) != 0);
740}
741
742
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000743FILE* OS::OpenTemporaryFile() {
744 // tmpfile_s tries to use the root dir, don't use it.
745 char tempPathBuffer[MAX_PATH];
746 DWORD path_result = 0;
747 path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
748 if (path_result > MAX_PATH || path_result == 0) return NULL;
749 UINT name_result = 0;
750 char tempNameBuffer[MAX_PATH];
751 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
752 if (name_result == 0) return NULL;
753 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
754 if (result != NULL) {
755 Remove(tempNameBuffer); // Delete on close.
756 }
757 return result;
758}
759
760
ager@chromium.org71daaf62009-04-01 07:22:49 +0000761// Open log file in binary mode to avoid /n -> /r/n conversion.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000762const char* const OS::LogFileOpenMode = "wb";
ager@chromium.org71daaf62009-04-01 07:22:49 +0000763
764
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000765// Print (debug) message to console.
766void OS::Print(const char* format, ...) {
767 va_list args;
768 va_start(args, format);
769 VPrint(format, args);
770 va_end(args);
771}
772
773
774void OS::VPrint(const char* format, va_list args) {
775 VPrintHelper(stdout, format, args);
776}
777
778
whesse@chromium.org023421e2010-12-21 12:19:12 +0000779void OS::FPrint(FILE* out, const char* format, ...) {
780 va_list args;
781 va_start(args, format);
782 VFPrint(out, format, args);
783 va_end(args);
784}
785
786
787void OS::VFPrint(FILE* out, const char* format, va_list args) {
788 VPrintHelper(out, format, args);
789}
790
791
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000792// Print error message to console.
793void OS::PrintError(const char* format, ...) {
794 va_list args;
795 va_start(args, format);
796 VPrintError(format, args);
797 va_end(args);
798}
799
800
801void OS::VPrintError(const char* format, va_list args) {
802 VPrintHelper(stderr, format, args);
803}
804
805
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000806int OS::SNPrintF(Vector<char> str, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807 va_list args;
808 va_start(args, format);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000809 int result = VSNPrintF(str, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000810 va_end(args);
811 return result;
812}
813
814
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000815int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
816 int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 // Make sure to zero-terminate the string if the output was
818 // truncated or if there was an error.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000819 if (n < 0 || n >= str.length()) {
whesse@chromium.org023421e2010-12-21 12:19:12 +0000820 if (str.length() > 0)
821 str[str.length() - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000822 return -1;
823 } else {
824 return n;
825 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826}
827
828
ager@chromium.org381abbb2009-02-25 13:23:22 +0000829char* OS::StrChr(char* str, int c) {
830 return const_cast<char*>(strchr(str, c));
831}
832
833
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000834void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000835 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
836 size_t buffer_size = static_cast<size_t>(dest.length());
837 if (n + 1 > buffer_size) // count for trailing '\0'
838 n = _TRUNCATE;
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000839 int result = strncpy_s(dest.start(), dest.length(), src, n);
840 USE(result);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000841 ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000842}
843
844
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000845// We keep the lowest and highest addresses mapped as a quick way of
846// determining that pointers are outside the heap (used mostly in assertions
847// and verification). The estimate is conservative, ie, not all addresses in
848// 'allocated' space are actually allocated to our heap. The range is
849// [lowest, highest), inclusive on the low and and exclusive on the high end.
850static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
851static void* highest_ever_allocated = reinterpret_cast<void*>(0);
852
853
854static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000855 ASSERT(limit_mutex != NULL);
856 ScopedLock lock(limit_mutex);
857
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000858 lowest_ever_allocated = Min(lowest_ever_allocated, address);
859 highest_ever_allocated =
860 Max(highest_ever_allocated,
861 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
862}
863
864
865bool OS::IsOutsideAllocatedSpace(void* pointer) {
866 if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated)
867 return true;
868 // Ask the Windows API
869 if (IsBadWritePtr(pointer, 1))
870 return true;
871 return false;
872}
873
874
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000875// Get the system's page size used by VirtualAlloc() or the next power
876// of two. The reason for always returning a power of two is that the
877// rounding up in OS::Allocate expects that.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878static size_t GetPageSize() {
879 static size_t page_size = 0;
880 if (page_size == 0) {
881 SYSTEM_INFO info;
882 GetSystemInfo(&info);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000883 page_size = RoundUpToPowerOf2(info.dwPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000884 }
885 return page_size;
886}
887
888
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000889// The allocation alignment is the guaranteed alignment for
890// VirtualAlloc'ed blocks of memory.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000891size_t OS::AllocateAlignment() {
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000892 static size_t allocate_alignment = 0;
893 if (allocate_alignment == 0) {
894 SYSTEM_INFO info;
895 GetSystemInfo(&info);
896 allocate_alignment = info.dwAllocationGranularity;
897 }
898 return allocate_alignment;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000899}
900
901
kasper.lund7276f142008-07-30 08:49:36 +0000902void* OS::Allocate(const size_t requested,
903 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000904 bool is_executable) {
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000905 // The address range used to randomize RWX allocations in OS::Allocate
906 // Try not to map pages into the default range that windows loads DLLs
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000907 // Use a multiple of 64k to prevent committing unused memory.
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000908 // Note: This does not guarantee RWX regions will be within the
909 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
910#ifdef V8_HOST_ARCH_64_BIT
911 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000912 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000913#else
914 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000915 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000916#endif
917
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000918 // VirtualAlloc rounds allocated size to page size automatically.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000919 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000920 intptr_t address = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000921
922 // Windows XP SP2 allows Data Excution Prevention (DEP).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000923 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000924
925 // For exectutable pages try and randomize the allocation address
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000926 if (prot == PAGE_EXECUTE_READWRITE &&
927 msize >= static_cast<size_t>(Page::kPageSize)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000928 address = (V8::RandomPrivate(Isolate::Current()) << kPageSizeBits)
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000929 | kAllocationRandomAddressMin;
930 address &= kAllocationRandomAddressMax;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000931 }
932
933 LPVOID mbase = VirtualAlloc(reinterpret_cast<void *>(address),
934 msize,
935 MEM_COMMIT | MEM_RESERVE,
936 prot);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000937 if (mbase == NULL && address != 0)
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000938 mbase = VirtualAlloc(NULL, msize, MEM_COMMIT | MEM_RESERVE, prot);
939
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000940 if (mbase == NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000941 LOG(ISOLATE, StringEvent("OS::Allocate", "VirtualAlloc failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000942 return NULL;
943 }
944
945 ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
946
947 *allocated = msize;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000948 UpdateAllocatedSpaceLimits(mbase, static_cast<int>(msize));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000949 return mbase;
950}
951
952
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000953void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000954 // TODO(1240712): VirtualFree has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000955 VirtualFree(address, 0, MEM_RELEASE);
956 USE(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000957}
958
959
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000960void OS::ProtectCode(void* address, const size_t size) {
961 DWORD old_protect;
962 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
963}
964
965
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000966void OS::Guard(void* address, const size_t size) {
967 DWORD oldprotect;
968 VirtualProtect(address, size, PAGE_READONLY | PAGE_GUARD, &oldprotect);
969}
970
971
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000972void OS::Sleep(int milliseconds) {
973 ::Sleep(milliseconds);
974}
975
976
977void OS::Abort() {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000978 if (!IsDebuggerPresent()) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000979#ifdef _MSC_VER
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000980 // Make the MSVCRT do a silent abort.
981 _set_abort_behavior(0, _WRITE_ABORT_MSG);
982 _set_abort_behavior(0, _CALL_REPORTFAULT);
iposva@chromium.org245aa852009-02-10 00:49:54 +0000983#endif // _MSC_VER
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000984 abort();
985 } else {
986 DebugBreak();
987 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000988}
989
990
kasper.lund7276f142008-07-30 08:49:36 +0000991void OS::DebugBreak() {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000992#ifdef _MSC_VER
kasper.lund7276f142008-07-30 08:49:36 +0000993 __debugbreak();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000994#else
995 ::DebugBreak();
996#endif
kasper.lund7276f142008-07-30 08:49:36 +0000997}
998
999
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001000class Win32MemoryMappedFile : public OS::MemoryMappedFile {
1001 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001002 Win32MemoryMappedFile(HANDLE file,
1003 HANDLE file_mapping,
1004 void* memory,
1005 int size)
1006 : file_(file),
1007 file_mapping_(file_mapping),
1008 memory_(memory),
1009 size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001010 virtual ~Win32MemoryMappedFile();
1011 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001012 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001013 private:
1014 HANDLE file_;
1015 HANDLE file_mapping_;
1016 void* memory_;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001017 int size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001018};
1019
1020
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001021OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
1022 // Open a physical file
1023 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
1024 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +00001025 if (file == INVALID_HANDLE_VALUE) return NULL;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001026
1027 int size = static_cast<int>(GetFileSize(file, NULL));
1028
1029 // Create a file mapping for the physical file
1030 HANDLE file_mapping = CreateFileMapping(file, NULL,
1031 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
1032 if (file_mapping == NULL) return NULL;
1033
1034 // Map a view of the file into memory
1035 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
1036 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
1037}
1038
1039
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001040OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
1041 void* initial) {
1042 // Open a physical file
1043 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
1044 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
1045 if (file == NULL) return NULL;
1046 // Create a file mapping for the physical file
1047 HANDLE file_mapping = CreateFileMapping(file, NULL,
1048 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
1049 if (file_mapping == NULL) return NULL;
1050 // Map a view of the file into memory
1051 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
1052 if (memory) memmove(memory, initial, size);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001053 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001054}
1055
1056
1057Win32MemoryMappedFile::~Win32MemoryMappedFile() {
1058 if (memory_ != NULL)
1059 UnmapViewOfFile(memory_);
1060 CloseHandle(file_mapping_);
1061 CloseHandle(file_);
1062}
1063
1064
1065// The following code loads functions defined in DbhHelp.h and TlHelp32.h
ager@chromium.org32912102009-01-16 10:38:43 +00001066// dynamically. This is to avoid being depending on dbghelp.dll and
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
1068// kernel32.dll at some point so loading functions defines in TlHelp32.h
1069// dynamically might not be necessary any more - for some versions of Windows?).
1070
1071// Function pointers to functions dynamically loaded from dbghelp.dll.
1072#define DBGHELP_FUNCTION_LIST(V) \
1073 V(SymInitialize) \
1074 V(SymGetOptions) \
1075 V(SymSetOptions) \
1076 V(SymGetSearchPath) \
1077 V(SymLoadModule64) \
1078 V(StackWalk64) \
1079 V(SymGetSymFromAddr64) \
1080 V(SymGetLineFromAddr64) \
1081 V(SymFunctionTableAccess64) \
1082 V(SymGetModuleBase64)
1083
1084// Function pointers to functions dynamically loaded from dbghelp.dll.
1085#define TLHELP32_FUNCTION_LIST(V) \
1086 V(CreateToolhelp32Snapshot) \
1087 V(Module32FirstW) \
1088 V(Module32NextW)
1089
1090// Define the decoration to use for the type and variable name used for
1091// dynamically loaded DLL function..
1092#define DLL_FUNC_TYPE(name) _##name##_
1093#define DLL_FUNC_VAR(name) _##name
1094
1095// Define the type for each dynamically loaded DLL function. The function
1096// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1097// from the Windows include files are redefined here to have the function
1098// definitions to be as close to the ones in the original .h files as possible.
1099#ifndef IN
1100#define IN
1101#endif
1102#ifndef VOID
1103#define VOID void
1104#endif
1105
iposva@chromium.org245aa852009-02-10 00:49:54 +00001106// DbgHelp isn't supported on MinGW yet
1107#ifndef __MINGW32__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001108// DbgHelp.h functions.
1109typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
1110 IN PSTR UserSearchPath,
1111 IN BOOL fInvadeProcess);
1112typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
1113typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
1114typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
1115 IN HANDLE hProcess,
1116 OUT PSTR SearchPath,
1117 IN DWORD SearchPathLength);
1118typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
1119 IN HANDLE hProcess,
1120 IN HANDLE hFile,
1121 IN PSTR ImageName,
1122 IN PSTR ModuleName,
1123 IN DWORD64 BaseOfDll,
1124 IN DWORD SizeOfDll);
1125typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
1126 DWORD MachineType,
1127 HANDLE hProcess,
1128 HANDLE hThread,
1129 LPSTACKFRAME64 StackFrame,
1130 PVOID ContextRecord,
1131 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1132 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1133 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1134 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1135typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
1136 IN HANDLE hProcess,
1137 IN DWORD64 qwAddr,
1138 OUT PDWORD64 pdwDisplacement,
1139 OUT PIMAGEHLP_SYMBOL64 Symbol);
1140typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
1141 IN HANDLE hProcess,
1142 IN DWORD64 qwAddr,
1143 OUT PDWORD pdwDisplacement,
1144 OUT PIMAGEHLP_LINE64 Line64);
1145// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1146typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
1147 HANDLE hProcess,
1148 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1149typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1150 HANDLE hProcess,
1151 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1152
1153// TlHelp32.h functions.
1154typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1155 DWORD dwFlags,
1156 DWORD th32ProcessID);
1157typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1158 LPMODULEENTRY32W lpme);
1159typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1160 LPMODULEENTRY32W lpme);
1161
1162#undef IN
1163#undef VOID
1164
1165// Declare a variable for each dynamically loaded DLL function.
1166#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1167DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1168TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1169#undef DEF_DLL_FUNCTION
1170
1171// Load the functions. This function has a lot of "ugly" macros in order to
1172// keep down code duplication.
1173
1174static bool LoadDbgHelpAndTlHelp32() {
1175 static bool dbghelp_loaded = false;
1176
1177 if (dbghelp_loaded) return true;
1178
1179 HMODULE module;
1180
1181 // Load functions from the dbghelp.dll module.
1182 module = LoadLibrary(TEXT("dbghelp.dll"));
1183 if (module == NULL) {
1184 return false;
1185 }
1186
1187#define LOAD_DLL_FUNC(name) \
1188 DLL_FUNC_VAR(name) = \
1189 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1190
1191DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1192
1193#undef LOAD_DLL_FUNC
1194
1195 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1196 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1197 module = LoadLibrary(TEXT("kernel32.dll"));
1198 if (module == NULL) {
1199 return false;
1200 }
1201
1202#define LOAD_DLL_FUNC(name) \
1203 DLL_FUNC_VAR(name) = \
1204 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1205
1206TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1207
1208#undef LOAD_DLL_FUNC
1209
1210 // Check that all functions where loaded.
1211 bool result =
1212#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1213
1214DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1215TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1216
1217#undef DLL_FUNC_LOADED
1218 true;
1219
1220 dbghelp_loaded = result;
1221 return result;
ager@chromium.org32912102009-01-16 10:38:43 +00001222 // NOTE: The modules are never unloaded and will stay around until the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001223 // application is closed.
1224}
1225
1226
1227// Load the symbols for generating stack traces.
1228static bool LoadSymbols(HANDLE process_handle) {
1229 static bool symbols_loaded = false;
1230
1231 if (symbols_loaded) return true;
1232
1233 BOOL ok;
1234
1235 // Initialize the symbol engine.
1236 ok = _SymInitialize(process_handle, // hProcess
1237 NULL, // UserSearchPath
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001238 false); // fInvadeProcess
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001239 if (!ok) return false;
1240
1241 DWORD options = _SymGetOptions();
1242 options |= SYMOPT_LOAD_LINES;
1243 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1244 options = _SymSetOptions(options);
1245
1246 char buf[OS::kStackWalkMaxNameLen] = {0};
1247 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1248 if (!ok) {
1249 int err = GetLastError();
1250 PrintF("%d\n", err);
1251 return false;
1252 }
1253
1254 HANDLE snapshot = _CreateToolhelp32Snapshot(
1255 TH32CS_SNAPMODULE, // dwFlags
1256 GetCurrentProcessId()); // th32ProcessId
1257 if (snapshot == INVALID_HANDLE_VALUE) return false;
1258 MODULEENTRY32W module_entry;
1259 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1260 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1261 while (cont) {
1262 DWORD64 base;
1263 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1264 // both unicode and ASCII strings even though the parameter is PSTR.
1265 base = _SymLoadModule64(
1266 process_handle, // hProcess
1267 0, // hFile
1268 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1269 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1270 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1271 module_entry.modBaseSize); // SizeOfDll
1272 if (base == 0) {
1273 int err = GetLastError();
1274 if (err != ERROR_MOD_NOT_FOUND &&
1275 err != ERROR_INVALID_HANDLE) return false;
1276 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001277 LOG(i::Isolate::Current(),
1278 SharedLibraryEvent(
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001279 module_entry.szExePath,
1280 reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1281 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1282 module_entry.modBaseSize)));
1283 cont = _Module32NextW(snapshot, &module_entry);
1284 }
1285 CloseHandle(snapshot);
1286
1287 symbols_loaded = true;
1288 return true;
1289}
1290
1291
1292void OS::LogSharedLibraryAddresses() {
1293 // SharedLibraryEvents are logged when loading symbol information.
1294 // Only the shared libraries loaded at the time of the call to
1295 // LogSharedLibraryAddresses are logged. DLLs loaded after
1296 // initialization are not accounted for.
1297 if (!LoadDbgHelpAndTlHelp32()) return;
1298 HANDLE process_handle = GetCurrentProcess();
1299 LoadSymbols(process_handle);
1300}
1301
1302
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00001303void OS::SignalCodeMovingGC() {
1304}
1305
1306
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001307// Walk the stack using the facilities in dbghelp.dll and tlhelp32.dll
1308
1309// Switch off warning 4748 (/GS can not protect parameters and local variables
1310// from local buffer overrun because optimizations are disabled in function) as
1311// it is triggered by the use of inline assembler.
1312#pragma warning(push)
1313#pragma warning(disable : 4748)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001314int OS::StackWalk(Vector<OS::StackFrame> frames) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001315 BOOL ok;
1316
1317 // Load the required functions from DLL's.
1318 if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError;
1319
1320 // Get the process and thread handles.
1321 HANDLE process_handle = GetCurrentProcess();
1322 HANDLE thread_handle = GetCurrentThread();
1323
1324 // Read the symbols.
1325 if (!LoadSymbols(process_handle)) return kStackWalkError;
1326
1327 // Capture current context.
1328 CONTEXT context;
ager@chromium.org3811b432009-10-28 14:53:37 +00001329 RtlCaptureContext(&context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001330
1331 // Initialize the stack walking
1332 STACKFRAME64 stack_frame;
1333 memset(&stack_frame, 0, sizeof(stack_frame));
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001334#ifdef _WIN64
1335 stack_frame.AddrPC.Offset = context.Rip;
1336 stack_frame.AddrFrame.Offset = context.Rbp;
1337 stack_frame.AddrStack.Offset = context.Rsp;
1338#else
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001339 stack_frame.AddrPC.Offset = context.Eip;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001340 stack_frame.AddrFrame.Offset = context.Ebp;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001341 stack_frame.AddrStack.Offset = context.Esp;
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001342#endif
1343 stack_frame.AddrPC.Mode = AddrModeFlat;
1344 stack_frame.AddrFrame.Mode = AddrModeFlat;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001345 stack_frame.AddrStack.Mode = AddrModeFlat;
1346 int frames_count = 0;
1347
1348 // Collect stack frames.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001349 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001350 while (frames_count < frames_size) {
1351 ok = _StackWalk64(
1352 IMAGE_FILE_MACHINE_I386, // MachineType
1353 process_handle, // hProcess
1354 thread_handle, // hThread
1355 &stack_frame, // StackFrame
1356 &context, // ContextRecord
1357 NULL, // ReadMemoryRoutine
1358 _SymFunctionTableAccess64, // FunctionTableAccessRoutine
1359 _SymGetModuleBase64, // GetModuleBaseRoutine
1360 NULL); // TranslateAddress
1361 if (!ok) break;
1362
1363 // Store the address.
1364 ASSERT((stack_frame.AddrPC.Offset >> 32) == 0); // 32-bit address.
1365 frames[frames_count].address =
1366 reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
1367
1368 // Try to locate a symbol for this frame.
1369 DWORD64 symbol_displacement;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001370 SmartPointer<IMAGEHLP_SYMBOL64> symbol(
1371 NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen));
1372 if (symbol.is_empty()) return kStackWalkError; // Out of memory.
1373 memset(*symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
1374 (*symbol)->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
1375 (*symbol)->MaxNameLength = kStackWalkMaxNameLen;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001376 ok = _SymGetSymFromAddr64(process_handle, // hProcess
1377 stack_frame.AddrPC.Offset, // Address
1378 &symbol_displacement, // Displacement
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001379 *symbol); // Symbol
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001380 if (ok) {
1381 // Try to locate more source information for the symbol.
1382 IMAGEHLP_LINE64 Line;
1383 memset(&Line, 0, sizeof(Line));
1384 Line.SizeOfStruct = sizeof(Line);
1385 DWORD line_displacement;
1386 ok = _SymGetLineFromAddr64(
1387 process_handle, // hProcess
1388 stack_frame.AddrPC.Offset, // dwAddr
1389 &line_displacement, // pdwDisplacement
1390 &Line); // Line
1391 // Format a text representation of the frame based on the information
1392 // available.
1393 if (ok) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001394 SNPrintF(MutableCStrVector(frames[frames_count].text,
1395 kStackWalkMaxTextLen),
1396 "%s %s:%d:%d",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001397 (*symbol)->Name, Line.FileName, Line.LineNumber,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001398 line_displacement);
1399 } else {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001400 SNPrintF(MutableCStrVector(frames[frames_count].text,
1401 kStackWalkMaxTextLen),
1402 "%s",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001403 (*symbol)->Name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001404 }
1405 // Make sure line termination is in place.
1406 frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
1407 } else {
1408 // No text representation of this frame
1409 frames[frames_count].text[0] = '\0';
1410
1411 // Continue if we are just missing a module (for non C/C++ frames a
1412 // module will never be found).
1413 int err = GetLastError();
1414 if (err != ERROR_MOD_NOT_FOUND) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001415 break;
1416 }
1417 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001418
1419 frames_count++;
1420 }
1421
1422 // Return the number of frames filled in.
1423 return frames_count;
1424}
1425
1426// Restore warnings to previous settings.
1427#pragma warning(pop)
1428
iposva@chromium.org245aa852009-02-10 00:49:54 +00001429#else // __MINGW32__
1430void OS::LogSharedLibraryAddresses() { }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001431void OS::SignalCodeMovingGC() { }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001432int OS::StackWalk(Vector<OS::StackFrame> frames) { return 0; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001433#endif // __MINGW32__
1434
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001435
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001436uint64_t OS::CpuFeaturesImpliedByPlatform() {
1437 return 0; // Windows runs on anything.
1438}
1439
1440
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441double OS::nan_value() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001442#ifdef _MSC_VER
ager@chromium.org3811b432009-10-28 14:53:37 +00001443 // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
1444 // in mask set, so value equals mask.
1445 static const __int64 nanval = kQuietNaNMask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001446 return *reinterpret_cast<const double*>(&nanval);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001447#else // _MSC_VER
1448 return NAN;
1449#endif // _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001450}
1451
ager@chromium.org236ad962008-09-25 09:45:57 +00001452
1453int OS::ActivationFrameAlignment() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001454#ifdef _WIN64
1455 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1456#else
1457 return 8; // Floating-point math runs faster with 8-byte alignment.
1458#endif
ager@chromium.org236ad962008-09-25 09:45:57 +00001459}
1460
1461
kmillikin@chromium.org9155e252010-05-26 13:27:57 +00001462void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
1463 MemoryBarrier();
1464 *ptr = value;
1465}
1466
1467
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001468bool VirtualMemory::IsReserved() {
1469 return address_ != NULL;
1470}
1471
1472
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001473VirtualMemory::VirtualMemory(size_t size) {
1474 address_ = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001475 size_ = size;
1476}
1477
1478
1479VirtualMemory::~VirtualMemory() {
1480 if (IsReserved()) {
1481 if (0 == VirtualFree(address(), 0, MEM_RELEASE)) address_ = NULL;
1482 }
1483}
1484
1485
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00001486bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1487 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
kasper.lund7276f142008-07-30 08:49:36 +00001488 if (NULL == VirtualAlloc(address, size, MEM_COMMIT, prot)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001489 return false;
1490 }
1491
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001492 UpdateAllocatedSpaceLimits(address, static_cast<int>(size));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001493 return true;
1494}
1495
1496
1497bool VirtualMemory::Uncommit(void* address, size_t size) {
1498 ASSERT(IsReserved());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001499 return VirtualFree(address, size, MEM_DECOMMIT) != false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001500}
1501
1502
1503// ----------------------------------------------------------------------------
1504// Win32 thread support.
1505
1506// Definition of invalid thread handle and id.
1507static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001508
1509// Entry point for threads. The supplied argument is a pointer to the thread
1510// object. The entry function dispatches to the run method in the thread
1511// object. It is important that this function has __stdcall calling
1512// convention.
1513static unsigned int __stdcall ThreadEntry(void* arg) {
1514 Thread* thread = reinterpret_cast<Thread*>(arg);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001515 thread->Run();
1516 return 0;
1517}
1518
1519
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001520class Thread::PlatformData : public Malloced {
1521 public:
1522 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1523 HANDLE thread_;
1524};
1525
1526
1527// Initialize a Win32 thread object. The thread has an invalid thread
1528// handle until it is started.
1529
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001530Thread::Thread(const Options& options)
1531 : stack_size_(options.stack_size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001532 data_ = new PlatformData(kNoThread);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001533 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001534}
1535
1536
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001537Thread::Thread(const char* name)
1538 : stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001539 data_ = new PlatformData(kNoThread);
1540 set_name(name);
1541}
1542
1543
1544void Thread::set_name(const char* name) {
erik.corry@gmail.com0511e242011-01-19 11:11:08 +00001545 OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001546 name_[sizeof(name_) - 1] = '\0';
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001547}
1548
1549
1550// Close our own handle for the thread.
1551Thread::~Thread() {
1552 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1553 delete data_;
1554}
1555
1556
1557// Create a new thread. It is important to use _beginthreadex() instead of
1558// the Win32 function CreateThread(), because the CreateThread() does not
1559// initialize thread specific structures in the C runtime library.
1560void Thread::Start() {
1561 data_->thread_ = reinterpret_cast<HANDLE>(
1562 _beginthreadex(NULL,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001563 static_cast<unsigned>(stack_size_),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001564 ThreadEntry,
1565 this,
1566 0,
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001567 NULL));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001568}
1569
1570
1571// Wait for thread to terminate.
1572void Thread::Join() {
1573 WaitForSingleObject(data_->thread_, INFINITE);
1574}
1575
1576
1577Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1578 DWORD result = TlsAlloc();
1579 ASSERT(result != TLS_OUT_OF_INDEXES);
1580 return static_cast<LocalStorageKey>(result);
1581}
1582
1583
1584void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1585 BOOL result = TlsFree(static_cast<DWORD>(key));
1586 USE(result);
1587 ASSERT(result);
1588}
1589
1590
1591void* Thread::GetThreadLocal(LocalStorageKey key) {
1592 return TlsGetValue(static_cast<DWORD>(key));
1593}
1594
1595
1596void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1597 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1598 USE(result);
1599 ASSERT(result);
1600}
1601
1602
1603
1604void Thread::YieldCPU() {
1605 Sleep(0);
1606}
1607
1608
1609// ----------------------------------------------------------------------------
1610// Win32 mutex support.
1611//
1612// On Win32 mutexes are implemented using CRITICAL_SECTION objects. These are
1613// faster than Win32 Mutex objects because they are implemented using user mode
1614// atomic instructions. Therefore we only do ring transitions if there is lock
1615// contention.
1616
1617class Win32Mutex : public Mutex {
1618 public:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001619 Win32Mutex() { InitializeCriticalSection(&cs_); }
1620
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001621 virtual ~Win32Mutex() { DeleteCriticalSection(&cs_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001622
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001623 virtual int Lock() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001624 EnterCriticalSection(&cs_);
1625 return 0;
1626 }
1627
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001628 virtual int Unlock() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629 LeaveCriticalSection(&cs_);
1630 return 0;
1631 }
1632
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001633
1634 virtual bool TryLock() {
1635 // Returns non-zero if critical section is entered successfully entered.
1636 return TryEnterCriticalSection(&cs_);
1637 }
1638
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001639 private:
1640 CRITICAL_SECTION cs_; // Critical section used for mutex
1641};
1642
1643
1644Mutex* OS::CreateMutex() {
1645 return new Win32Mutex();
1646}
1647
1648
1649// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001650// Win32 semaphore support.
1651//
1652// On Win32 semaphores are implemented using Win32 Semaphore objects. The
1653// semaphores are anonymous. Also, the semaphores are initialized to have
1654// no upper limit on count.
1655
1656
1657class Win32Semaphore : public Semaphore {
1658 public:
1659 explicit Win32Semaphore(int count) {
1660 sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
1661 }
1662
1663 ~Win32Semaphore() {
1664 CloseHandle(sem);
1665 }
1666
1667 void Wait() {
1668 WaitForSingleObject(sem, INFINITE);
1669 }
1670
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001671 bool Wait(int timeout) {
1672 // Timeout in Windows API is in milliseconds.
1673 DWORD millis_timeout = timeout / 1000;
1674 return WaitForSingleObject(sem, millis_timeout) != WAIT_TIMEOUT;
1675 }
1676
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001677 void Signal() {
1678 LONG dummy;
1679 ReleaseSemaphore(sem, 1, &dummy);
1680 }
1681
1682 private:
1683 HANDLE sem;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001684};
1685
1686
1687Semaphore* OS::CreateSemaphore(int count) {
1688 return new Win32Semaphore(count);
1689}
1690
ager@chromium.org381abbb2009-02-25 13:23:22 +00001691
1692// ----------------------------------------------------------------------------
1693// Win32 socket support.
1694//
1695
1696class Win32Socket : public Socket {
1697 public:
1698 explicit Win32Socket() {
1699 // Create the socket.
1700 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1701 }
1702 explicit Win32Socket(SOCKET socket): socket_(socket) { }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001703 virtual ~Win32Socket() { Shutdown(); }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001704
1705 // Server initialization.
1706 bool Bind(const int port);
1707 bool Listen(int backlog) const;
1708 Socket* Accept() const;
1709
1710 // Client initialization.
1711 bool Connect(const char* host, const char* port);
1712
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001713 // Shutdown socket for both read and write.
1714 bool Shutdown();
1715
ager@chromium.org381abbb2009-02-25 13:23:22 +00001716 // Data Transimission
1717 int Send(const char* data, int len) const;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001718 int Receive(char* data, int len) const;
1719
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001720 bool SetReuseAddress(bool reuse_address);
1721
ager@chromium.org381abbb2009-02-25 13:23:22 +00001722 bool IsValid() const { return socket_ != INVALID_SOCKET; }
1723
1724 private:
1725 SOCKET socket_;
1726};
1727
1728
1729bool Win32Socket::Bind(const int port) {
1730 if (!IsValid()) {
1731 return false;
1732 }
1733
1734 sockaddr_in addr;
1735 memset(&addr, 0, sizeof(addr));
1736 addr.sin_family = AF_INET;
1737 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1738 addr.sin_port = htons(port);
1739 int status = bind(socket_,
1740 reinterpret_cast<struct sockaddr *>(&addr),
1741 sizeof(addr));
1742 return status == 0;
1743}
1744
1745
1746bool Win32Socket::Listen(int backlog) const {
1747 if (!IsValid()) {
1748 return false;
1749 }
1750
1751 int status = listen(socket_, backlog);
1752 return status == 0;
1753}
1754
1755
1756Socket* Win32Socket::Accept() const {
1757 if (!IsValid()) {
1758 return NULL;
1759 }
1760
1761 SOCKET socket = accept(socket_, NULL, NULL);
1762 if (socket == INVALID_SOCKET) {
1763 return NULL;
1764 } else {
1765 return new Win32Socket(socket);
1766 }
1767}
1768
1769
1770bool Win32Socket::Connect(const char* host, const char* port) {
1771 if (!IsValid()) {
1772 return false;
1773 }
1774
1775 // Lookup host and port.
1776 struct addrinfo *result = NULL;
1777 struct addrinfo hints;
1778 memset(&hints, 0, sizeof(addrinfo));
1779 hints.ai_family = AF_INET;
1780 hints.ai_socktype = SOCK_STREAM;
1781 hints.ai_protocol = IPPROTO_TCP;
1782 int status = getaddrinfo(host, port, &hints, &result);
1783 if (status != 0) {
1784 return false;
1785 }
1786
1787 // Connect.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001788 status = connect(socket_,
1789 result->ai_addr,
1790 static_cast<int>(result->ai_addrlen));
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001791 freeaddrinfo(result);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001792 return status == 0;
1793}
1794
1795
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001796bool Win32Socket::Shutdown() {
1797 if (IsValid()) {
1798 // Shutdown socket for both read and write.
1799 int status = shutdown(socket_, SD_BOTH);
1800 closesocket(socket_);
1801 socket_ = INVALID_SOCKET;
1802 return status == SOCKET_ERROR;
1803 }
1804 return true;
1805}
1806
1807
ager@chromium.org381abbb2009-02-25 13:23:22 +00001808int Win32Socket::Send(const char* data, int len) const {
1809 int status = send(socket_, data, len, 0);
1810 return status;
1811}
1812
1813
ager@chromium.org381abbb2009-02-25 13:23:22 +00001814int Win32Socket::Receive(char* data, int len) const {
1815 int status = recv(socket_, data, len, 0);
1816 return status;
1817}
1818
1819
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001820bool Win32Socket::SetReuseAddress(bool reuse_address) {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001821 BOOL on = reuse_address ? true : false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001822 int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
1823 reinterpret_cast<char*>(&on), sizeof(on));
1824 return status == SOCKET_ERROR;
1825}
1826
1827
ager@chromium.org381abbb2009-02-25 13:23:22 +00001828bool Socket::Setup() {
1829 // Initialize Winsock32
1830 int err;
1831 WSADATA winsock_data;
1832 WORD version_requested = MAKEWORD(1, 0);
1833 err = WSAStartup(version_requested, &winsock_data);
1834 if (err != 0) {
1835 PrintF("Unable to initialize Winsock, err = %d\n", Socket::LastError());
1836 }
1837
1838 return err == 0;
1839}
1840
1841
1842int Socket::LastError() {
1843 return WSAGetLastError();
1844}
1845
1846
1847uint16_t Socket::HToN(uint16_t value) {
1848 return htons(value);
1849}
1850
1851
1852uint16_t Socket::NToH(uint16_t value) {
1853 return ntohs(value);
1854}
1855
1856
1857uint32_t Socket::HToN(uint32_t value) {
1858 return htonl(value);
1859}
1860
1861
1862uint32_t Socket::NToH(uint32_t value) {
1863 return ntohl(value);
1864}
1865
1866
1867Socket* OS::CreateSocket() {
1868 return new Win32Socket();
1869}
1870
1871
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001872// ----------------------------------------------------------------------------
1873// Win32 profiler support.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001874
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001875class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001876 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001877 // Get a handle to the calling thread. This is the thread that we are
1878 // going to profile. We need to make a copy of the handle because we are
1879 // going to use it in the sampler thread. Using GetThreadHandle() will
1880 // not work in this case. We're using OpenThread because DuplicateHandle
1881 // for some reason doesn't work in Chrome's sandbox.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001882 PlatformData() : profiled_thread_(OpenThread(THREAD_GET_CONTEXT |
1883 THREAD_SUSPEND_RESUME |
1884 THREAD_QUERY_INFORMATION,
1885 false,
1886 GetCurrentThreadId())) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001887
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001888 ~PlatformData() {
1889 if (profiled_thread_ != NULL) {
1890 CloseHandle(profiled_thread_);
1891 profiled_thread_ = NULL;
1892 }
1893 }
1894
1895 HANDLE profiled_thread() { return profiled_thread_; }
1896
1897 private:
1898 HANDLE profiled_thread_;
1899};
1900
1901
1902class SamplerThread : public Thread {
1903 public:
1904 explicit SamplerThread(int interval)
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001905 : Thread("SamplerThread"),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001906 interval_(interval) {}
1907
1908 static void AddActiveSampler(Sampler* sampler) {
1909 ScopedLock lock(mutex_);
1910 SamplerRegistry::AddActiveSampler(sampler);
1911 if (instance_ == NULL) {
1912 instance_ = new SamplerThread(sampler->interval());
1913 instance_->Start();
1914 } else {
1915 ASSERT(instance_->interval_ == sampler->interval());
1916 }
1917 }
1918
1919 static void RemoveActiveSampler(Sampler* sampler) {
1920 ScopedLock lock(mutex_);
1921 SamplerRegistry::RemoveActiveSampler(sampler);
1922 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001923 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001924 delete instance_;
1925 instance_ = NULL;
1926 }
1927 }
1928
1929 // Implement Thread::Run().
1930 virtual void Run() {
1931 SamplerRegistry::State state;
1932 while ((state = SamplerRegistry::GetState()) !=
1933 SamplerRegistry::HAS_NO_SAMPLERS) {
1934 bool cpu_profiling_enabled =
1935 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1936 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
1937 // When CPU profiling is enabled both JavaScript and C++ code is
1938 // profiled. We must not suspend.
1939 if (!cpu_profiling_enabled) {
1940 if (rate_limiter_.SuspendIfNecessary()) continue;
1941 }
1942 if (cpu_profiling_enabled) {
1943 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1944 return;
1945 }
1946 }
1947 if (runtime_profiler_enabled) {
1948 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1949 return;
1950 }
1951 }
1952 OS::Sleep(interval_);
1953 }
1954 }
1955
1956 static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
1957 if (!sampler->isolate()->IsInitialized()) return;
1958 if (!sampler->IsProfiling()) return;
1959 SamplerThread* sampler_thread =
1960 reinterpret_cast<SamplerThread*>(raw_sampler_thread);
1961 sampler_thread->SampleContext(sampler);
1962 }
1963
1964 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1965 if (!sampler->isolate()->IsInitialized()) return;
1966 sampler->isolate()->runtime_profiler()->NotifyTick();
1967 }
1968
1969 void SampleContext(Sampler* sampler) {
1970 HANDLE profiled_thread = sampler->platform_data()->profiled_thread();
1971 if (profiled_thread == NULL) return;
1972
1973 // Context used for sampling the register state of the profiled thread.
1974 CONTEXT context;
1975 memset(&context, 0, sizeof(context));
1976
1977 TickSample sample_obj;
1978 TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
1979 if (sample == NULL) sample = &sample_obj;
1980
1981 static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
1982 if (SuspendThread(profiled_thread) == kSuspendFailed) return;
1983 sample->state = sampler->isolate()->current_vm_state();
1984
1985 context.ContextFlags = CONTEXT_FULL;
1986 if (GetThreadContext(profiled_thread, &context) != 0) {
1987#if V8_HOST_ARCH_X64
1988 sample->pc = reinterpret_cast<Address>(context.Rip);
1989 sample->sp = reinterpret_cast<Address>(context.Rsp);
1990 sample->fp = reinterpret_cast<Address>(context.Rbp);
1991#else
1992 sample->pc = reinterpret_cast<Address>(context.Eip);
1993 sample->sp = reinterpret_cast<Address>(context.Esp);
1994 sample->fp = reinterpret_cast<Address>(context.Ebp);
1995#endif
1996 sampler->SampleStack(sample);
1997 sampler->Tick(sample);
1998 }
1999 ResumeThread(profiled_thread);
2000 }
2001
2002 const int interval_;
2003 RuntimeProfilerRateLimiter rate_limiter_;
2004
2005 // Protects the process wide state below.
2006 static Mutex* mutex_;
2007 static SamplerThread* instance_;
2008
2009 DISALLOW_COPY_AND_ASSIGN(SamplerThread);
2010};
2011
2012
2013Mutex* SamplerThread::mutex_ = OS::CreateMutex();
2014SamplerThread* SamplerThread::instance_ = NULL;
2015
2016
2017Sampler::Sampler(Isolate* isolate, int interval)
2018 : isolate_(isolate),
2019 interval_(interval),
2020 profiling_(false),
2021 active_(false),
2022 samples_taken_(0) {
2023 data_ = new PlatformData;
2024}
2025
2026
2027Sampler::~Sampler() {
2028 ASSERT(!IsActive());
2029 delete data_;
2030}
2031
2032
2033void Sampler::Start() {
2034 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002035 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002036 SamplerThread::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002037}
2038
2039
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002040void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002041 ASSERT(IsActive());
2042 SamplerThread::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002043 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002044}
2045
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002046
2047} } // namespace v8::internal