blob: 8673f047ee2a7bac6786a8463322d03d0fab9cce [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
141int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
142 const char* format, va_list argptr) {
143 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
144}
145#define _TRUNCATE 0
146
147
148int strncpy_s(char* strDest, size_t numberOfElements,
149 const char* strSource, size_t count) {
150 strncpy(strDest, strSource, count);
151 return 0;
152}
153
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000154
155inline void MemoryBarrier() {
156 int barrier = 0;
157 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
158}
159
iposva@chromium.org245aa852009-02-10 00:49:54 +0000160#endif // __MINGW32__
161
162// Generate a pseudo-random number in the range 0-2^31-1. Usually
163// defined in stdlib.h. Missing in both Microsoft Visual Studio C++ and MinGW.
164int random() {
165 return rand();
166}
167
168
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000169namespace v8 {
170namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171
172double ceiling(double x) {
173 return ceil(x);
174}
175
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000176
177static Mutex* limit_mutex = NULL;
178
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000179#if defined(V8_TARGET_ARCH_IA32)
180static OS::MemCopyFunction memcopy_function = NULL;
181static Mutex* memcopy_function_mutex = OS::CreateMutex();
182// Defined in codegen-ia32.cc.
183OS::MemCopyFunction CreateMemCopyFunction();
184
185// Copy memory area to disjoint memory area.
186void OS::MemCopy(void* dest, const void* src, size_t size) {
187 if (memcopy_function == NULL) {
188 ScopedLock lock(memcopy_function_mutex);
189 if (memcopy_function == NULL) {
190 OS::MemCopyFunction temp = CreateMemCopyFunction();
191 MemoryBarrier();
192 memcopy_function = temp;
193 }
194 }
195 // Note: here we rely on dependent reads being ordered. This is true
196 // on all architectures we currently support.
197 (*memcopy_function)(dest, src, size);
198#ifdef DEBUG
199 CHECK_EQ(0, memcmp(dest, src, size));
200#endif
201}
202#endif // V8_TARGET_ARCH_IA32
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000203
ager@chromium.org3811b432009-10-28 14:53:37 +0000204#ifdef _WIN64
205typedef double (*ModuloFunction)(double, double);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000206static ModuloFunction modulo_function = NULL;
207static Mutex* modulo_function_mutex = OS::CreateMutex();
ager@chromium.org3811b432009-10-28 14:53:37 +0000208// Defined in codegen-x64.cc.
209ModuloFunction CreateModuloFunction();
210
211double modulo(double x, double y) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000212 if (modulo_function == NULL) {
213 ScopedLock lock(modulo_function_mutex);
214 if (modulo_function == NULL) {
215 ModuloFunction temp = CreateModuloFunction();
216 MemoryBarrier();
217 modulo_function = temp;
218 }
219 }
220 // Note: here we rely on dependent reads being ordered. This is true
221 // on all architectures we currently support.
222 return (*modulo_function)(x, y);
ager@chromium.org3811b432009-10-28 14:53:37 +0000223}
224#else // Win32
225
226double modulo(double x, double y) {
227 // Workaround MS fmod bugs. ECMA-262 says:
228 // dividend is finite and divisor is an infinity => result equals dividend
229 // dividend is a zero and divisor is nonzero finite => result equals dividend
230 if (!(isfinite(x) && (!isfinite(y) && !isnan(y))) &&
231 !(x == 0 && (y != 0 && isfinite(y)))) {
232 x = fmod(x, y);
233 }
234 return x;
235}
236
237#endif // _WIN64
238
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000239// ----------------------------------------------------------------------------
240// The Time class represents time on win32. A timestamp is represented as
241// a 64-bit integer in 100 nano-seconds since January 1, 1601 (UTC). JavaScript
242// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
243// January 1, 1970.
244
245class Time {
246 public:
247 // Constructors.
248 Time();
249 explicit Time(double jstime);
250 Time(int year, int mon, int day, int hour, int min, int sec);
251
252 // Convert timestamp to JavaScript representation.
253 double ToJSTime();
254
255 // Set timestamp to current time.
256 void SetToCurrentTime();
257
258 // Returns the local timezone offset in milliseconds east of UTC. This is
259 // the number of milliseconds you must add to UTC to get local time, i.e.
260 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
261 // routine also takes into account whether daylight saving is effect
262 // at the time.
263 int64_t LocalOffset();
264
265 // Returns the daylight savings time offset for the time in milliseconds.
266 int64_t DaylightSavingsOffset();
267
268 // Returns a string identifying the current timezone for the
269 // timestamp taking into account daylight saving.
270 char* LocalTimezone();
271
272 private:
273 // Constants for time conversion.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000274 static const int64_t kTimeEpoc = 116444736000000000LL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000275 static const int64_t kTimeScaler = 10000;
276 static const int64_t kMsPerMinute = 60000;
277
278 // Constants for timezone information.
279 static const int kTzNameSize = 128;
280 static const bool kShortTzNames = false;
281
282 // Timezone information. We need to have static buffers for the
283 // timezone names because we return pointers to these in
284 // LocalTimezone().
285 static bool tz_initialized_;
286 static TIME_ZONE_INFORMATION tzinfo_;
287 static char std_tz_name_[kTzNameSize];
288 static char dst_tz_name_[kTzNameSize];
289
290 // Initialize the timezone information (if not already done).
291 static void TzSet();
292
293 // Guess the name of the timezone from the bias.
294 static const char* GuessTimezoneNameFromBias(int bias);
295
296 // Return whether or not daylight savings time is in effect at this time.
297 bool InDST();
298
299 // Return the difference (in milliseconds) between this timestamp and
300 // another timestamp.
301 int64_t Diff(Time* other);
302
303 // Accessor for FILETIME representation.
304 FILETIME& ft() { return time_.ft_; }
305
306 // Accessor for integer representation.
307 int64_t& t() { return time_.t_; }
308
309 // Although win32 uses 64-bit integers for representing timestamps,
310 // these are packed into a FILETIME structure. The FILETIME structure
311 // is just a struct representing a 64-bit integer. The TimeStamp union
312 // allows access to both a FILETIME and an integer representation of
313 // the timestamp.
314 union TimeStamp {
315 FILETIME ft_;
316 int64_t t_;
317 };
318
319 TimeStamp time_;
320};
321
322// Static variables.
323bool Time::tz_initialized_ = false;
324TIME_ZONE_INFORMATION Time::tzinfo_;
325char Time::std_tz_name_[kTzNameSize];
326char Time::dst_tz_name_[kTzNameSize];
327
328
329// Initialize timestamp to start of epoc.
330Time::Time() {
331 t() = 0;
332}
333
334
335// Initialize timestamp from a JavaScript timestamp.
336Time::Time(double jstime) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000337 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338}
339
340
341// Initialize timestamp from date/time components.
342Time::Time(int year, int mon, int day, int hour, int min, int sec) {
343 SYSTEMTIME st;
344 st.wYear = year;
345 st.wMonth = mon;
346 st.wDay = day;
347 st.wHour = hour;
348 st.wMinute = min;
349 st.wSecond = sec;
350 st.wMilliseconds = 0;
351 SystemTimeToFileTime(&st, &ft());
352}
353
354
355// Convert timestamp to JavaScript timestamp.
356double Time::ToJSTime() {
357 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
358}
359
360
361// Guess the name of the timezone from the bias.
362// The guess is very biased towards the northern hemisphere.
363const char* Time::GuessTimezoneNameFromBias(int bias) {
364 static const int kHour = 60;
365 switch (-bias) {
366 case -9*kHour: return "Alaska";
367 case -8*kHour: return "Pacific";
368 case -7*kHour: return "Mountain";
369 case -6*kHour: return "Central";
370 case -5*kHour: return "Eastern";
371 case -4*kHour: return "Atlantic";
372 case 0*kHour: return "GMT";
373 case +1*kHour: return "Central Europe";
374 case +2*kHour: return "Eastern Europe";
375 case +3*kHour: return "Russia";
376 case +5*kHour + 30: return "India";
377 case +8*kHour: return "China";
378 case +9*kHour: return "Japan";
379 case +12*kHour: return "New Zealand";
380 default: return "Local";
381 }
382}
383
384
385// Initialize timezone information. The timezone information is obtained from
386// windows. If we cannot get the timezone information we fall back to CET.
387// Please notice that this code is not thread-safe.
388void Time::TzSet() {
389 // Just return if timezone information has already been initialized.
390 if (tz_initialized_) return;
391
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000392 // Initialize POSIX time zone data.
393 _tzset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000394 // Obtain timezone information from operating system.
395 memset(&tzinfo_, 0, sizeof(tzinfo_));
396 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
397 // If we cannot get timezone information we fall back to CET.
398 tzinfo_.Bias = -60;
399 tzinfo_.StandardDate.wMonth = 10;
400 tzinfo_.StandardDate.wDay = 5;
401 tzinfo_.StandardDate.wHour = 3;
402 tzinfo_.StandardBias = 0;
403 tzinfo_.DaylightDate.wMonth = 3;
404 tzinfo_.DaylightDate.wDay = 5;
405 tzinfo_.DaylightDate.wHour = 2;
406 tzinfo_.DaylightBias = -60;
407 }
408
409 // Make standard and DST timezone names.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000410 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize),
411 "%S",
412 tzinfo_.StandardName);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413 std_tz_name_[kTzNameSize - 1] = '\0';
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000414 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize),
415 "%S",
416 tzinfo_.DaylightName);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000417 dst_tz_name_[kTzNameSize - 1] = '\0';
418
419 // If OS returned empty string or resource id (like "@tzres.dll,-211")
420 // simply guess the name from the UTC bias of the timezone.
421 // To properly resolve the resource identifier requires a library load,
422 // which is not possible in a sandbox.
423 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000424 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
425 "%s Standard Time",
426 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427 }
428 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000429 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
430 "%s Daylight Time",
431 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000432 }
433
434 // Timezone information initialized.
435 tz_initialized_ = true;
436}
437
438
439// Return the difference in milliseconds between this and another timestamp.
440int64_t Time::Diff(Time* other) {
441 return (t() - other->t()) / kTimeScaler;
442}
443
444
445// Set timestamp to current time.
446void Time::SetToCurrentTime() {
447 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
448 // Because we're fast, we like fast timers which have at least a
449 // 1ms resolution.
450 //
451 // timeGetTime() provides 1ms granularity when combined with
452 // timeBeginPeriod(). If the host application for v8 wants fast
453 // timers, it can use timeBeginPeriod to increase the resolution.
454 //
455 // Using timeGetTime() has a drawback because it is a 32bit value
456 // and hence rolls-over every ~49days.
457 //
458 // To use the clock, we use GetSystemTimeAsFileTime as our base;
459 // and then use timeGetTime to extrapolate current time from the
460 // start time. To deal with rollovers, we resync the clock
461 // any time when more than kMaxClockElapsedTime has passed or
462 // whenever timeGetTime creates a rollover.
463
464 static bool initialized = false;
465 static TimeStamp init_time;
466 static DWORD init_ticks;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000467 static const int64_t kHundredNanosecondsPerSecond = 10000000;
468 static const int64_t kMaxClockElapsedTime =
469 60*kHundredNanosecondsPerSecond; // 1 minute
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470
471 // If we are uninitialized, we need to resync the clock.
472 bool needs_resync = !initialized;
473
474 // Get the current time.
475 TimeStamp time_now;
476 GetSystemTimeAsFileTime(&time_now.ft_);
477 DWORD ticks_now = timeGetTime();
478
479 // Check if we need to resync due to clock rollover.
480 needs_resync |= ticks_now < init_ticks;
481
482 // Check if we need to resync due to elapsed time.
483 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
484
485 // Resync the clock if necessary.
486 if (needs_resync) {
487 GetSystemTimeAsFileTime(&init_time.ft_);
488 init_ticks = ticks_now = timeGetTime();
489 initialized = true;
490 }
491
492 // Finally, compute the actual time. Why is this so hard.
493 DWORD elapsed = ticks_now - init_ticks;
494 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
495}
496
497
498// Return the local timezone offset in milliseconds east of UTC. This
499// takes into account whether daylight saving is in effect at the time.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000500// Only times in the 32-bit Unix range may be passed to this function.
501// Also, adding the time-zone offset to the input must not overflow.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000502// The function EquivalentTime() in date.js guarantees this.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000503int64_t Time::LocalOffset() {
504 // Initialize timezone information, if needed.
505 TzSet();
506
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000507 Time rounded_to_second(*this);
508 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
509 1000 * kTimeScaler;
510 // Convert to local time using POSIX localtime function.
511 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
512 // very slow. Other browsers use localtime().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000513
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000514 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
515 // POSIX seconds past 1/1/1970 0:00:00.
516 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
517 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
518 return 0;
519 }
520 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
521 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000522
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000523 // Convert to local time, as struct with fields for day, hour, year, etc.
524 tm posix_local_time_struct;
525 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
526 // Convert local time in struct to POSIX time as if it were a UTC time.
527 time_t local_posix_time = _mkgmtime(&posix_local_time_struct);
528 Time localtime(1000.0 * local_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000529
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000530 return localtime.Diff(&rounded_to_second);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000531}
532
533
534// Return whether or not daylight savings time is in effect at this time.
535bool Time::InDST() {
536 // Initialize timezone information, if needed.
537 TzSet();
538
539 // Determine if DST is in effect at the specified time.
540 bool in_dst = false;
541 if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) {
542 // Get the local timezone offset for the timestamp in milliseconds.
543 int64_t offset = LocalOffset();
544
545 // Compute the offset for DST. The bias parameters in the timezone info
546 // are specified in minutes. These must be converted to milliseconds.
547 int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute;
548
549 // If the local time offset equals the timezone bias plus the daylight
550 // bias then DST is in effect.
551 in_dst = offset == dstofs;
552 }
553
554 return in_dst;
555}
556
557
ager@chromium.org32912102009-01-16 10:38:43 +0000558// Return the daylight savings time offset for this time.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000559int64_t Time::DaylightSavingsOffset() {
560 return InDST() ? 60 * kMsPerMinute : 0;
561}
562
563
564// Returns a string identifying the current timezone for the
565// timestamp taking into account daylight saving.
566char* Time::LocalTimezone() {
567 // Return the standard or DST time zone name based on whether daylight
568 // saving is in effect at the given time.
569 return InDST() ? dst_tz_name_ : std_tz_name_;
570}
571
572
573void OS::Setup() {
574 // Seed the random number generator.
ager@chromium.orgef7cd1f2010-11-29 14:33:17 +0000575 // Convert the current time to a 64-bit integer first, before converting it
576 // to an unsigned. Going directly can cause an overflow and the seed to be
577 // set to all ones. The seed will be identical for different instances that
578 // call this setup code within the same millisecond.
579 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000580 srand(static_cast<unsigned int>(seed));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000581 limit_mutex = CreateMutex();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000582}
583
584
585// Returns the accumulated user time for thread.
586int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
587 FILETIME dummy;
588 uint64_t usertime;
589
590 // Get the amount of time that the thread has executed in user mode.
591 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
592 reinterpret_cast<FILETIME*>(&usertime))) return -1;
593
594 // Adjust the resolution to micro-seconds.
595 usertime /= 10;
596
597 // Convert to seconds and microseconds
598 *secs = static_cast<uint32_t>(usertime / 1000000);
599 *usecs = static_cast<uint32_t>(usertime % 1000000);
600 return 0;
601}
602
603
604// Returns current time as the number of milliseconds since
605// 00:00:00 UTC, January 1, 1970.
606double OS::TimeCurrentMillis() {
607 Time t;
608 t.SetToCurrentTime();
609 return t.ToJSTime();
610}
611
612// Returns the tickcounter based on timeGetTime.
613int64_t OS::Ticks() {
614 return timeGetTime() * 1000; // Convert to microseconds.
615}
616
617
618// Returns a string identifying the current timezone taking into
619// account daylight saving.
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000620const char* OS::LocalTimezone(double time) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000621 return Time(time).LocalTimezone();
622}
623
624
kasper.lund7276f142008-07-30 08:49:36 +0000625// Returns the local time offset in milliseconds east of UTC without
626// taking daylight savings time into account.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000627double OS::LocalTimeOffset() {
kasper.lund7276f142008-07-30 08:49:36 +0000628 // Use current time, rounded to the millisecond.
629 Time t(TimeCurrentMillis());
630 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
631 return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000632}
633
634
635// Returns the daylight savings offset in milliseconds for the given
636// time.
637double OS::DaylightSavingsOffset(double time) {
638 int64_t offset = Time(time).DaylightSavingsOffset();
639 return static_cast<double>(offset);
640}
641
642
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000643int OS::GetLastError() {
644 return ::GetLastError();
645}
646
647
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000648// ----------------------------------------------------------------------------
649// Win32 console output.
650//
651// If a Win32 application is linked as a console application it has a normal
652// standard output and standard error. In this case normal printf works fine
653// for output. However, if the application is linked as a GUI application,
654// the process doesn't have a console, and therefore (debugging) output is lost.
655// This is the case if we are embedded in a windows program (like a browser).
656// In order to be able to get debug output in this case the the debugging
657// facility using OutputDebugString. This output goes to the active debugger
658// for the process (if any). Else the output can be monitored using DBMON.EXE.
659
660enum OutputMode {
661 UNKNOWN, // Output method has not yet been determined.
662 CONSOLE, // Output is written to stdout.
663 ODS // Output is written to debug facility.
664};
665
666static OutputMode output_mode = UNKNOWN; // Current output mode.
667
668
669// Determine if the process has a console for output.
670static bool HasConsole() {
671 // Only check the first time. Eventual race conditions are not a problem,
672 // because all threads will eventually determine the same mode.
673 if (output_mode == UNKNOWN) {
674 // We cannot just check that the standard output is attached to a console
675 // because this would fail if output is redirected to a file. Therefore we
676 // say that a process does not have an output console if either the
677 // standard output handle is invalid or its file type is unknown.
678 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
679 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
680 output_mode = CONSOLE;
681 else
682 output_mode = ODS;
683 }
684 return output_mode == CONSOLE;
685}
686
687
688static void VPrintHelper(FILE* stream, const char* format, va_list args) {
689 if (HasConsole()) {
690 vfprintf(stream, format, args);
691 } else {
692 // It is important to use safe print here in order to avoid
693 // overflowing the buffer. We might truncate the output, but this
694 // does not crash.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000695 EmbeddedVector<char, 4096> buffer;
696 OS::VSNPrintF(buffer, format, args);
697 OutputDebugStringA(buffer.start());
698 }
699}
700
701
702FILE* OS::FOpen(const char* path, const char* mode) {
703 FILE* result;
704 if (fopen_s(&result, path, mode) == 0) {
705 return result;
706 } else {
707 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000708 }
709}
710
711
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000712bool OS::Remove(const char* path) {
713 return (DeleteFileA(path) != 0);
714}
715
716
ager@chromium.org71daaf62009-04-01 07:22:49 +0000717// Open log file in binary mode to avoid /n -> /r/n conversion.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000718const char* const OS::LogFileOpenMode = "wb";
ager@chromium.org71daaf62009-04-01 07:22:49 +0000719
720
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000721// Print (debug) message to console.
722void OS::Print(const char* format, ...) {
723 va_list args;
724 va_start(args, format);
725 VPrint(format, args);
726 va_end(args);
727}
728
729
730void OS::VPrint(const char* format, va_list args) {
731 VPrintHelper(stdout, format, args);
732}
733
734
whesse@chromium.org023421e2010-12-21 12:19:12 +0000735void OS::FPrint(FILE* out, const char* format, ...) {
736 va_list args;
737 va_start(args, format);
738 VFPrint(out, format, args);
739 va_end(args);
740}
741
742
743void OS::VFPrint(FILE* out, const char* format, va_list args) {
744 VPrintHelper(out, format, args);
745}
746
747
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000748// Print error message to console.
749void OS::PrintError(const char* format, ...) {
750 va_list args;
751 va_start(args, format);
752 VPrintError(format, args);
753 va_end(args);
754}
755
756
757void OS::VPrintError(const char* format, va_list args) {
758 VPrintHelper(stderr, format, args);
759}
760
761
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000762int OS::SNPrintF(Vector<char> str, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000763 va_list args;
764 va_start(args, format);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000765 int result = VSNPrintF(str, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 va_end(args);
767 return result;
768}
769
770
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000771int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
772 int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773 // Make sure to zero-terminate the string if the output was
774 // truncated or if there was an error.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000775 if (n < 0 || n >= str.length()) {
whesse@chromium.org023421e2010-12-21 12:19:12 +0000776 if (str.length() > 0)
777 str[str.length() - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000778 return -1;
779 } else {
780 return n;
781 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000782}
783
784
ager@chromium.org381abbb2009-02-25 13:23:22 +0000785char* OS::StrChr(char* str, int c) {
786 return const_cast<char*>(strchr(str, c));
787}
788
789
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000790void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000791 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
792 size_t buffer_size = static_cast<size_t>(dest.length());
793 if (n + 1 > buffer_size) // count for trailing '\0'
794 n = _TRUNCATE;
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000795 int result = strncpy_s(dest.start(), dest.length(), src, n);
796 USE(result);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000797 ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000798}
799
800
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801// We keep the lowest and highest addresses mapped as a quick way of
802// determining that pointers are outside the heap (used mostly in assertions
803// and verification). The estimate is conservative, ie, not all addresses in
804// 'allocated' space are actually allocated to our heap. The range is
805// [lowest, highest), inclusive on the low and and exclusive on the high end.
806static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
807static void* highest_ever_allocated = reinterpret_cast<void*>(0);
808
809
810static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000811 ASSERT(limit_mutex != NULL);
812 ScopedLock lock(limit_mutex);
813
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000814 lowest_ever_allocated = Min(lowest_ever_allocated, address);
815 highest_ever_allocated =
816 Max(highest_ever_allocated,
817 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
818}
819
820
821bool OS::IsOutsideAllocatedSpace(void* pointer) {
822 if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated)
823 return true;
824 // Ask the Windows API
825 if (IsBadWritePtr(pointer, 1))
826 return true;
827 return false;
828}
829
830
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000831// Get the system's page size used by VirtualAlloc() or the next power
832// of two. The reason for always returning a power of two is that the
833// rounding up in OS::Allocate expects that.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000834static size_t GetPageSize() {
835 static size_t page_size = 0;
836 if (page_size == 0) {
837 SYSTEM_INFO info;
838 GetSystemInfo(&info);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000839 page_size = RoundUpToPowerOf2(info.dwPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000840 }
841 return page_size;
842}
843
844
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000845// The allocation alignment is the guaranteed alignment for
846// VirtualAlloc'ed blocks of memory.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000847size_t OS::AllocateAlignment() {
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000848 static size_t allocate_alignment = 0;
849 if (allocate_alignment == 0) {
850 SYSTEM_INFO info;
851 GetSystemInfo(&info);
852 allocate_alignment = info.dwAllocationGranularity;
853 }
854 return allocate_alignment;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000855}
856
857
kasper.lund7276f142008-07-30 08:49:36 +0000858void* OS::Allocate(const size_t requested,
859 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000860 bool is_executable) {
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000861 // The address range used to randomize RWX allocations in OS::Allocate
862 // Try not to map pages into the default range that windows loads DLLs
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000863 // Use a multiple of 64k to prevent committing unused memory.
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000864 // Note: This does not guarantee RWX regions will be within the
865 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
866#ifdef V8_HOST_ARCH_64_BIT
867 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000868 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000869#else
870 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000871 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000872#endif
873
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000874 // VirtualAlloc rounds allocated size to page size automatically.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000875 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000876 intptr_t address = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000877
878 // Windows XP SP2 allows Data Excution Prevention (DEP).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000879 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000880
881 // For exectutable pages try and randomize the allocation address
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000882 if (prot == PAGE_EXECUTE_READWRITE &&
883 msize >= static_cast<size_t>(Page::kPageSize)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000884 address = (V8::RandomPrivate(Isolate::Current()) << kPageSizeBits)
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000885 | kAllocationRandomAddressMin;
886 address &= kAllocationRandomAddressMax;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000887 }
888
889 LPVOID mbase = VirtualAlloc(reinterpret_cast<void *>(address),
890 msize,
891 MEM_COMMIT | MEM_RESERVE,
892 prot);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000893 if (mbase == NULL && address != 0)
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000894 mbase = VirtualAlloc(NULL, msize, MEM_COMMIT | MEM_RESERVE, prot);
895
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000896 if (mbase == NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000897 LOG(ISOLATE, StringEvent("OS::Allocate", "VirtualAlloc failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898 return NULL;
899 }
900
901 ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
902
903 *allocated = msize;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000904 UpdateAllocatedSpaceLimits(mbase, static_cast<int>(msize));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000905 return mbase;
906}
907
908
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000909void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000910 // TODO(1240712): VirtualFree has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000911 VirtualFree(address, 0, MEM_RELEASE);
912 USE(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913}
914
915
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000916#ifdef ENABLE_HEAP_PROTECTION
917
918void OS::Protect(void* address, size_t size) {
919 // TODO(1240712): VirtualProtect has a return value which is ignored here.
920 DWORD old_protect;
921 VirtualProtect(address, size, PAGE_READONLY, &old_protect);
922}
923
924
925void OS::Unprotect(void* address, size_t size, bool is_executable) {
926 // TODO(1240712): VirtualProtect has a return value which is ignored here.
927 DWORD new_protect = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
928 DWORD old_protect;
929 VirtualProtect(address, size, new_protect, &old_protect);
930}
931
932#endif
933
934
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000935void OS::Sleep(int milliseconds) {
936 ::Sleep(milliseconds);
937}
938
939
940void OS::Abort() {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000941 if (!IsDebuggerPresent()) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000942#ifdef _MSC_VER
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000943 // Make the MSVCRT do a silent abort.
944 _set_abort_behavior(0, _WRITE_ABORT_MSG);
945 _set_abort_behavior(0, _CALL_REPORTFAULT);
iposva@chromium.org245aa852009-02-10 00:49:54 +0000946#endif // _MSC_VER
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000947 abort();
948 } else {
949 DebugBreak();
950 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000951}
952
953
kasper.lund7276f142008-07-30 08:49:36 +0000954void OS::DebugBreak() {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000955#ifdef _MSC_VER
kasper.lund7276f142008-07-30 08:49:36 +0000956 __debugbreak();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000957#else
958 ::DebugBreak();
959#endif
kasper.lund7276f142008-07-30 08:49:36 +0000960}
961
962
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000963class Win32MemoryMappedFile : public OS::MemoryMappedFile {
964 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000965 Win32MemoryMappedFile(HANDLE file,
966 HANDLE file_mapping,
967 void* memory,
968 int size)
969 : file_(file),
970 file_mapping_(file_mapping),
971 memory_(memory),
972 size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000973 virtual ~Win32MemoryMappedFile();
974 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000975 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000976 private:
977 HANDLE file_;
978 HANDLE file_mapping_;
979 void* memory_;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000980 int size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000981};
982
983
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000984OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
985 // Open a physical file
986 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
987 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000988 if (file == INVALID_HANDLE_VALUE) return NULL;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000989
990 int size = static_cast<int>(GetFileSize(file, NULL));
991
992 // Create a file mapping for the physical file
993 HANDLE file_mapping = CreateFileMapping(file, NULL,
994 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
995 if (file_mapping == NULL) return NULL;
996
997 // Map a view of the file into memory
998 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
999 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
1000}
1001
1002
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001003OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
1004 void* initial) {
1005 // Open a physical file
1006 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
1007 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
1008 if (file == NULL) return NULL;
1009 // Create a file mapping for the physical file
1010 HANDLE file_mapping = CreateFileMapping(file, NULL,
1011 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
1012 if (file_mapping == NULL) return NULL;
1013 // Map a view of the file into memory
1014 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
1015 if (memory) memmove(memory, initial, size);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001016 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001017}
1018
1019
1020Win32MemoryMappedFile::~Win32MemoryMappedFile() {
1021 if (memory_ != NULL)
1022 UnmapViewOfFile(memory_);
1023 CloseHandle(file_mapping_);
1024 CloseHandle(file_);
1025}
1026
1027
1028// The following code loads functions defined in DbhHelp.h and TlHelp32.h
ager@chromium.org32912102009-01-16 10:38:43 +00001029// dynamically. This is to avoid being depending on dbghelp.dll and
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001030// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
1031// kernel32.dll at some point so loading functions defines in TlHelp32.h
1032// dynamically might not be necessary any more - for some versions of Windows?).
1033
1034// Function pointers to functions dynamically loaded from dbghelp.dll.
1035#define DBGHELP_FUNCTION_LIST(V) \
1036 V(SymInitialize) \
1037 V(SymGetOptions) \
1038 V(SymSetOptions) \
1039 V(SymGetSearchPath) \
1040 V(SymLoadModule64) \
1041 V(StackWalk64) \
1042 V(SymGetSymFromAddr64) \
1043 V(SymGetLineFromAddr64) \
1044 V(SymFunctionTableAccess64) \
1045 V(SymGetModuleBase64)
1046
1047// Function pointers to functions dynamically loaded from dbghelp.dll.
1048#define TLHELP32_FUNCTION_LIST(V) \
1049 V(CreateToolhelp32Snapshot) \
1050 V(Module32FirstW) \
1051 V(Module32NextW)
1052
1053// Define the decoration to use for the type and variable name used for
1054// dynamically loaded DLL function..
1055#define DLL_FUNC_TYPE(name) _##name##_
1056#define DLL_FUNC_VAR(name) _##name
1057
1058// Define the type for each dynamically loaded DLL function. The function
1059// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1060// from the Windows include files are redefined here to have the function
1061// definitions to be as close to the ones in the original .h files as possible.
1062#ifndef IN
1063#define IN
1064#endif
1065#ifndef VOID
1066#define VOID void
1067#endif
1068
iposva@chromium.org245aa852009-02-10 00:49:54 +00001069// DbgHelp isn't supported on MinGW yet
1070#ifndef __MINGW32__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001071// DbgHelp.h functions.
1072typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
1073 IN PSTR UserSearchPath,
1074 IN BOOL fInvadeProcess);
1075typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
1076typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
1077typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
1078 IN HANDLE hProcess,
1079 OUT PSTR SearchPath,
1080 IN DWORD SearchPathLength);
1081typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
1082 IN HANDLE hProcess,
1083 IN HANDLE hFile,
1084 IN PSTR ImageName,
1085 IN PSTR ModuleName,
1086 IN DWORD64 BaseOfDll,
1087 IN DWORD SizeOfDll);
1088typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
1089 DWORD MachineType,
1090 HANDLE hProcess,
1091 HANDLE hThread,
1092 LPSTACKFRAME64 StackFrame,
1093 PVOID ContextRecord,
1094 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1095 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1096 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1097 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1098typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
1099 IN HANDLE hProcess,
1100 IN DWORD64 qwAddr,
1101 OUT PDWORD64 pdwDisplacement,
1102 OUT PIMAGEHLP_SYMBOL64 Symbol);
1103typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
1104 IN HANDLE hProcess,
1105 IN DWORD64 qwAddr,
1106 OUT PDWORD pdwDisplacement,
1107 OUT PIMAGEHLP_LINE64 Line64);
1108// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1109typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
1110 HANDLE hProcess,
1111 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1112typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1113 HANDLE hProcess,
1114 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1115
1116// TlHelp32.h functions.
1117typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1118 DWORD dwFlags,
1119 DWORD th32ProcessID);
1120typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1121 LPMODULEENTRY32W lpme);
1122typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1123 LPMODULEENTRY32W lpme);
1124
1125#undef IN
1126#undef VOID
1127
1128// Declare a variable for each dynamically loaded DLL function.
1129#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1130DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1131TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1132#undef DEF_DLL_FUNCTION
1133
1134// Load the functions. This function has a lot of "ugly" macros in order to
1135// keep down code duplication.
1136
1137static bool LoadDbgHelpAndTlHelp32() {
1138 static bool dbghelp_loaded = false;
1139
1140 if (dbghelp_loaded) return true;
1141
1142 HMODULE module;
1143
1144 // Load functions from the dbghelp.dll module.
1145 module = LoadLibrary(TEXT("dbghelp.dll"));
1146 if (module == NULL) {
1147 return false;
1148 }
1149
1150#define LOAD_DLL_FUNC(name) \
1151 DLL_FUNC_VAR(name) = \
1152 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1153
1154DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1155
1156#undef LOAD_DLL_FUNC
1157
1158 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1159 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1160 module = LoadLibrary(TEXT("kernel32.dll"));
1161 if (module == NULL) {
1162 return false;
1163 }
1164
1165#define LOAD_DLL_FUNC(name) \
1166 DLL_FUNC_VAR(name) = \
1167 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1168
1169TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1170
1171#undef LOAD_DLL_FUNC
1172
1173 // Check that all functions where loaded.
1174 bool result =
1175#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1176
1177DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1178TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1179
1180#undef DLL_FUNC_LOADED
1181 true;
1182
1183 dbghelp_loaded = result;
1184 return result;
ager@chromium.org32912102009-01-16 10:38:43 +00001185 // NOTE: The modules are never unloaded and will stay around until the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001186 // application is closed.
1187}
1188
1189
1190// Load the symbols for generating stack traces.
1191static bool LoadSymbols(HANDLE process_handle) {
1192 static bool symbols_loaded = false;
1193
1194 if (symbols_loaded) return true;
1195
1196 BOOL ok;
1197
1198 // Initialize the symbol engine.
1199 ok = _SymInitialize(process_handle, // hProcess
1200 NULL, // UserSearchPath
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001201 false); // fInvadeProcess
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001202 if (!ok) return false;
1203
1204 DWORD options = _SymGetOptions();
1205 options |= SYMOPT_LOAD_LINES;
1206 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1207 options = _SymSetOptions(options);
1208
1209 char buf[OS::kStackWalkMaxNameLen] = {0};
1210 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1211 if (!ok) {
1212 int err = GetLastError();
1213 PrintF("%d\n", err);
1214 return false;
1215 }
1216
1217 HANDLE snapshot = _CreateToolhelp32Snapshot(
1218 TH32CS_SNAPMODULE, // dwFlags
1219 GetCurrentProcessId()); // th32ProcessId
1220 if (snapshot == INVALID_HANDLE_VALUE) return false;
1221 MODULEENTRY32W module_entry;
1222 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1223 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1224 while (cont) {
1225 DWORD64 base;
1226 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1227 // both unicode and ASCII strings even though the parameter is PSTR.
1228 base = _SymLoadModule64(
1229 process_handle, // hProcess
1230 0, // hFile
1231 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1232 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1233 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1234 module_entry.modBaseSize); // SizeOfDll
1235 if (base == 0) {
1236 int err = GetLastError();
1237 if (err != ERROR_MOD_NOT_FOUND &&
1238 err != ERROR_INVALID_HANDLE) return false;
1239 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001240 LOG(i::Isolate::Current(),
1241 SharedLibraryEvent(
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001242 module_entry.szExePath,
1243 reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1244 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1245 module_entry.modBaseSize)));
1246 cont = _Module32NextW(snapshot, &module_entry);
1247 }
1248 CloseHandle(snapshot);
1249
1250 symbols_loaded = true;
1251 return true;
1252}
1253
1254
1255void OS::LogSharedLibraryAddresses() {
1256 // SharedLibraryEvents are logged when loading symbol information.
1257 // Only the shared libraries loaded at the time of the call to
1258 // LogSharedLibraryAddresses are logged. DLLs loaded after
1259 // initialization are not accounted for.
1260 if (!LoadDbgHelpAndTlHelp32()) return;
1261 HANDLE process_handle = GetCurrentProcess();
1262 LoadSymbols(process_handle);
1263}
1264
1265
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00001266void OS::SignalCodeMovingGC() {
1267}
1268
1269
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001270// Walk the stack using the facilities in dbghelp.dll and tlhelp32.dll
1271
1272// Switch off warning 4748 (/GS can not protect parameters and local variables
1273// from local buffer overrun because optimizations are disabled in function) as
1274// it is triggered by the use of inline assembler.
1275#pragma warning(push)
1276#pragma warning(disable : 4748)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001277int OS::StackWalk(Vector<OS::StackFrame> frames) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001278 BOOL ok;
1279
1280 // Load the required functions from DLL's.
1281 if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError;
1282
1283 // Get the process and thread handles.
1284 HANDLE process_handle = GetCurrentProcess();
1285 HANDLE thread_handle = GetCurrentThread();
1286
1287 // Read the symbols.
1288 if (!LoadSymbols(process_handle)) return kStackWalkError;
1289
1290 // Capture current context.
1291 CONTEXT context;
ager@chromium.org3811b432009-10-28 14:53:37 +00001292 RtlCaptureContext(&context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001293
1294 // Initialize the stack walking
1295 STACKFRAME64 stack_frame;
1296 memset(&stack_frame, 0, sizeof(stack_frame));
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001297#ifdef _WIN64
1298 stack_frame.AddrPC.Offset = context.Rip;
1299 stack_frame.AddrFrame.Offset = context.Rbp;
1300 stack_frame.AddrStack.Offset = context.Rsp;
1301#else
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001302 stack_frame.AddrPC.Offset = context.Eip;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001303 stack_frame.AddrFrame.Offset = context.Ebp;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001304 stack_frame.AddrStack.Offset = context.Esp;
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001305#endif
1306 stack_frame.AddrPC.Mode = AddrModeFlat;
1307 stack_frame.AddrFrame.Mode = AddrModeFlat;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001308 stack_frame.AddrStack.Mode = AddrModeFlat;
1309 int frames_count = 0;
1310
1311 // Collect stack frames.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001312 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001313 while (frames_count < frames_size) {
1314 ok = _StackWalk64(
1315 IMAGE_FILE_MACHINE_I386, // MachineType
1316 process_handle, // hProcess
1317 thread_handle, // hThread
1318 &stack_frame, // StackFrame
1319 &context, // ContextRecord
1320 NULL, // ReadMemoryRoutine
1321 _SymFunctionTableAccess64, // FunctionTableAccessRoutine
1322 _SymGetModuleBase64, // GetModuleBaseRoutine
1323 NULL); // TranslateAddress
1324 if (!ok) break;
1325
1326 // Store the address.
1327 ASSERT((stack_frame.AddrPC.Offset >> 32) == 0); // 32-bit address.
1328 frames[frames_count].address =
1329 reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
1330
1331 // Try to locate a symbol for this frame.
1332 DWORD64 symbol_displacement;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001333 SmartPointer<IMAGEHLP_SYMBOL64> symbol(
1334 NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen));
1335 if (symbol.is_empty()) return kStackWalkError; // Out of memory.
1336 memset(*symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
1337 (*symbol)->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
1338 (*symbol)->MaxNameLength = kStackWalkMaxNameLen;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001339 ok = _SymGetSymFromAddr64(process_handle, // hProcess
1340 stack_frame.AddrPC.Offset, // Address
1341 &symbol_displacement, // Displacement
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001342 *symbol); // Symbol
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001343 if (ok) {
1344 // Try to locate more source information for the symbol.
1345 IMAGEHLP_LINE64 Line;
1346 memset(&Line, 0, sizeof(Line));
1347 Line.SizeOfStruct = sizeof(Line);
1348 DWORD line_displacement;
1349 ok = _SymGetLineFromAddr64(
1350 process_handle, // hProcess
1351 stack_frame.AddrPC.Offset, // dwAddr
1352 &line_displacement, // pdwDisplacement
1353 &Line); // Line
1354 // Format a text representation of the frame based on the information
1355 // available.
1356 if (ok) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001357 SNPrintF(MutableCStrVector(frames[frames_count].text,
1358 kStackWalkMaxTextLen),
1359 "%s %s:%d:%d",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001360 (*symbol)->Name, Line.FileName, Line.LineNumber,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001361 line_displacement);
1362 } else {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001363 SNPrintF(MutableCStrVector(frames[frames_count].text,
1364 kStackWalkMaxTextLen),
1365 "%s",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001366 (*symbol)->Name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001367 }
1368 // Make sure line termination is in place.
1369 frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
1370 } else {
1371 // No text representation of this frame
1372 frames[frames_count].text[0] = '\0';
1373
1374 // Continue if we are just missing a module (for non C/C++ frames a
1375 // module will never be found).
1376 int err = GetLastError();
1377 if (err != ERROR_MOD_NOT_FOUND) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001378 break;
1379 }
1380 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001381
1382 frames_count++;
1383 }
1384
1385 // Return the number of frames filled in.
1386 return frames_count;
1387}
1388
1389// Restore warnings to previous settings.
1390#pragma warning(pop)
1391
iposva@chromium.org245aa852009-02-10 00:49:54 +00001392#else // __MINGW32__
1393void OS::LogSharedLibraryAddresses() { }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001394void OS::SignalCodeMovingGC() { }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001395int OS::StackWalk(Vector<OS::StackFrame> frames) { return 0; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001396#endif // __MINGW32__
1397
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001398
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001399uint64_t OS::CpuFeaturesImpliedByPlatform() {
1400 return 0; // Windows runs on anything.
1401}
1402
1403
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001404double OS::nan_value() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001405#ifdef _MSC_VER
ager@chromium.org3811b432009-10-28 14:53:37 +00001406 // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
1407 // in mask set, so value equals mask.
1408 static const __int64 nanval = kQuietNaNMask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409 return *reinterpret_cast<const double*>(&nanval);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001410#else // _MSC_VER
1411 return NAN;
1412#endif // _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001413}
1414
ager@chromium.org236ad962008-09-25 09:45:57 +00001415
1416int OS::ActivationFrameAlignment() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001417#ifdef _WIN64
1418 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1419#else
1420 return 8; // Floating-point math runs faster with 8-byte alignment.
1421#endif
ager@chromium.org236ad962008-09-25 09:45:57 +00001422}
1423
1424
kmillikin@chromium.org9155e252010-05-26 13:27:57 +00001425void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
1426 MemoryBarrier();
1427 *ptr = value;
1428}
1429
1430
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001431bool VirtualMemory::IsReserved() {
1432 return address_ != NULL;
1433}
1434
1435
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001436VirtualMemory::VirtualMemory(size_t size) {
1437 address_ = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001438 size_ = size;
1439}
1440
1441
1442VirtualMemory::~VirtualMemory() {
1443 if (IsReserved()) {
1444 if (0 == VirtualFree(address(), 0, MEM_RELEASE)) address_ = NULL;
1445 }
1446}
1447
1448
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00001449bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1450 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
kasper.lund7276f142008-07-30 08:49:36 +00001451 if (NULL == VirtualAlloc(address, size, MEM_COMMIT, prot)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001452 return false;
1453 }
1454
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001455 UpdateAllocatedSpaceLimits(address, static_cast<int>(size));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001456 return true;
1457}
1458
1459
1460bool VirtualMemory::Uncommit(void* address, size_t size) {
1461 ASSERT(IsReserved());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001462 return VirtualFree(address, size, MEM_DECOMMIT) != false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463}
1464
1465
1466// ----------------------------------------------------------------------------
1467// Win32 thread support.
1468
1469// Definition of invalid thread handle and id.
1470static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001471
1472// Entry point for threads. The supplied argument is a pointer to the thread
1473// object. The entry function dispatches to the run method in the thread
1474// object. It is important that this function has __stdcall calling
1475// convention.
1476static unsigned int __stdcall ThreadEntry(void* arg) {
1477 Thread* thread = reinterpret_cast<Thread*>(arg);
1478 // This is also initialized by the last parameter to _beginthreadex() but we
1479 // don't know which thread will run first (the original thread or the new
1480 // one) so we initialize it here too.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001481 Thread::SetThreadLocal(Isolate::isolate_key(), thread->isolate());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001482 thread->Run();
1483 return 0;
1484}
1485
1486
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001487class Thread::PlatformData : public Malloced {
1488 public:
1489 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1490 HANDLE thread_;
1491};
1492
1493
1494// Initialize a Win32 thread object. The thread has an invalid thread
1495// handle until it is started.
1496
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001497Thread::Thread(Isolate* isolate, const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001498 : isolate_(isolate),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001499 stack_size_(options.stack_size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001500 data_ = new PlatformData(kNoThread);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001501 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001502}
1503
1504
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001505Thread::Thread(Isolate* isolate, const char* name)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001506 : isolate_(isolate),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001507 stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001508 data_ = new PlatformData(kNoThread);
1509 set_name(name);
1510}
1511
1512
1513void Thread::set_name(const char* name) {
erik.corry@gmail.com0511e242011-01-19 11:11:08 +00001514 OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001515 name_[sizeof(name_) - 1] = '\0';
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001516}
1517
1518
1519// Close our own handle for the thread.
1520Thread::~Thread() {
1521 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1522 delete data_;
1523}
1524
1525
1526// Create a new thread. It is important to use _beginthreadex() instead of
1527// the Win32 function CreateThread(), because the CreateThread() does not
1528// initialize thread specific structures in the C runtime library.
1529void Thread::Start() {
1530 data_->thread_ = reinterpret_cast<HANDLE>(
1531 _beginthreadex(NULL,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001532 static_cast<unsigned>(stack_size_),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001533 ThreadEntry,
1534 this,
1535 0,
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001536 NULL));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001537}
1538
1539
1540// Wait for thread to terminate.
1541void Thread::Join() {
1542 WaitForSingleObject(data_->thread_, INFINITE);
1543}
1544
1545
1546Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1547 DWORD result = TlsAlloc();
1548 ASSERT(result != TLS_OUT_OF_INDEXES);
1549 return static_cast<LocalStorageKey>(result);
1550}
1551
1552
1553void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1554 BOOL result = TlsFree(static_cast<DWORD>(key));
1555 USE(result);
1556 ASSERT(result);
1557}
1558
1559
1560void* Thread::GetThreadLocal(LocalStorageKey key) {
1561 return TlsGetValue(static_cast<DWORD>(key));
1562}
1563
1564
1565void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1566 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1567 USE(result);
1568 ASSERT(result);
1569}
1570
1571
1572
1573void Thread::YieldCPU() {
1574 Sleep(0);
1575}
1576
1577
1578// ----------------------------------------------------------------------------
1579// Win32 mutex support.
1580//
1581// On Win32 mutexes are implemented using CRITICAL_SECTION objects. These are
1582// faster than Win32 Mutex objects because they are implemented using user mode
1583// atomic instructions. Therefore we only do ring transitions if there is lock
1584// contention.
1585
1586class Win32Mutex : public Mutex {
1587 public:
1588
1589 Win32Mutex() { InitializeCriticalSection(&cs_); }
1590
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001591 virtual ~Win32Mutex() { DeleteCriticalSection(&cs_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001592
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001593 virtual int Lock() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001594 EnterCriticalSection(&cs_);
1595 return 0;
1596 }
1597
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001598 virtual int Unlock() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001599 LeaveCriticalSection(&cs_);
1600 return 0;
1601 }
1602
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001603
1604 virtual bool TryLock() {
1605 // Returns non-zero if critical section is entered successfully entered.
1606 return TryEnterCriticalSection(&cs_);
1607 }
1608
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001609 private:
1610 CRITICAL_SECTION cs_; // Critical section used for mutex
1611};
1612
1613
1614Mutex* OS::CreateMutex() {
1615 return new Win32Mutex();
1616}
1617
1618
1619// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001620// Win32 semaphore support.
1621//
1622// On Win32 semaphores are implemented using Win32 Semaphore objects. The
1623// semaphores are anonymous. Also, the semaphores are initialized to have
1624// no upper limit on count.
1625
1626
1627class Win32Semaphore : public Semaphore {
1628 public:
1629 explicit Win32Semaphore(int count) {
1630 sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
1631 }
1632
1633 ~Win32Semaphore() {
1634 CloseHandle(sem);
1635 }
1636
1637 void Wait() {
1638 WaitForSingleObject(sem, INFINITE);
1639 }
1640
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001641 bool Wait(int timeout) {
1642 // Timeout in Windows API is in milliseconds.
1643 DWORD millis_timeout = timeout / 1000;
1644 return WaitForSingleObject(sem, millis_timeout) != WAIT_TIMEOUT;
1645 }
1646
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001647 void Signal() {
1648 LONG dummy;
1649 ReleaseSemaphore(sem, 1, &dummy);
1650 }
1651
1652 private:
1653 HANDLE sem;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001654};
1655
1656
1657Semaphore* OS::CreateSemaphore(int count) {
1658 return new Win32Semaphore(count);
1659}
1660
ager@chromium.org381abbb2009-02-25 13:23:22 +00001661
1662// ----------------------------------------------------------------------------
1663// Win32 socket support.
1664//
1665
1666class Win32Socket : public Socket {
1667 public:
1668 explicit Win32Socket() {
1669 // Create the socket.
1670 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1671 }
1672 explicit Win32Socket(SOCKET socket): socket_(socket) { }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001673 virtual ~Win32Socket() { Shutdown(); }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001674
1675 // Server initialization.
1676 bool Bind(const int port);
1677 bool Listen(int backlog) const;
1678 Socket* Accept() const;
1679
1680 // Client initialization.
1681 bool Connect(const char* host, const char* port);
1682
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001683 // Shutdown socket for both read and write.
1684 bool Shutdown();
1685
ager@chromium.org381abbb2009-02-25 13:23:22 +00001686 // Data Transimission
1687 int Send(const char* data, int len) const;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001688 int Receive(char* data, int len) const;
1689
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001690 bool SetReuseAddress(bool reuse_address);
1691
ager@chromium.org381abbb2009-02-25 13:23:22 +00001692 bool IsValid() const { return socket_ != INVALID_SOCKET; }
1693
1694 private:
1695 SOCKET socket_;
1696};
1697
1698
1699bool Win32Socket::Bind(const int port) {
1700 if (!IsValid()) {
1701 return false;
1702 }
1703
1704 sockaddr_in addr;
1705 memset(&addr, 0, sizeof(addr));
1706 addr.sin_family = AF_INET;
1707 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1708 addr.sin_port = htons(port);
1709 int status = bind(socket_,
1710 reinterpret_cast<struct sockaddr *>(&addr),
1711 sizeof(addr));
1712 return status == 0;
1713}
1714
1715
1716bool Win32Socket::Listen(int backlog) const {
1717 if (!IsValid()) {
1718 return false;
1719 }
1720
1721 int status = listen(socket_, backlog);
1722 return status == 0;
1723}
1724
1725
1726Socket* Win32Socket::Accept() const {
1727 if (!IsValid()) {
1728 return NULL;
1729 }
1730
1731 SOCKET socket = accept(socket_, NULL, NULL);
1732 if (socket == INVALID_SOCKET) {
1733 return NULL;
1734 } else {
1735 return new Win32Socket(socket);
1736 }
1737}
1738
1739
1740bool Win32Socket::Connect(const char* host, const char* port) {
1741 if (!IsValid()) {
1742 return false;
1743 }
1744
1745 // Lookup host and port.
1746 struct addrinfo *result = NULL;
1747 struct addrinfo hints;
1748 memset(&hints, 0, sizeof(addrinfo));
1749 hints.ai_family = AF_INET;
1750 hints.ai_socktype = SOCK_STREAM;
1751 hints.ai_protocol = IPPROTO_TCP;
1752 int status = getaddrinfo(host, port, &hints, &result);
1753 if (status != 0) {
1754 return false;
1755 }
1756
1757 // Connect.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001758 status = connect(socket_,
1759 result->ai_addr,
1760 static_cast<int>(result->ai_addrlen));
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001761 freeaddrinfo(result);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001762 return status == 0;
1763}
1764
1765
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001766bool Win32Socket::Shutdown() {
1767 if (IsValid()) {
1768 // Shutdown socket for both read and write.
1769 int status = shutdown(socket_, SD_BOTH);
1770 closesocket(socket_);
1771 socket_ = INVALID_SOCKET;
1772 return status == SOCKET_ERROR;
1773 }
1774 return true;
1775}
1776
1777
ager@chromium.org381abbb2009-02-25 13:23:22 +00001778int Win32Socket::Send(const char* data, int len) const {
1779 int status = send(socket_, data, len, 0);
1780 return status;
1781}
1782
1783
ager@chromium.org381abbb2009-02-25 13:23:22 +00001784int Win32Socket::Receive(char* data, int len) const {
1785 int status = recv(socket_, data, len, 0);
1786 return status;
1787}
1788
1789
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001790bool Win32Socket::SetReuseAddress(bool reuse_address) {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001791 BOOL on = reuse_address ? true : false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001792 int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
1793 reinterpret_cast<char*>(&on), sizeof(on));
1794 return status == SOCKET_ERROR;
1795}
1796
1797
ager@chromium.org381abbb2009-02-25 13:23:22 +00001798bool Socket::Setup() {
1799 // Initialize Winsock32
1800 int err;
1801 WSADATA winsock_data;
1802 WORD version_requested = MAKEWORD(1, 0);
1803 err = WSAStartup(version_requested, &winsock_data);
1804 if (err != 0) {
1805 PrintF("Unable to initialize Winsock, err = %d\n", Socket::LastError());
1806 }
1807
1808 return err == 0;
1809}
1810
1811
1812int Socket::LastError() {
1813 return WSAGetLastError();
1814}
1815
1816
1817uint16_t Socket::HToN(uint16_t value) {
1818 return htons(value);
1819}
1820
1821
1822uint16_t Socket::NToH(uint16_t value) {
1823 return ntohs(value);
1824}
1825
1826
1827uint32_t Socket::HToN(uint32_t value) {
1828 return htonl(value);
1829}
1830
1831
1832uint32_t Socket::NToH(uint32_t value) {
1833 return ntohl(value);
1834}
1835
1836
1837Socket* OS::CreateSocket() {
1838 return new Win32Socket();
1839}
1840
1841
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001842#ifdef ENABLE_LOGGING_AND_PROFILING
1843
1844// ----------------------------------------------------------------------------
1845// Win32 profiler support.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001846
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001847class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001848 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001849 // Get a handle to the calling thread. This is the thread that we are
1850 // going to profile. We need to make a copy of the handle because we are
1851 // going to use it in the sampler thread. Using GetThreadHandle() will
1852 // not work in this case. We're using OpenThread because DuplicateHandle
1853 // for some reason doesn't work in Chrome's sandbox.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001854 PlatformData() : profiled_thread_(OpenThread(THREAD_GET_CONTEXT |
1855 THREAD_SUSPEND_RESUME |
1856 THREAD_QUERY_INFORMATION,
1857 false,
1858 GetCurrentThreadId())) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001860 ~PlatformData() {
1861 if (profiled_thread_ != NULL) {
1862 CloseHandle(profiled_thread_);
1863 profiled_thread_ = NULL;
1864 }
1865 }
1866
1867 HANDLE profiled_thread() { return profiled_thread_; }
1868
1869 private:
1870 HANDLE profiled_thread_;
1871};
1872
1873
1874class SamplerThread : public Thread {
1875 public:
1876 explicit SamplerThread(int interval)
1877 : Thread(NULL, "SamplerThread"),
1878 interval_(interval) {}
1879
1880 static void AddActiveSampler(Sampler* sampler) {
1881 ScopedLock lock(mutex_);
1882 SamplerRegistry::AddActiveSampler(sampler);
1883 if (instance_ == NULL) {
1884 instance_ = new SamplerThread(sampler->interval());
1885 instance_->Start();
1886 } else {
1887 ASSERT(instance_->interval_ == sampler->interval());
1888 }
1889 }
1890
1891 static void RemoveActiveSampler(Sampler* sampler) {
1892 ScopedLock lock(mutex_);
1893 SamplerRegistry::RemoveActiveSampler(sampler);
1894 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
1895 RuntimeProfiler::WakeUpRuntimeProfilerThreadBeforeShutdown();
1896 instance_->Join();
1897 delete instance_;
1898 instance_ = NULL;
1899 }
1900 }
1901
1902 // Implement Thread::Run().
1903 virtual void Run() {
1904 SamplerRegistry::State state;
1905 while ((state = SamplerRegistry::GetState()) !=
1906 SamplerRegistry::HAS_NO_SAMPLERS) {
1907 bool cpu_profiling_enabled =
1908 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1909 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
1910 // When CPU profiling is enabled both JavaScript and C++ code is
1911 // profiled. We must not suspend.
1912 if (!cpu_profiling_enabled) {
1913 if (rate_limiter_.SuspendIfNecessary()) continue;
1914 }
1915 if (cpu_profiling_enabled) {
1916 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1917 return;
1918 }
1919 }
1920 if (runtime_profiler_enabled) {
1921 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1922 return;
1923 }
1924 }
1925 OS::Sleep(interval_);
1926 }
1927 }
1928
1929 static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
1930 if (!sampler->isolate()->IsInitialized()) return;
1931 if (!sampler->IsProfiling()) return;
1932 SamplerThread* sampler_thread =
1933 reinterpret_cast<SamplerThread*>(raw_sampler_thread);
1934 sampler_thread->SampleContext(sampler);
1935 }
1936
1937 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1938 if (!sampler->isolate()->IsInitialized()) return;
1939 sampler->isolate()->runtime_profiler()->NotifyTick();
1940 }
1941
1942 void SampleContext(Sampler* sampler) {
1943 HANDLE profiled_thread = sampler->platform_data()->profiled_thread();
1944 if (profiled_thread == NULL) return;
1945
1946 // Context used for sampling the register state of the profiled thread.
1947 CONTEXT context;
1948 memset(&context, 0, sizeof(context));
1949
1950 TickSample sample_obj;
1951 TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
1952 if (sample == NULL) sample = &sample_obj;
1953
1954 static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
1955 if (SuspendThread(profiled_thread) == kSuspendFailed) return;
1956 sample->state = sampler->isolate()->current_vm_state();
1957
1958 context.ContextFlags = CONTEXT_FULL;
1959 if (GetThreadContext(profiled_thread, &context) != 0) {
1960#if V8_HOST_ARCH_X64
1961 sample->pc = reinterpret_cast<Address>(context.Rip);
1962 sample->sp = reinterpret_cast<Address>(context.Rsp);
1963 sample->fp = reinterpret_cast<Address>(context.Rbp);
1964#else
1965 sample->pc = reinterpret_cast<Address>(context.Eip);
1966 sample->sp = reinterpret_cast<Address>(context.Esp);
1967 sample->fp = reinterpret_cast<Address>(context.Ebp);
1968#endif
1969 sampler->SampleStack(sample);
1970 sampler->Tick(sample);
1971 }
1972 ResumeThread(profiled_thread);
1973 }
1974
1975 const int interval_;
1976 RuntimeProfilerRateLimiter rate_limiter_;
1977
1978 // Protects the process wide state below.
1979 static Mutex* mutex_;
1980 static SamplerThread* instance_;
1981
1982 DISALLOW_COPY_AND_ASSIGN(SamplerThread);
1983};
1984
1985
1986Mutex* SamplerThread::mutex_ = OS::CreateMutex();
1987SamplerThread* SamplerThread::instance_ = NULL;
1988
1989
1990Sampler::Sampler(Isolate* isolate, int interval)
1991 : isolate_(isolate),
1992 interval_(interval),
1993 profiling_(false),
1994 active_(false),
1995 samples_taken_(0) {
1996 data_ = new PlatformData;
1997}
1998
1999
2000Sampler::~Sampler() {
2001 ASSERT(!IsActive());
2002 delete data_;
2003}
2004
2005
2006void Sampler::Start() {
2007 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002008 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002009 SamplerThread::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002010}
2011
2012
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002013void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002014 ASSERT(IsActive());
2015 SamplerThread::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002016 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002017}
2018
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002019#endif // ENABLE_LOGGING_AND_PROFILING
2020
2021} } // namespace v8::internal