blob: 10f89de68080e793bf944cffbed72ca405ad0231 [file] [log] [blame]
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +00001// Copyright 2012 the V8 project authors. All rights reserved.
rossberg@chromium.org34849642014-04-29 16:30:47 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004
machenbach@chromium.orge014e5b2014-01-28 07:51:38 +00005// Platform-specific code for Win32.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00006
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00007// Secure API functions are not available using MinGW with msvcrt.dll
8// on Windows XP. Make sure MINGW_HAS_SECURE_API is not defined to
9// disable definition of secure API functions in standard headers that
10// would conflict with our own implementation.
11#ifdef __MINGW32__
12#include <_mingw.h>
13#ifdef MINGW_HAS_SECURE_API
14#undef MINGW_HAS_SECURE_API
15#endif // MINGW_HAS_SECURE_API
16#endif // __MINGW32__
17
yangguo@chromium.org5de00742014-07-01 11:58:10 +000018#ifdef _MSC_VER
19#include <limits>
20#endif
21
machenbach@chromium.org1e2d50c2014-06-06 00:04:56 +000022#include "src/base/win32-headers.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000023
machenbach@chromium.org21d700e2014-09-03 08:32:14 +000024#include "src/base/bits.h"
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +000025#include "src/base/lazy-instance.h"
yangguo@chromium.org5de00742014-07-01 11:58:10 +000026#include "src/base/macros.h"
27#include "src/base/platform/platform.h"
28#include "src/base/platform/time.h"
29#include "src/base/utils/random-number-generator.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000030
iposva@chromium.org245aa852009-02-10 00:49:54 +000031#ifdef _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000033// Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
34// defined in strings.h.
35int strncasecmp(const char* s1, const char* s2, int n) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000036 return _strnicmp(s1, s2, n);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037}
38
iposva@chromium.org245aa852009-02-10 00:49:54 +000039#endif // _MSC_VER
40
41
42// Extra functions for MinGW. Most of these are the _s functions which are in
43// the Microsoft Visual Studio C++ CRT.
44#ifdef __MINGW32__
45
svenpanne@chromium.orgfb046332012-04-19 12:02:44 +000046
47#ifndef __MINGW64_VERSION_MAJOR
48
49#define _TRUNCATE 0
50#define STRUNCATE 80
51
52inline void MemoryBarrier() {
53 int barrier = 0;
54 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
55}
56
57#endif // __MINGW64_VERSION_MAJOR
58
59
iposva@chromium.org245aa852009-02-10 00:49:54 +000060int localtime_s(tm* out_tm, const time_t* time) {
61 tm* posix_local_time_struct = localtime(time);
62 if (posix_local_time_struct == NULL) return 1;
63 *out_tm = *posix_local_time_struct;
64 return 0;
65}
66
67
iposva@chromium.org245aa852009-02-10 00:49:54 +000068int fopen_s(FILE** pFile, const char* filename, const char* mode) {
69 *pFile = fopen(filename, mode);
70 return *pFile != NULL ? 0 : 1;
71}
72
iposva@chromium.org245aa852009-02-10 00:49:54 +000073int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
74 const char* format, va_list argptr) {
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +000075 DCHECK(count == _TRUNCATE);
iposva@chromium.org245aa852009-02-10 00:49:54 +000076 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
77}
iposva@chromium.org245aa852009-02-10 00:49:54 +000078
79
sgjesse@chromium.org6db88712011-07-11 11:41:22 +000080int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
81 CHECK(source != NULL);
82 CHECK(dest != NULL);
83 CHECK_GT(dest_size, 0);
84
85 if (count == _TRUNCATE) {
86 while (dest_size > 0 && *source != 0) {
87 *(dest++) = *(source++);
88 --dest_size;
89 }
90 if (dest_size == 0) {
91 *(dest - 1) = 0;
92 return STRUNCATE;
93 }
94 } else {
95 while (dest_size > 0 && count > 0 && *source != 0) {
96 *(dest++) = *(source++);
97 --dest_size;
98 --count;
99 }
100 }
101 CHECK_GT(dest_size, 0);
102 *dest = 0;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000103 return 0;
104}
105
106#endif // __MINGW32__
107
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000108namespace v8 {
yangguo@chromium.org5de00742014-07-01 11:58:10 +0000109namespace base {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000110
machenbach@chromium.org248dd432014-06-30 00:04:54 +0000111namespace {
112
113bool g_hard_abort = false;
114
115} // namespace
116
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000117class TimezoneCache {
118 public:
119 TimezoneCache() : initialized_(false) { }
120
121 void Clear() {
122 initialized_ = false;
123 }
124
125 // Initialize timezone information. The timezone information is obtained from
126 // windows. If we cannot get the timezone information we fall back to CET.
127 void InitializeIfNeeded() {
128 // Just return if timezone information has already been initialized.
129 if (initialized_) return;
130
131 // Initialize POSIX time zone data.
132 _tzset();
133 // Obtain timezone information from operating system.
134 memset(&tzinfo_, 0, sizeof(tzinfo_));
135 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
136 // If we cannot get timezone information we fall back to CET.
137 tzinfo_.Bias = -60;
138 tzinfo_.StandardDate.wMonth = 10;
139 tzinfo_.StandardDate.wDay = 5;
140 tzinfo_.StandardDate.wHour = 3;
141 tzinfo_.StandardBias = 0;
142 tzinfo_.DaylightDate.wMonth = 3;
143 tzinfo_.DaylightDate.wDay = 5;
144 tzinfo_.DaylightDate.wHour = 2;
145 tzinfo_.DaylightBias = -60;
146 }
147
148 // Make standard and DST timezone names.
149 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
150 std_tz_name_, kTzNameSize, NULL, NULL);
151 std_tz_name_[kTzNameSize - 1] = '\0';
152 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
153 dst_tz_name_, kTzNameSize, NULL, NULL);
154 dst_tz_name_[kTzNameSize - 1] = '\0';
155
156 // If OS returned empty string or resource id (like "@tzres.dll,-211")
157 // simply guess the name from the UTC bias of the timezone.
158 // To properly resolve the resource identifier requires a library load,
159 // which is not possible in a sandbox.
160 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000161 OS::SNPrintF(std_tz_name_, kTzNameSize - 1,
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000162 "%s Standard Time",
163 GuessTimezoneNameFromBias(tzinfo_.Bias));
164 }
165 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000166 OS::SNPrintF(dst_tz_name_, kTzNameSize - 1,
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000167 "%s Daylight Time",
168 GuessTimezoneNameFromBias(tzinfo_.Bias));
169 }
170 // Timezone information initialized.
171 initialized_ = true;
172 }
173
174 // Guess the name of the timezone from the bias.
175 // The guess is very biased towards the northern hemisphere.
176 const char* GuessTimezoneNameFromBias(int bias) {
177 static const int kHour = 60;
178 switch (-bias) {
179 case -9*kHour: return "Alaska";
180 case -8*kHour: return "Pacific";
181 case -7*kHour: return "Mountain";
182 case -6*kHour: return "Central";
183 case -5*kHour: return "Eastern";
184 case -4*kHour: return "Atlantic";
185 case 0*kHour: return "GMT";
186 case +1*kHour: return "Central Europe";
187 case +2*kHour: return "Eastern Europe";
188 case +3*kHour: return "Russia";
189 case +5*kHour + 30: return "India";
190 case +8*kHour: return "China";
191 case +9*kHour: return "Japan";
192 case +12*kHour: return "New Zealand";
193 default: return "Local";
194 }
195 }
196
197
198 private:
199 static const int kTzNameSize = 128;
200 bool initialized_;
201 char std_tz_name_[kTzNameSize];
202 char dst_tz_name_[kTzNameSize];
203 TIME_ZONE_INFORMATION tzinfo_;
204 friend class Win32Time;
205};
206
207
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000208// ----------------------------------------------------------------------------
209// The Time class represents time on win32. A timestamp is represented as
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000210// a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000211// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
212// January 1, 1970.
213
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000214class Win32Time {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000215 public:
216 // Constructors.
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000217 Win32Time();
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000218 explicit Win32Time(double jstime);
219 Win32Time(int year, int mon, int day, int hour, int min, int sec);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000220
221 // Convert timestamp to JavaScript representation.
222 double ToJSTime();
223
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000224 // Set timestamp to current time.
225 void SetToCurrentTime();
226
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000227 // Returns the local timezone offset in milliseconds east of UTC. This is
228 // the number of milliseconds you must add to UTC to get local time, i.e.
229 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
230 // routine also takes into account whether daylight saving is effect
231 // at the time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000232 int64_t LocalOffset(TimezoneCache* cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233
234 // Returns the daylight savings time offset for the time in milliseconds.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000235 int64_t DaylightSavingsOffset(TimezoneCache* cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236
237 // Returns a string identifying the current timezone for the
238 // timestamp taking into account daylight saving.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000239 char* LocalTimezone(TimezoneCache* cache);
dslomov@chromium.org486536d2014-03-12 13:09:18 +0000240
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000241 private:
242 // Constants for time conversion.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000243 static const int64_t kTimeEpoc = 116444736000000000LL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000244 static const int64_t kTimeScaler = 10000;
245 static const int64_t kMsPerMinute = 60000;
246
247 // Constants for timezone information.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000248 static const bool kShortTzNames = false;
249
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000250 // Return whether or not daylight savings time is in effect at this time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000251 bool InDST(TimezoneCache* cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000253 // Accessor for FILETIME representation.
254 FILETIME& ft() { return time_.ft_; }
255
256 // Accessor for integer representation.
257 int64_t& t() { return time_.t_; }
258
259 // Although win32 uses 64-bit integers for representing timestamps,
260 // these are packed into a FILETIME structure. The FILETIME structure
261 // is just a struct representing a 64-bit integer. The TimeStamp union
262 // allows access to both a FILETIME and an integer representation of
263 // the timestamp.
264 union TimeStamp {
265 FILETIME ft_;
266 int64_t t_;
267 };
268
269 TimeStamp time_;
270};
271
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +0000272
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000273// Initialize timestamp to start of epoc.
274Win32Time::Win32Time() {
275 t() = 0;
276}
277
278
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000279// Initialize timestamp from a JavaScript timestamp.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000280Win32Time::Win32Time(double jstime) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000281 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000282}
283
284
285// Initialize timestamp from date/time components.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000286Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000287 SYSTEMTIME st;
288 st.wYear = year;
289 st.wMonth = mon;
290 st.wDay = day;
291 st.wHour = hour;
292 st.wMinute = min;
293 st.wSecond = sec;
294 st.wMilliseconds = 0;
295 SystemTimeToFileTime(&st, &ft());
296}
297
298
299// Convert timestamp to JavaScript timestamp.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000300double Win32Time::ToJSTime() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000301 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
302}
303
304
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000305// Set timestamp to current time.
306void Win32Time::SetToCurrentTime() {
307 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
308 // Because we're fast, we like fast timers which have at least a
309 // 1ms resolution.
310 //
311 // timeGetTime() provides 1ms granularity when combined with
312 // timeBeginPeriod(). If the host application for v8 wants fast
313 // timers, it can use timeBeginPeriod to increase the resolution.
314 //
315 // Using timeGetTime() has a drawback because it is a 32bit value
316 // and hence rolls-over every ~49days.
317 //
318 // To use the clock, we use GetSystemTimeAsFileTime as our base;
319 // and then use timeGetTime to extrapolate current time from the
320 // start time. To deal with rollovers, we resync the clock
321 // any time when more than kMaxClockElapsedTime has passed or
322 // whenever timeGetTime creates a rollover.
323
324 static bool initialized = false;
325 static TimeStamp init_time;
326 static DWORD init_ticks;
327 static const int64_t kHundredNanosecondsPerSecond = 10000000;
328 static const int64_t kMaxClockElapsedTime =
329 60*kHundredNanosecondsPerSecond; // 1 minute
330
331 // If we are uninitialized, we need to resync the clock.
332 bool needs_resync = !initialized;
333
334 // Get the current time.
335 TimeStamp time_now;
336 GetSystemTimeAsFileTime(&time_now.ft_);
337 DWORD ticks_now = timeGetTime();
338
339 // Check if we need to resync due to clock rollover.
340 needs_resync |= ticks_now < init_ticks;
341
342 // Check if we need to resync due to elapsed time.
343 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
344
345 // Check if we need to resync due to backwards time change.
346 needs_resync |= time_now.t_ < init_time.t_;
347
348 // Resync the clock if necessary.
349 if (needs_resync) {
350 GetSystemTimeAsFileTime(&init_time.ft_);
351 init_ticks = ticks_now = timeGetTime();
352 initialized = true;
353 }
354
355 // Finally, compute the actual time. Why is this so hard.
356 DWORD elapsed = ticks_now - init_ticks;
357 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
358}
359
360
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361// Return the local timezone offset in milliseconds east of UTC. This
362// takes into account whether daylight saving is in effect at the time.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000363// Only times in the 32-bit Unix range may be passed to this function.
364// Also, adding the time-zone offset to the input must not overflow.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000365// The function EquivalentTime() in date.js guarantees this.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000366int64_t Win32Time::LocalOffset(TimezoneCache* cache) {
367 cache->InitializeIfNeeded();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000369 Win32Time rounded_to_second(*this);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000370 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
371 1000 * kTimeScaler;
372 // Convert to local time using POSIX localtime function.
373 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
374 // very slow. Other browsers use localtime().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000375
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000376 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
377 // POSIX seconds past 1/1/1970 0:00:00.
378 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
379 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
380 return 0;
381 }
382 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
383 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000385 // Convert to local time, as struct with fields for day, hour, year, etc.
386 tm posix_local_time_struct;
387 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000388
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000389 if (posix_local_time_struct.tm_isdst > 0) {
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000390 return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000391 } else if (posix_local_time_struct.tm_isdst == 0) {
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000392 return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000393 } else {
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000394 return cache->tzinfo_.Bias * -kMsPerMinute;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000395 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000396}
397
398
399// Return whether or not daylight savings time is in effect at this time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000400bool Win32Time::InDST(TimezoneCache* cache) {
401 cache->InitializeIfNeeded();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000402
403 // Determine if DST is in effect at the specified time.
404 bool in_dst = false;
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000405 if (cache->tzinfo_.StandardDate.wMonth != 0 ||
406 cache->tzinfo_.DaylightDate.wMonth != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000407 // Get the local timezone offset for the timestamp in milliseconds.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000408 int64_t offset = LocalOffset(cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000409
410 // Compute the offset for DST. The bias parameters in the timezone info
411 // are specified in minutes. These must be converted to milliseconds.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000412 int64_t dstofs =
413 -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000414
415 // If the local time offset equals the timezone bias plus the daylight
416 // bias then DST is in effect.
417 in_dst = offset == dstofs;
418 }
419
420 return in_dst;
421}
422
423
ager@chromium.org32912102009-01-16 10:38:43 +0000424// Return the daylight savings time offset for this time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000425int64_t Win32Time::DaylightSavingsOffset(TimezoneCache* cache) {
426 return InDST(cache) ? 60 * kMsPerMinute : 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427}
428
429
430// Returns a string identifying the current timezone for the
431// timestamp taking into account daylight saving.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000432char* Win32Time::LocalTimezone(TimezoneCache* cache) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000433 // Return the standard or DST time zone name based on whether daylight
434 // saving is in effect at the given time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000435 return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000436}
437
438
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000439// Returns the accumulated user time for thread.
440int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
441 FILETIME dummy;
442 uint64_t usertime;
443
444 // Get the amount of time that the thread has executed in user mode.
445 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
446 reinterpret_cast<FILETIME*>(&usertime))) return -1;
447
448 // Adjust the resolution to micro-seconds.
449 usertime /= 10;
450
451 // Convert to seconds and microseconds
452 *secs = static_cast<uint32_t>(usertime / 1000000);
453 *usecs = static_cast<uint32_t>(usertime % 1000000);
454 return 0;
455}
456
457
458// Returns current time as the number of milliseconds since
459// 00:00:00 UTC, January 1, 1970.
460double OS::TimeCurrentMillis() {
jkummerow@chromium.orgd8a3a142013-10-03 12:15:05 +0000461 return Time::Now().ToJsTime();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000462}
463
464
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000465TimezoneCache* OS::CreateTimezoneCache() {
466 return new TimezoneCache();
467}
468
469
470void OS::DisposeTimezoneCache(TimezoneCache* cache) {
471 delete cache;
472}
473
474
475void OS::ClearTimezoneCache(TimezoneCache* cache) {
476 cache->Clear();
477}
478
479
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480// Returns a string identifying the current timezone taking into
481// account daylight saving.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000482const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
483 return Win32Time(time).LocalTimezone(cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000484}
485
486
kasper.lund7276f142008-07-30 08:49:36 +0000487// Returns the local time offset in milliseconds east of UTC without
488// taking daylight savings time into account.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000489double OS::LocalTimeOffset(TimezoneCache* cache) {
kasper.lund7276f142008-07-30 08:49:36 +0000490 // Use current time, rounded to the millisecond.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000491 Win32Time t(TimeCurrentMillis());
kasper.lund7276f142008-07-30 08:49:36 +0000492 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000493 return static_cast<double>(t.LocalOffset(cache) -
494 t.DaylightSavingsOffset(cache));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000495}
496
497
498// Returns the daylight savings offset in milliseconds for the given
499// time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000500double OS::DaylightSavingsOffset(double time, TimezoneCache* cache) {
501 int64_t offset = Win32Time(time).DaylightSavingsOffset(cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000502 return static_cast<double>(offset);
503}
504
505
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000506int OS::GetLastError() {
507 return ::GetLastError();
508}
509
510
rossberg@chromium.org657d53b2012-07-12 11:06:03 +0000511int OS::GetCurrentProcessId() {
512 return static_cast<int>(::GetCurrentProcessId());
513}
514
515
machenbach@chromium.orgd0bddc62014-07-07 00:05:07 +0000516int OS::GetCurrentThreadId() {
517 return static_cast<int>(::GetCurrentThreadId());
518}
519
520
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000521// ----------------------------------------------------------------------------
522// Win32 console output.
523//
524// If a Win32 application is linked as a console application it has a normal
525// standard output and standard error. In this case normal printf works fine
526// for output. However, if the application is linked as a GUI application,
527// the process doesn't have a console, and therefore (debugging) output is lost.
528// This is the case if we are embedded in a windows program (like a browser).
529// In order to be able to get debug output in this case the the debugging
530// facility using OutputDebugString. This output goes to the active debugger
531// for the process (if any). Else the output can be monitored using DBMON.EXE.
532
533enum OutputMode {
534 UNKNOWN, // Output method has not yet been determined.
535 CONSOLE, // Output is written to stdout.
536 ODS // Output is written to debug facility.
537};
538
539static OutputMode output_mode = UNKNOWN; // Current output mode.
540
541
542// Determine if the process has a console for output.
543static bool HasConsole() {
544 // Only check the first time. Eventual race conditions are not a problem,
545 // because all threads will eventually determine the same mode.
546 if (output_mode == UNKNOWN) {
547 // We cannot just check that the standard output is attached to a console
548 // because this would fail if output is redirected to a file. Therefore we
549 // say that a process does not have an output console if either the
550 // standard output handle is invalid or its file type is unknown.
551 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
552 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
553 output_mode = CONSOLE;
554 else
555 output_mode = ODS;
556 }
557 return output_mode == CONSOLE;
558}
559
560
561static void VPrintHelper(FILE* stream, const char* format, va_list args) {
jkummerow@chromium.org50bb8682014-03-06 17:59:13 +0000562 if ((stream == stdout || stream == stderr) && !HasConsole()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563 // It is important to use safe print here in order to avoid
564 // overflowing the buffer. We might truncate the output, but this
565 // does not crash.
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000566 char buffer[4096];
567 OS::VSNPrintF(buffer, sizeof(buffer), format, args);
568 OutputDebugStringA(buffer);
jkummerow@chromium.org50bb8682014-03-06 17:59:13 +0000569 } else {
570 vfprintf(stream, format, args);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000571 }
572}
573
574
575FILE* OS::FOpen(const char* path, const char* mode) {
576 FILE* result;
577 if (fopen_s(&result, path, mode) == 0) {
578 return result;
579 } else {
580 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000581 }
582}
583
584
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000585bool OS::Remove(const char* path) {
586 return (DeleteFileA(path) != 0);
587}
588
589
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000590FILE* OS::OpenTemporaryFile() {
591 // tmpfile_s tries to use the root dir, don't use it.
592 char tempPathBuffer[MAX_PATH];
593 DWORD path_result = 0;
594 path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
595 if (path_result > MAX_PATH || path_result == 0) return NULL;
596 UINT name_result = 0;
597 char tempNameBuffer[MAX_PATH];
598 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
599 if (name_result == 0) return NULL;
600 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
601 if (result != NULL) {
602 Remove(tempNameBuffer); // Delete on close.
603 }
604 return result;
605}
606
607
ager@chromium.org71daaf62009-04-01 07:22:49 +0000608// Open log file in binary mode to avoid /n -> /r/n conversion.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000609const char* const OS::LogFileOpenMode = "wb";
ager@chromium.org71daaf62009-04-01 07:22:49 +0000610
611
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000612// Print (debug) message to console.
613void OS::Print(const char* format, ...) {
614 va_list args;
615 va_start(args, format);
616 VPrint(format, args);
617 va_end(args);
618}
619
620
621void OS::VPrint(const char* format, va_list args) {
622 VPrintHelper(stdout, format, args);
623}
624
625
whesse@chromium.org023421e2010-12-21 12:19:12 +0000626void OS::FPrint(FILE* out, const char* format, ...) {
627 va_list args;
628 va_start(args, format);
629 VFPrint(out, format, args);
630 va_end(args);
631}
632
633
634void OS::VFPrint(FILE* out, const char* format, va_list args) {
635 VPrintHelper(out, format, args);
636}
637
638
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000639// Print error message to console.
640void OS::PrintError(const char* format, ...) {
641 va_list args;
642 va_start(args, format);
643 VPrintError(format, args);
644 va_end(args);
645}
646
647
648void OS::VPrintError(const char* format, va_list args) {
649 VPrintHelper(stderr, format, args);
650}
651
652
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000653int OS::SNPrintF(char* str, int length, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000654 va_list args;
655 va_start(args, format);
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000656 int result = VSNPrintF(str, length, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000657 va_end(args);
658 return result;
659}
660
661
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000662int OS::VSNPrintF(char* str, int length, const char* format, va_list args) {
663 int n = _vsnprintf_s(str, length, _TRUNCATE, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000664 // Make sure to zero-terminate the string if the output was
665 // truncated or if there was an error.
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000666 if (n < 0 || n >= length) {
667 if (length > 0)
668 str[length - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000669 return -1;
670 } else {
671 return n;
672 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673}
674
675
ager@chromium.org381abbb2009-02-25 13:23:22 +0000676char* OS::StrChr(char* str, int c) {
677 return const_cast<char*>(strchr(str, c));
678}
679
680
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000681void OS::StrNCpy(char* dest, int length, const char* src, size_t n) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000682 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000683 size_t buffer_size = static_cast<size_t>(length);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000684 if (n + 1 > buffer_size) // count for trailing '\0'
685 n = _TRUNCATE;
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000686 int result = strncpy_s(dest, length, src, n);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000687 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +0000688 DCHECK(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000689}
690
691
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +0000692#undef _TRUNCATE
693#undef STRUNCATE
694
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000695
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000696// Get the system's page size used by VirtualAlloc() or the next power
697// of two. The reason for always returning a power of two is that the
698// rounding up in OS::Allocate expects that.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000699static size_t GetPageSize() {
700 static size_t page_size = 0;
701 if (page_size == 0) {
702 SYSTEM_INFO info;
703 GetSystemInfo(&info);
machenbach@chromium.org21d700e2014-09-03 08:32:14 +0000704 page_size = base::bits::RoundUpToPowerOfTwo32(info.dwPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000705 }
706 return page_size;
707}
708
709
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000710// The allocation alignment is the guaranteed alignment for
711// VirtualAlloc'ed blocks of memory.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000712size_t OS::AllocateAlignment() {
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000713 static size_t allocate_alignment = 0;
714 if (allocate_alignment == 0) {
715 SYSTEM_INFO info;
716 GetSystemInfo(&info);
717 allocate_alignment = info.dwAllocationGranularity;
718 }
719 return allocate_alignment;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000720}
721
722
yangguo@chromium.org5de00742014-07-01 11:58:10 +0000723static LazyInstance<RandomNumberGenerator>::type
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000724 platform_random_number_generator = LAZY_INSTANCE_INITIALIZER;
725
726
machenbach@chromium.org248dd432014-06-30 00:04:54 +0000727void OS::Initialize(int64_t random_seed, bool hard_abort,
728 const char* const gc_fake_mmap) {
729 if (random_seed) {
730 platform_random_number_generator.Pointer()->SetSeed(random_seed);
731 }
732 g_hard_abort = hard_abort;
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000733}
734
735
danno@chromium.orgd3c42102013-08-01 16:58:23 +0000736void* OS::GetRandomMmapAddr() {
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000737 // The address range used to randomize RWX allocations in OS::Allocate
738 // Try not to map pages into the default range that windows loads DLLs
739 // Use a multiple of 64k to prevent committing unused memory.
740 // Note: This does not guarantee RWX regions will be within the
741 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000742#ifdef V8_HOST_ARCH_64_BIT
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000743 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
744 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000745#else
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000746 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
747 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000748#endif
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000749 uintptr_t address =
750 (platform_random_number_generator.Pointer()->NextInt() << kPageSizeBits) |
751 kAllocationRandomAddressMin;
752 address &= kAllocationRandomAddressMax;
753 return reinterpret_cast<void *>(address);
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000754}
755
756
757static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
758 LPVOID base = NULL;
759
760 if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
761 // For exectutable pages try and randomize the allocation address
762 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
danno@chromium.orgd3c42102013-08-01 16:58:23 +0000763 base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection);
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000764 }
765 }
766
767 // After three attempts give up and let the OS find an address to use.
768 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
769
770 return base;
771}
772
773
kasper.lund7276f142008-07-30 08:49:36 +0000774void* OS::Allocate(const size_t requested,
775 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000776 bool is_executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000777 // VirtualAlloc rounds allocated size to page size automatically.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000778 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000779
780 // Windows XP SP2 allows Data Excution Prevention (DEP).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000781 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000782
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000783 LPVOID mbase = RandomizedVirtualAlloc(msize,
784 MEM_COMMIT | MEM_RESERVE,
785 prot);
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000786
machenbach@chromium.org1845eb02014-06-13 00:05:05 +0000787 if (mbase == NULL) return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000788
machenbach@chromium.orge20e19e2014-09-09 00:05:04 +0000789 DCHECK((reinterpret_cast<uintptr_t>(mbase) % OS::AllocateAlignment()) == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000790
791 *allocated = msize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000792 return mbase;
793}
794
795
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000796void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797 // TODO(1240712): VirtualFree has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000798 VirtualFree(address, 0, MEM_RELEASE);
799 USE(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000800}
801
802
ricow@chromium.org64e3a4b2011-12-13 08:07:27 +0000803intptr_t OS::CommitPageSize() {
804 return 4096;
805}
806
807
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000808void OS::ProtectCode(void* address, const size_t size) {
809 DWORD old_protect;
810 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
811}
812
813
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000814void OS::Guard(void* address, const size_t size) {
815 DWORD oldprotect;
hpayer@chromium.orgc5d49712013-09-11 08:25:48 +0000816 VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000817}
818
819
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000820void OS::Sleep(int milliseconds) {
821 ::Sleep(milliseconds);
822}
823
824
825void OS::Abort() {
machenbach@chromium.org248dd432014-06-30 00:04:54 +0000826 if (g_hard_abort) {
titzer@chromium.orgf5a24542014-03-04 09:06:17 +0000827 V8_IMMEDIATE_CRASH();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000828 }
titzer@chromium.orgf5a24542014-03-04 09:06:17 +0000829 // Make the MSVCRT do a silent abort.
830 raise(SIGABRT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000831}
832
833
kasper.lund7276f142008-07-30 08:49:36 +0000834void OS::DebugBreak() {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000835#ifdef _MSC_VER
rossberg@chromium.org92597162013-08-23 13:28:00 +0000836 // To avoid Visual Studio runtime support the following code can be used
837 // instead
838 // __asm { int 3 }
kasper.lund7276f142008-07-30 08:49:36 +0000839 __debugbreak();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000840#else
841 ::DebugBreak();
842#endif
kasper.lund7276f142008-07-30 08:49:36 +0000843}
844
845
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000846class Win32MemoryMappedFile : public OS::MemoryMappedFile {
847 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000848 Win32MemoryMappedFile(HANDLE file,
849 HANDLE file_mapping,
850 void* memory,
851 int size)
852 : file_(file),
853 file_mapping_(file_mapping),
854 memory_(memory),
855 size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000856 virtual ~Win32MemoryMappedFile();
857 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000858 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000859 private:
860 HANDLE file_;
861 HANDLE file_mapping_;
862 void* memory_;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000863 int size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000864};
865
866
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000867OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
868 // Open a physical file
869 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
870 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000871 if (file == INVALID_HANDLE_VALUE) return NULL;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000872
873 int size = static_cast<int>(GetFileSize(file, NULL));
874
875 // Create a file mapping for the physical file
876 HANDLE file_mapping = CreateFileMapping(file, NULL,
877 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
878 if (file_mapping == NULL) return NULL;
879
880 // Map a view of the file into memory
881 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
882 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
883}
884
885
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000886OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
887 void* initial) {
888 // Open a physical file
889 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
890 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
891 if (file == NULL) return NULL;
892 // Create a file mapping for the physical file
893 HANDLE file_mapping = CreateFileMapping(file, NULL,
894 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
895 if (file_mapping == NULL) return NULL;
896 // Map a view of the file into memory
897 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
yangguo@chromium.org5de00742014-07-01 11:58:10 +0000898 if (memory) memmove(memory, initial, size);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000899 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900}
901
902
903Win32MemoryMappedFile::~Win32MemoryMappedFile() {
904 if (memory_ != NULL)
905 UnmapViewOfFile(memory_);
906 CloseHandle(file_mapping_);
907 CloseHandle(file_);
908}
909
910
911// The following code loads functions defined in DbhHelp.h and TlHelp32.h
ager@chromium.org32912102009-01-16 10:38:43 +0000912// dynamically. This is to avoid being depending on dbghelp.dll and
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
914// kernel32.dll at some point so loading functions defines in TlHelp32.h
915// dynamically might not be necessary any more - for some versions of Windows?).
916
917// Function pointers to functions dynamically loaded from dbghelp.dll.
918#define DBGHELP_FUNCTION_LIST(V) \
919 V(SymInitialize) \
920 V(SymGetOptions) \
921 V(SymSetOptions) \
922 V(SymGetSearchPath) \
923 V(SymLoadModule64) \
924 V(StackWalk64) \
925 V(SymGetSymFromAddr64) \
926 V(SymGetLineFromAddr64) \
927 V(SymFunctionTableAccess64) \
928 V(SymGetModuleBase64)
929
930// Function pointers to functions dynamically loaded from dbghelp.dll.
931#define TLHELP32_FUNCTION_LIST(V) \
932 V(CreateToolhelp32Snapshot) \
933 V(Module32FirstW) \
934 V(Module32NextW)
935
936// Define the decoration to use for the type and variable name used for
937// dynamically loaded DLL function..
938#define DLL_FUNC_TYPE(name) _##name##_
939#define DLL_FUNC_VAR(name) _##name
940
941// Define the type for each dynamically loaded DLL function. The function
942// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
943// from the Windows include files are redefined here to have the function
944// definitions to be as close to the ones in the original .h files as possible.
945#ifndef IN
946#define IN
947#endif
948#ifndef VOID
949#define VOID void
950#endif
951
iposva@chromium.org245aa852009-02-10 00:49:54 +0000952// DbgHelp isn't supported on MinGW yet
953#ifndef __MINGW32__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000954// DbgHelp.h functions.
955typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
956 IN PSTR UserSearchPath,
957 IN BOOL fInvadeProcess);
958typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
959typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
960typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
961 IN HANDLE hProcess,
962 OUT PSTR SearchPath,
963 IN DWORD SearchPathLength);
964typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
965 IN HANDLE hProcess,
966 IN HANDLE hFile,
967 IN PSTR ImageName,
968 IN PSTR ModuleName,
969 IN DWORD64 BaseOfDll,
970 IN DWORD SizeOfDll);
971typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
972 DWORD MachineType,
973 HANDLE hProcess,
974 HANDLE hThread,
975 LPSTACKFRAME64 StackFrame,
976 PVOID ContextRecord,
977 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
978 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
979 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
980 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
981typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
982 IN HANDLE hProcess,
983 IN DWORD64 qwAddr,
984 OUT PDWORD64 pdwDisplacement,
985 OUT PIMAGEHLP_SYMBOL64 Symbol);
986typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
987 IN HANDLE hProcess,
988 IN DWORD64 qwAddr,
989 OUT PDWORD pdwDisplacement,
990 OUT PIMAGEHLP_LINE64 Line64);
991// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
992typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
993 HANDLE hProcess,
994 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
995typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
996 HANDLE hProcess,
997 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
998
999// TlHelp32.h functions.
1000typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1001 DWORD dwFlags,
1002 DWORD th32ProcessID);
1003typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1004 LPMODULEENTRY32W lpme);
1005typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1006 LPMODULEENTRY32W lpme);
1007
1008#undef IN
1009#undef VOID
1010
1011// Declare a variable for each dynamically loaded DLL function.
1012#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1013DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1014TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1015#undef DEF_DLL_FUNCTION
1016
1017// Load the functions. This function has a lot of "ugly" macros in order to
1018// keep down code duplication.
1019
1020static bool LoadDbgHelpAndTlHelp32() {
1021 static bool dbghelp_loaded = false;
1022
1023 if (dbghelp_loaded) return true;
1024
1025 HMODULE module;
1026
1027 // Load functions from the dbghelp.dll module.
1028 module = LoadLibrary(TEXT("dbghelp.dll"));
1029 if (module == NULL) {
1030 return false;
1031 }
1032
1033#define LOAD_DLL_FUNC(name) \
1034 DLL_FUNC_VAR(name) = \
1035 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1036
1037DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1038
1039#undef LOAD_DLL_FUNC
1040
1041 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1042 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1043 module = LoadLibrary(TEXT("kernel32.dll"));
1044 if (module == NULL) {
1045 return false;
1046 }
1047
1048#define LOAD_DLL_FUNC(name) \
1049 DLL_FUNC_VAR(name) = \
1050 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1051
1052TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1053
1054#undef LOAD_DLL_FUNC
1055
1056 // Check that all functions where loaded.
1057 bool result =
1058#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1059
1060DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1061TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1062
1063#undef DLL_FUNC_LOADED
1064 true;
1065
1066 dbghelp_loaded = result;
1067 return result;
ager@chromium.org32912102009-01-16 10:38:43 +00001068 // NOTE: The modules are never unloaded and will stay around until the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001069 // application is closed.
1070}
1071
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00001072#undef DBGHELP_FUNCTION_LIST
1073#undef TLHELP32_FUNCTION_LIST
1074#undef DLL_FUNC_VAR
1075#undef DLL_FUNC_TYPE
1076
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001077
1078// Load the symbols for generating stack traces.
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001079static std::vector<OS::SharedLibraryAddress> LoadSymbols(
1080 HANDLE process_handle) {
1081 static std::vector<OS::SharedLibraryAddress> result;
1082
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001083 static bool symbols_loaded = false;
1084
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001085 if (symbols_loaded) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001086
1087 BOOL ok;
1088
1089 // Initialize the symbol engine.
1090 ok = _SymInitialize(process_handle, // hProcess
1091 NULL, // UserSearchPath
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001092 false); // fInvadeProcess
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001093 if (!ok) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001094
1095 DWORD options = _SymGetOptions();
1096 options |= SYMOPT_LOAD_LINES;
1097 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1098 options = _SymSetOptions(options);
1099
1100 char buf[OS::kStackWalkMaxNameLen] = {0};
1101 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1102 if (!ok) {
1103 int err = GetLastError();
yangguo@chromium.org5de00742014-07-01 11:58:10 +00001104 OS::Print("%d\n", err);
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001105 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001106 }
1107
1108 HANDLE snapshot = _CreateToolhelp32Snapshot(
1109 TH32CS_SNAPMODULE, // dwFlags
1110 GetCurrentProcessId()); // th32ProcessId
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001111 if (snapshot == INVALID_HANDLE_VALUE) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001112 MODULEENTRY32W module_entry;
1113 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1114 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1115 while (cont) {
1116 DWORD64 base;
1117 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1118 // both unicode and ASCII strings even though the parameter is PSTR.
1119 base = _SymLoadModule64(
1120 process_handle, // hProcess
1121 0, // hFile
1122 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1123 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1124 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1125 module_entry.modBaseSize); // SizeOfDll
1126 if (base == 0) {
1127 int err = GetLastError();
1128 if (err != ERROR_MOD_NOT_FOUND &&
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001129 err != ERROR_INVALID_HANDLE) {
1130 result.clear();
1131 return result;
1132 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001133 }
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001134 int lib_name_length = WideCharToMultiByte(
1135 CP_UTF8, 0, module_entry.szExePath, -1, NULL, 0, NULL, NULL);
1136 std::string lib_name(lib_name_length, 0);
1137 WideCharToMultiByte(CP_UTF8, 0, module_entry.szExePath, -1, &lib_name[0],
1138 lib_name_length, NULL, NULL);
1139 result.push_back(OS::SharedLibraryAddress(
1140 lib_name, reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1141 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1142 module_entry.modBaseSize)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001143 cont = _Module32NextW(snapshot, &module_entry);
1144 }
1145 CloseHandle(snapshot);
1146
1147 symbols_loaded = true;
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001148 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001149}
1150
1151
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001152std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001153 // SharedLibraryEvents are logged when loading symbol information.
1154 // Only the shared libraries loaded at the time of the call to
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001155 // GetSharedLibraryAddresses are logged. DLLs loaded after
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001156 // initialization are not accounted for.
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001157 if (!LoadDbgHelpAndTlHelp32()) return std::vector<OS::SharedLibraryAddress>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001158 HANDLE process_handle = GetCurrentProcess();
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001159 return LoadSymbols(process_handle);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001160}
1161
1162
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00001163void OS::SignalCodeMovingGC() {
1164}
1165
1166
iposva@chromium.org245aa852009-02-10 00:49:54 +00001167#else // __MINGW32__
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001168std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
1169 return std::vector<OS::SharedLibraryAddress>();
1170}
1171
1172
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001173void OS::SignalCodeMovingGC() { }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001174#endif // __MINGW32__
1175
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001176
1177double OS::nan_value() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001178#ifdef _MSC_VER
yangguo@chromium.org5de00742014-07-01 11:58:10 +00001179 return std::numeric_limits<double>::quiet_NaN();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001180#else // _MSC_VER
1181 return NAN;
1182#endif // _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001183}
1184
ager@chromium.org236ad962008-09-25 09:45:57 +00001185
1186int OS::ActivationFrameAlignment() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001187#ifdef _WIN64
1188 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +00001189#elif defined(__MINGW32__)
1190 // With gcc 4.4 the tree vectorization optimizer can generate code
1191 // that requires 16 byte alignment such as movdqa on x86.
1192 return 16;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001193#else
1194 return 8; // Floating-point math runs faster with 8-byte alignment.
1195#endif
ager@chromium.org236ad962008-09-25 09:45:57 +00001196}
1197
1198
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001199VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001200
1201
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001202VirtualMemory::VirtualMemory(size_t size)
1203 : address_(ReserveRegion(size)), size_(size) { }
1204
1205
1206VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1207 : address_(NULL), size_(0) {
machenbach@chromium.orge20e19e2014-09-09 00:05:04 +00001208 DCHECK((alignment % OS::AllocateAlignment()) == 0);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001209 size_t request_size = RoundUp(size + alignment,
1210 static_cast<intptr_t>(OS::AllocateAlignment()));
1211 void* address = ReserveRegion(request_size);
1212 if (address == NULL) return;
machenbach@chromium.org248dd432014-06-30 00:04:54 +00001213 uint8_t* base = RoundUp(static_cast<uint8_t*>(address), alignment);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001214 // Try reducing the size by freeing and then reallocating a specific area.
1215 bool result = ReleaseRegion(address, request_size);
1216 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001217 DCHECK(result);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001218 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1219 if (address != NULL) {
1220 request_size = size;
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001221 DCHECK(base == static_cast<uint8_t*>(address));
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001222 } else {
1223 // Resizing failed, just go with a bigger area.
1224 address = ReserveRegion(request_size);
1225 if (address == NULL) return;
1226 }
1227 address_ = address;
1228 size_ = request_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001229}
1230
1231
1232VirtualMemory::~VirtualMemory() {
1233 if (IsReserved()) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001234 bool result = ReleaseRegion(address(), size());
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001235 DCHECK(result);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001236 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001237 }
1238}
1239
1240
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001241bool VirtualMemory::IsReserved() {
1242 return address_ != NULL;
1243}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001244
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001245
1246void VirtualMemory::Reset() {
1247 address_ = NULL;
1248 size_ = 0;
1249}
1250
1251
1252bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001253 return CommitRegion(address, size, is_executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001254}
1255
1256
1257bool VirtualMemory::Uncommit(void* address, size_t size) {
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001258 DCHECK(IsReserved());
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001259 return UncommitRegion(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001260}
1261
1262
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001263bool VirtualMemory::Guard(void* address) {
1264 if (NULL == VirtualAlloc(address,
1265 OS::CommitPageSize(),
1266 MEM_COMMIT,
hpayer@chromium.orgc5d49712013-09-11 08:25:48 +00001267 PAGE_NOACCESS)) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001268 return false;
1269 }
1270 return true;
1271}
1272
1273
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001274void* VirtualMemory::ReserveRegion(size_t size) {
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +00001275 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001276}
1277
1278
1279bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1280 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1281 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1282 return false;
1283 }
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001284 return true;
1285}
1286
1287
1288bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1289 return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1290}
1291
1292
1293bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1294 return VirtualFree(base, 0, MEM_RELEASE) != 0;
1295}
1296
1297
danno@chromium.org72204d52012-10-31 10:02:10 +00001298bool VirtualMemory::HasLazyCommits() {
1299 // TODO(alph): implement for the platform.
1300 return false;
1301}
1302
1303
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001304// ----------------------------------------------------------------------------
1305// Win32 thread support.
1306
1307// Definition of invalid thread handle and id.
1308static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001309
1310// Entry point for threads. The supplied argument is a pointer to the thread
1311// object. The entry function dispatches to the run method in the thread
1312// object. It is important that this function has __stdcall calling
1313// convention.
1314static unsigned int __stdcall ThreadEntry(void* arg) {
1315 Thread* thread = reinterpret_cast<Thread*>(arg);
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001316 thread->NotifyStartedAndRun();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001317 return 0;
1318}
1319
1320
machenbach@chromium.org248dd432014-06-30 00:04:54 +00001321class Thread::PlatformData {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001322 public:
1323 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1324 HANDLE thread_;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001325 unsigned thread_id_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001326};
1327
1328
1329// Initialize a Win32 thread object. The thread has an invalid thread
1330// handle until it is started.
1331
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001332Thread::Thread(const Options& options)
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001333 : stack_size_(options.stack_size()),
1334 start_semaphore_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001335 data_ = new PlatformData(kNoThread);
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00001336 set_name(options.name());
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001337}
1338
1339
1340void Thread::set_name(const char* name) {
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +00001341 OS::StrNCpy(name_, sizeof(name_), name, strlen(name));
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001342 name_[sizeof(name_) - 1] = '\0';
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001343}
1344
1345
1346// Close our own handle for the thread.
1347Thread::~Thread() {
1348 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1349 delete data_;
1350}
1351
1352
1353// Create a new thread. It is important to use _beginthreadex() instead of
1354// the Win32 function CreateThread(), because the CreateThread() does not
1355// initialize thread specific structures in the C runtime library.
1356void Thread::Start() {
1357 data_->thread_ = reinterpret_cast<HANDLE>(
1358 _beginthreadex(NULL,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001359 static_cast<unsigned>(stack_size_),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001360 ThreadEntry,
1361 this,
1362 0,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001363 &data_->thread_id_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001364}
1365
1366
1367// Wait for thread to terminate.
1368void Thread::Join() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001369 if (data_->thread_id_ != GetCurrentThreadId()) {
1370 WaitForSingleObject(data_->thread_, INFINITE);
1371 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001372}
1373
1374
1375Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1376 DWORD result = TlsAlloc();
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001377 DCHECK(result != TLS_OUT_OF_INDEXES);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001378 return static_cast<LocalStorageKey>(result);
1379}
1380
1381
1382void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1383 BOOL result = TlsFree(static_cast<DWORD>(key));
1384 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001385 DCHECK(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001386}
1387
1388
1389void* Thread::GetThreadLocal(LocalStorageKey key) {
1390 return TlsGetValue(static_cast<DWORD>(key));
1391}
1392
1393
1394void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1395 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1396 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001397 DCHECK(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001398}
1399
1400
1401
1402void Thread::YieldCPU() {
1403 Sleep(0);
1404}
1405
yangguo@chromium.org5de00742014-07-01 11:58:10 +00001406} } // namespace v8::base