blob: 9f106785eb1cebd00b8ff8492c6dc9c126b94f4a [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.orgc3564d82014-06-26 00:05:26 +000024#include "src/base/lazy-instance.h"
yangguo@chromium.org5de00742014-07-01 11:58:10 +000025#include "src/base/macros.h"
26#include "src/base/platform/platform.h"
27#include "src/base/platform/time.h"
28#include "src/base/utils/random-number-generator.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000029
iposva@chromium.org245aa852009-02-10 00:49:54 +000030#ifdef _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000031
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032// Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
33// defined in strings.h.
34int strncasecmp(const char* s1, const char* s2, int n) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000035 return _strnicmp(s1, s2, n);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036}
37
iposva@chromium.org245aa852009-02-10 00:49:54 +000038#endif // _MSC_VER
39
40
41// Extra functions for MinGW. Most of these are the _s functions which are in
42// the Microsoft Visual Studio C++ CRT.
43#ifdef __MINGW32__
44
svenpanne@chromium.orgfb046332012-04-19 12:02:44 +000045
46#ifndef __MINGW64_VERSION_MAJOR
47
48#define _TRUNCATE 0
49#define STRUNCATE 80
50
51inline void MemoryBarrier() {
52 int barrier = 0;
53 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
54}
55
56#endif // __MINGW64_VERSION_MAJOR
57
58
iposva@chromium.org245aa852009-02-10 00:49:54 +000059int localtime_s(tm* out_tm, const time_t* time) {
60 tm* posix_local_time_struct = localtime(time);
61 if (posix_local_time_struct == NULL) return 1;
62 *out_tm = *posix_local_time_struct;
63 return 0;
64}
65
66
iposva@chromium.org245aa852009-02-10 00:49:54 +000067int fopen_s(FILE** pFile, const char* filename, const char* mode) {
68 *pFile = fopen(filename, mode);
69 return *pFile != NULL ? 0 : 1;
70}
71
iposva@chromium.org245aa852009-02-10 00:49:54 +000072int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
73 const char* format, va_list argptr) {
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +000074 DCHECK(count == _TRUNCATE);
iposva@chromium.org245aa852009-02-10 00:49:54 +000075 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
76}
iposva@chromium.org245aa852009-02-10 00:49:54 +000077
78
sgjesse@chromium.org6db88712011-07-11 11:41:22 +000079int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
80 CHECK(source != NULL);
81 CHECK(dest != NULL);
82 CHECK_GT(dest_size, 0);
83
84 if (count == _TRUNCATE) {
85 while (dest_size > 0 && *source != 0) {
86 *(dest++) = *(source++);
87 --dest_size;
88 }
89 if (dest_size == 0) {
90 *(dest - 1) = 0;
91 return STRUNCATE;
92 }
93 } else {
94 while (dest_size > 0 && count > 0 && *source != 0) {
95 *(dest++) = *(source++);
96 --dest_size;
97 --count;
98 }
99 }
100 CHECK_GT(dest_size, 0);
101 *dest = 0;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000102 return 0;
103}
104
105#endif // __MINGW32__
106
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000107namespace v8 {
yangguo@chromium.org5de00742014-07-01 11:58:10 +0000108namespace base {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000109
machenbach@chromium.org248dd432014-06-30 00:04:54 +0000110namespace {
111
112bool g_hard_abort = false;
113
114} // namespace
115
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000116intptr_t OS::MaxVirtualMemory() {
117 return 0;
118}
119
120
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000121class TimezoneCache {
122 public:
123 TimezoneCache() : initialized_(false) { }
124
125 void Clear() {
126 initialized_ = false;
127 }
128
129 // Initialize timezone information. The timezone information is obtained from
130 // windows. If we cannot get the timezone information we fall back to CET.
131 void InitializeIfNeeded() {
132 // Just return if timezone information has already been initialized.
133 if (initialized_) return;
134
135 // Initialize POSIX time zone data.
136 _tzset();
137 // Obtain timezone information from operating system.
138 memset(&tzinfo_, 0, sizeof(tzinfo_));
139 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
140 // If we cannot get timezone information we fall back to CET.
141 tzinfo_.Bias = -60;
142 tzinfo_.StandardDate.wMonth = 10;
143 tzinfo_.StandardDate.wDay = 5;
144 tzinfo_.StandardDate.wHour = 3;
145 tzinfo_.StandardBias = 0;
146 tzinfo_.DaylightDate.wMonth = 3;
147 tzinfo_.DaylightDate.wDay = 5;
148 tzinfo_.DaylightDate.wHour = 2;
149 tzinfo_.DaylightBias = -60;
150 }
151
152 // Make standard and DST timezone names.
153 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
154 std_tz_name_, kTzNameSize, NULL, NULL);
155 std_tz_name_[kTzNameSize - 1] = '\0';
156 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
157 dst_tz_name_, kTzNameSize, NULL, NULL);
158 dst_tz_name_[kTzNameSize - 1] = '\0';
159
160 // If OS returned empty string or resource id (like "@tzres.dll,-211")
161 // simply guess the name from the UTC bias of the timezone.
162 // To properly resolve the resource identifier requires a library load,
163 // which is not possible in a sandbox.
164 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000165 OS::SNPrintF(std_tz_name_, kTzNameSize - 1,
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000166 "%s Standard Time",
167 GuessTimezoneNameFromBias(tzinfo_.Bias));
168 }
169 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000170 OS::SNPrintF(dst_tz_name_, kTzNameSize - 1,
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000171 "%s Daylight Time",
172 GuessTimezoneNameFromBias(tzinfo_.Bias));
173 }
174 // Timezone information initialized.
175 initialized_ = true;
176 }
177
178 // Guess the name of the timezone from the bias.
179 // The guess is very biased towards the northern hemisphere.
180 const char* GuessTimezoneNameFromBias(int bias) {
181 static const int kHour = 60;
182 switch (-bias) {
183 case -9*kHour: return "Alaska";
184 case -8*kHour: return "Pacific";
185 case -7*kHour: return "Mountain";
186 case -6*kHour: return "Central";
187 case -5*kHour: return "Eastern";
188 case -4*kHour: return "Atlantic";
189 case 0*kHour: return "GMT";
190 case +1*kHour: return "Central Europe";
191 case +2*kHour: return "Eastern Europe";
192 case +3*kHour: return "Russia";
193 case +5*kHour + 30: return "India";
194 case +8*kHour: return "China";
195 case +9*kHour: return "Japan";
196 case +12*kHour: return "New Zealand";
197 default: return "Local";
198 }
199 }
200
201
202 private:
203 static const int kTzNameSize = 128;
204 bool initialized_;
205 char std_tz_name_[kTzNameSize];
206 char dst_tz_name_[kTzNameSize];
207 TIME_ZONE_INFORMATION tzinfo_;
208 friend class Win32Time;
209};
210
211
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000212// ----------------------------------------------------------------------------
213// The Time class represents time on win32. A timestamp is represented as
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000214// a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000215// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
216// January 1, 1970.
217
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000218class Win32Time {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219 public:
220 // Constructors.
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000221 Win32Time();
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000222 explicit Win32Time(double jstime);
223 Win32Time(int year, int mon, int day, int hour, int min, int sec);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000224
225 // Convert timestamp to JavaScript representation.
226 double ToJSTime();
227
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000228 // Set timestamp to current time.
229 void SetToCurrentTime();
230
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000231 // Returns the local timezone offset in milliseconds east of UTC. This is
232 // the number of milliseconds you must add to UTC to get local time, i.e.
233 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
234 // routine also takes into account whether daylight saving is effect
235 // at the time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000236 int64_t LocalOffset(TimezoneCache* cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000237
238 // Returns the daylight savings time offset for the time in milliseconds.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000239 int64_t DaylightSavingsOffset(TimezoneCache* cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000240
241 // Returns a string identifying the current timezone for the
242 // timestamp taking into account daylight saving.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000243 char* LocalTimezone(TimezoneCache* cache);
dslomov@chromium.org486536d2014-03-12 13:09:18 +0000244
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245 private:
246 // Constants for time conversion.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000247 static const int64_t kTimeEpoc = 116444736000000000LL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000248 static const int64_t kTimeScaler = 10000;
249 static const int64_t kMsPerMinute = 60000;
250
251 // Constants for timezone information.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252 static const bool kShortTzNames = false;
253
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254 // Return whether or not daylight savings time is in effect at this time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000255 bool InDST(TimezoneCache* cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000256
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000257 // Accessor for FILETIME representation.
258 FILETIME& ft() { return time_.ft_; }
259
260 // Accessor for integer representation.
261 int64_t& t() { return time_.t_; }
262
263 // Although win32 uses 64-bit integers for representing timestamps,
264 // these are packed into a FILETIME structure. The FILETIME structure
265 // is just a struct representing a 64-bit integer. The TimeStamp union
266 // allows access to both a FILETIME and an integer representation of
267 // the timestamp.
268 union TimeStamp {
269 FILETIME ft_;
270 int64_t t_;
271 };
272
273 TimeStamp time_;
274};
275
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +0000276
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000277// Initialize timestamp to start of epoc.
278Win32Time::Win32Time() {
279 t() = 0;
280}
281
282
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000283// Initialize timestamp from a JavaScript timestamp.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000284Win32Time::Win32Time(double jstime) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000285 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000286}
287
288
289// Initialize timestamp from date/time components.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000290Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000291 SYSTEMTIME st;
292 st.wYear = year;
293 st.wMonth = mon;
294 st.wDay = day;
295 st.wHour = hour;
296 st.wMinute = min;
297 st.wSecond = sec;
298 st.wMilliseconds = 0;
299 SystemTimeToFileTime(&st, &ft());
300}
301
302
303// Convert timestamp to JavaScript timestamp.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000304double Win32Time::ToJSTime() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000305 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
306}
307
308
machenbach@chromium.org8e36b5b2013-09-26 07:36:30 +0000309// Set timestamp to current time.
310void Win32Time::SetToCurrentTime() {
311 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
312 // Because we're fast, we like fast timers which have at least a
313 // 1ms resolution.
314 //
315 // timeGetTime() provides 1ms granularity when combined with
316 // timeBeginPeriod(). If the host application for v8 wants fast
317 // timers, it can use timeBeginPeriod to increase the resolution.
318 //
319 // Using timeGetTime() has a drawback because it is a 32bit value
320 // and hence rolls-over every ~49days.
321 //
322 // To use the clock, we use GetSystemTimeAsFileTime as our base;
323 // and then use timeGetTime to extrapolate current time from the
324 // start time. To deal with rollovers, we resync the clock
325 // any time when more than kMaxClockElapsedTime has passed or
326 // whenever timeGetTime creates a rollover.
327
328 static bool initialized = false;
329 static TimeStamp init_time;
330 static DWORD init_ticks;
331 static const int64_t kHundredNanosecondsPerSecond = 10000000;
332 static const int64_t kMaxClockElapsedTime =
333 60*kHundredNanosecondsPerSecond; // 1 minute
334
335 // If we are uninitialized, we need to resync the clock.
336 bool needs_resync = !initialized;
337
338 // Get the current time.
339 TimeStamp time_now;
340 GetSystemTimeAsFileTime(&time_now.ft_);
341 DWORD ticks_now = timeGetTime();
342
343 // Check if we need to resync due to clock rollover.
344 needs_resync |= ticks_now < init_ticks;
345
346 // Check if we need to resync due to elapsed time.
347 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
348
349 // Check if we need to resync due to backwards time change.
350 needs_resync |= time_now.t_ < init_time.t_;
351
352 // Resync the clock if necessary.
353 if (needs_resync) {
354 GetSystemTimeAsFileTime(&init_time.ft_);
355 init_ticks = ticks_now = timeGetTime();
356 initialized = true;
357 }
358
359 // Finally, compute the actual time. Why is this so hard.
360 DWORD elapsed = ticks_now - init_ticks;
361 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
362}
363
364
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000365// Return the local timezone offset in milliseconds east of UTC. This
366// takes into account whether daylight saving is in effect at the time.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000367// Only times in the 32-bit Unix range may be passed to this function.
368// Also, adding the time-zone offset to the input must not overflow.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000369// The function EquivalentTime() in date.js guarantees this.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000370int64_t Win32Time::LocalOffset(TimezoneCache* cache) {
371 cache->InitializeIfNeeded();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000372
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000373 Win32Time rounded_to_second(*this);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000374 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
375 1000 * kTimeScaler;
376 // Convert to local time using POSIX localtime function.
377 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
378 // very slow. Other browsers use localtime().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000380 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
381 // POSIX seconds past 1/1/1970 0:00:00.
382 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
383 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
384 return 0;
385 }
386 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
387 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000388
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000389 // Convert to local time, as struct with fields for day, hour, year, etc.
390 tm posix_local_time_struct;
391 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000392
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000393 if (posix_local_time_struct.tm_isdst > 0) {
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000394 return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000395 } else if (posix_local_time_struct.tm_isdst == 0) {
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000396 return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000397 } else {
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000398 return cache->tzinfo_.Bias * -kMsPerMinute;
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000399 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000400}
401
402
403// Return whether or not daylight savings time is in effect at this time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000404bool Win32Time::InDST(TimezoneCache* cache) {
405 cache->InitializeIfNeeded();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000406
407 // Determine if DST is in effect at the specified time.
408 bool in_dst = false;
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000409 if (cache->tzinfo_.StandardDate.wMonth != 0 ||
410 cache->tzinfo_.DaylightDate.wMonth != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000411 // Get the local timezone offset for the timestamp in milliseconds.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000412 int64_t offset = LocalOffset(cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413
414 // Compute the offset for DST. The bias parameters in the timezone info
415 // are specified in minutes. These must be converted to milliseconds.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000416 int64_t dstofs =
417 -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418
419 // If the local time offset equals the timezone bias plus the daylight
420 // bias then DST is in effect.
421 in_dst = offset == dstofs;
422 }
423
424 return in_dst;
425}
426
427
ager@chromium.org32912102009-01-16 10:38:43 +0000428// Return the daylight savings time offset for this time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000429int64_t Win32Time::DaylightSavingsOffset(TimezoneCache* cache) {
430 return InDST(cache) ? 60 * kMsPerMinute : 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000431}
432
433
434// Returns a string identifying the current timezone for the
435// timestamp taking into account daylight saving.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000436char* Win32Time::LocalTimezone(TimezoneCache* cache) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000437 // Return the standard or DST time zone name based on whether daylight
438 // saving is in effect at the given time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000439 return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000440}
441
442
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443// Returns the accumulated user time for thread.
444int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
445 FILETIME dummy;
446 uint64_t usertime;
447
448 // Get the amount of time that the thread has executed in user mode.
449 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
450 reinterpret_cast<FILETIME*>(&usertime))) return -1;
451
452 // Adjust the resolution to micro-seconds.
453 usertime /= 10;
454
455 // Convert to seconds and microseconds
456 *secs = static_cast<uint32_t>(usertime / 1000000);
457 *usecs = static_cast<uint32_t>(usertime % 1000000);
458 return 0;
459}
460
461
462// Returns current time as the number of milliseconds since
463// 00:00:00 UTC, January 1, 1970.
464double OS::TimeCurrentMillis() {
jkummerow@chromium.orgd8a3a142013-10-03 12:15:05 +0000465 return Time::Now().ToJsTime();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000466}
467
468
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000469TimezoneCache* OS::CreateTimezoneCache() {
470 return new TimezoneCache();
471}
472
473
474void OS::DisposeTimezoneCache(TimezoneCache* cache) {
475 delete cache;
476}
477
478
479void OS::ClearTimezoneCache(TimezoneCache* cache) {
480 cache->Clear();
481}
482
483
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000484// Returns a string identifying the current timezone taking into
485// account daylight saving.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000486const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
487 return Win32Time(time).LocalTimezone(cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000488}
489
490
kasper.lund7276f142008-07-30 08:49:36 +0000491// Returns the local time offset in milliseconds east of UTC without
492// taking daylight savings time into account.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000493double OS::LocalTimeOffset(TimezoneCache* cache) {
kasper.lund7276f142008-07-30 08:49:36 +0000494 // Use current time, rounded to the millisecond.
jkummerow@chromium.orgdc94e192013-08-30 11:35:42 +0000495 Win32Time t(TimeCurrentMillis());
kasper.lund7276f142008-07-30 08:49:36 +0000496 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000497 return static_cast<double>(t.LocalOffset(cache) -
498 t.DaylightSavingsOffset(cache));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000499}
500
501
502// Returns the daylight savings offset in milliseconds for the given
503// time.
dslomov@chromium.org6b6df382014-03-14 16:14:53 +0000504double OS::DaylightSavingsOffset(double time, TimezoneCache* cache) {
505 int64_t offset = Win32Time(time).DaylightSavingsOffset(cache);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000506 return static_cast<double>(offset);
507}
508
509
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000510int OS::GetLastError() {
511 return ::GetLastError();
512}
513
514
rossberg@chromium.org657d53b2012-07-12 11:06:03 +0000515int OS::GetCurrentProcessId() {
516 return static_cast<int>(::GetCurrentProcessId());
517}
518
519
machenbach@chromium.orgd0bddc62014-07-07 00:05:07 +0000520int OS::GetCurrentThreadId() {
521 return static_cast<int>(::GetCurrentThreadId());
522}
523
524
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000525// ----------------------------------------------------------------------------
526// Win32 console output.
527//
528// If a Win32 application is linked as a console application it has a normal
529// standard output and standard error. In this case normal printf works fine
530// for output. However, if the application is linked as a GUI application,
531// the process doesn't have a console, and therefore (debugging) output is lost.
532// This is the case if we are embedded in a windows program (like a browser).
533// In order to be able to get debug output in this case the the debugging
534// facility using OutputDebugString. This output goes to the active debugger
535// for the process (if any). Else the output can be monitored using DBMON.EXE.
536
537enum OutputMode {
538 UNKNOWN, // Output method has not yet been determined.
539 CONSOLE, // Output is written to stdout.
540 ODS // Output is written to debug facility.
541};
542
543static OutputMode output_mode = UNKNOWN; // Current output mode.
544
545
546// Determine if the process has a console for output.
547static bool HasConsole() {
548 // Only check the first time. Eventual race conditions are not a problem,
549 // because all threads will eventually determine the same mode.
550 if (output_mode == UNKNOWN) {
551 // We cannot just check that the standard output is attached to a console
552 // because this would fail if output is redirected to a file. Therefore we
553 // say that a process does not have an output console if either the
554 // standard output handle is invalid or its file type is unknown.
555 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
556 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
557 output_mode = CONSOLE;
558 else
559 output_mode = ODS;
560 }
561 return output_mode == CONSOLE;
562}
563
564
565static void VPrintHelper(FILE* stream, const char* format, va_list args) {
jkummerow@chromium.org50bb8682014-03-06 17:59:13 +0000566 if ((stream == stdout || stream == stderr) && !HasConsole()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000567 // It is important to use safe print here in order to avoid
568 // overflowing the buffer. We might truncate the output, but this
569 // does not crash.
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000570 char buffer[4096];
571 OS::VSNPrintF(buffer, sizeof(buffer), format, args);
572 OutputDebugStringA(buffer);
jkummerow@chromium.org50bb8682014-03-06 17:59:13 +0000573 } else {
574 vfprintf(stream, format, args);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000575 }
576}
577
578
579FILE* OS::FOpen(const char* path, const char* mode) {
580 FILE* result;
581 if (fopen_s(&result, path, mode) == 0) {
582 return result;
583 } else {
584 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585 }
586}
587
588
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000589bool OS::Remove(const char* path) {
590 return (DeleteFileA(path) != 0);
591}
592
593
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000594FILE* OS::OpenTemporaryFile() {
595 // tmpfile_s tries to use the root dir, don't use it.
596 char tempPathBuffer[MAX_PATH];
597 DWORD path_result = 0;
598 path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
599 if (path_result > MAX_PATH || path_result == 0) return NULL;
600 UINT name_result = 0;
601 char tempNameBuffer[MAX_PATH];
602 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
603 if (name_result == 0) return NULL;
604 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
605 if (result != NULL) {
606 Remove(tempNameBuffer); // Delete on close.
607 }
608 return result;
609}
610
611
ager@chromium.org71daaf62009-04-01 07:22:49 +0000612// Open log file in binary mode to avoid /n -> /r/n conversion.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000613const char* const OS::LogFileOpenMode = "wb";
ager@chromium.org71daaf62009-04-01 07:22:49 +0000614
615
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000616// Print (debug) message to console.
617void OS::Print(const char* format, ...) {
618 va_list args;
619 va_start(args, format);
620 VPrint(format, args);
621 va_end(args);
622}
623
624
625void OS::VPrint(const char* format, va_list args) {
626 VPrintHelper(stdout, format, args);
627}
628
629
whesse@chromium.org023421e2010-12-21 12:19:12 +0000630void OS::FPrint(FILE* out, const char* format, ...) {
631 va_list args;
632 va_start(args, format);
633 VFPrint(out, format, args);
634 va_end(args);
635}
636
637
638void OS::VFPrint(FILE* out, const char* format, va_list args) {
639 VPrintHelper(out, format, args);
640}
641
642
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000643// Print error message to console.
644void OS::PrintError(const char* format, ...) {
645 va_list args;
646 va_start(args, format);
647 VPrintError(format, args);
648 va_end(args);
649}
650
651
652void OS::VPrintError(const char* format, va_list args) {
653 VPrintHelper(stderr, format, args);
654}
655
656
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000657int OS::SNPrintF(char* str, int length, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000658 va_list args;
659 va_start(args, format);
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000660 int result = VSNPrintF(str, length, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000661 va_end(args);
662 return result;
663}
664
665
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000666int OS::VSNPrintF(char* str, int length, const char* format, va_list args) {
667 int n = _vsnprintf_s(str, length, _TRUNCATE, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000668 // Make sure to zero-terminate the string if the output was
669 // truncated or if there was an error.
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000670 if (n < 0 || n >= length) {
671 if (length > 0)
672 str[length - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000673 return -1;
674 } else {
675 return n;
676 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000677}
678
679
ager@chromium.org381abbb2009-02-25 13:23:22 +0000680char* OS::StrChr(char* str, int c) {
681 return const_cast<char*>(strchr(str, c));
682}
683
684
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000685void OS::StrNCpy(char* dest, int length, const char* src, size_t n) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000686 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000687 size_t buffer_size = static_cast<size_t>(length);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000688 if (n + 1 > buffer_size) // count for trailing '\0'
689 n = _TRUNCATE;
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +0000690 int result = strncpy_s(dest, length, src, n);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000691 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +0000692 DCHECK(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000693}
694
695
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +0000696#undef _TRUNCATE
697#undef STRUNCATE
698
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000699
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000700// Get the system's page size used by VirtualAlloc() or the next power
701// of two. The reason for always returning a power of two is that the
702// rounding up in OS::Allocate expects that.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000703static size_t GetPageSize() {
704 static size_t page_size = 0;
705 if (page_size == 0) {
706 SYSTEM_INFO info;
707 GetSystemInfo(&info);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000708 page_size = RoundUpToPowerOf2(info.dwPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000709 }
710 return page_size;
711}
712
713
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000714// The allocation alignment is the guaranteed alignment for
715// VirtualAlloc'ed blocks of memory.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000716size_t OS::AllocateAlignment() {
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000717 static size_t allocate_alignment = 0;
718 if (allocate_alignment == 0) {
719 SYSTEM_INFO info;
720 GetSystemInfo(&info);
721 allocate_alignment = info.dwAllocationGranularity;
722 }
723 return allocate_alignment;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000724}
725
726
yangguo@chromium.org5de00742014-07-01 11:58:10 +0000727static LazyInstance<RandomNumberGenerator>::type
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000728 platform_random_number_generator = LAZY_INSTANCE_INITIALIZER;
729
730
machenbach@chromium.org248dd432014-06-30 00:04:54 +0000731void OS::Initialize(int64_t random_seed, bool hard_abort,
732 const char* const gc_fake_mmap) {
733 if (random_seed) {
734 platform_random_number_generator.Pointer()->SetSeed(random_seed);
735 }
736 g_hard_abort = hard_abort;
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000737}
738
739
danno@chromium.orgd3c42102013-08-01 16:58:23 +0000740void* OS::GetRandomMmapAddr() {
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000741 // The address range used to randomize RWX allocations in OS::Allocate
742 // Try not to map pages into the default range that windows loads DLLs
743 // Use a multiple of 64k to prevent committing unused memory.
744 // Note: This does not guarantee RWX regions will be within the
745 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000746#ifdef V8_HOST_ARCH_64_BIT
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000747 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
748 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000749#else
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000750 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
751 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000752#endif
machenbach@chromium.orgc3564d82014-06-26 00:05:26 +0000753 uintptr_t address =
754 (platform_random_number_generator.Pointer()->NextInt() << kPageSizeBits) |
755 kAllocationRandomAddressMin;
756 address &= kAllocationRandomAddressMax;
757 return reinterpret_cast<void *>(address);
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000758}
759
760
761static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
762 LPVOID base = NULL;
763
764 if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
765 // For exectutable pages try and randomize the allocation address
766 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
danno@chromium.orgd3c42102013-08-01 16:58:23 +0000767 base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection);
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000768 }
769 }
770
771 // After three attempts give up and let the OS find an address to use.
772 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
773
774 return base;
775}
776
777
kasper.lund7276f142008-07-30 08:49:36 +0000778void* OS::Allocate(const size_t requested,
779 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000780 bool is_executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000781 // VirtualAlloc rounds allocated size to page size automatically.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000782 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000783
784 // Windows XP SP2 allows Data Excution Prevention (DEP).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000785 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000786
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000787 LPVOID mbase = RandomizedVirtualAlloc(msize,
788 MEM_COMMIT | MEM_RESERVE,
789 prot);
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000790
machenbach@chromium.org1845eb02014-06-13 00:05:05 +0000791 if (mbase == NULL) return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000792
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +0000793 DCHECK(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000794
795 *allocated = msize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000796 return mbase;
797}
798
799
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000800void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801 // TODO(1240712): VirtualFree has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000802 VirtualFree(address, 0, MEM_RELEASE);
803 USE(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000804}
805
806
ricow@chromium.org64e3a4b2011-12-13 08:07:27 +0000807intptr_t OS::CommitPageSize() {
808 return 4096;
809}
810
811
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000812void OS::ProtectCode(void* address, const size_t size) {
813 DWORD old_protect;
814 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
815}
816
817
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000818void OS::Guard(void* address, const size_t size) {
819 DWORD oldprotect;
hpayer@chromium.orgc5d49712013-09-11 08:25:48 +0000820 VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000821}
822
823
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000824void OS::Sleep(int milliseconds) {
825 ::Sleep(milliseconds);
826}
827
828
829void OS::Abort() {
machenbach@chromium.org248dd432014-06-30 00:04:54 +0000830 if (g_hard_abort) {
titzer@chromium.orgf5a24542014-03-04 09:06:17 +0000831 V8_IMMEDIATE_CRASH();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000832 }
titzer@chromium.orgf5a24542014-03-04 09:06:17 +0000833 // Make the MSVCRT do a silent abort.
834 raise(SIGABRT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000835}
836
837
kasper.lund7276f142008-07-30 08:49:36 +0000838void OS::DebugBreak() {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000839#ifdef _MSC_VER
rossberg@chromium.org92597162013-08-23 13:28:00 +0000840 // To avoid Visual Studio runtime support the following code can be used
841 // instead
842 // __asm { int 3 }
kasper.lund7276f142008-07-30 08:49:36 +0000843 __debugbreak();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000844#else
845 ::DebugBreak();
846#endif
kasper.lund7276f142008-07-30 08:49:36 +0000847}
848
849
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000850class Win32MemoryMappedFile : public OS::MemoryMappedFile {
851 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000852 Win32MemoryMappedFile(HANDLE file,
853 HANDLE file_mapping,
854 void* memory,
855 int size)
856 : file_(file),
857 file_mapping_(file_mapping),
858 memory_(memory),
859 size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000860 virtual ~Win32MemoryMappedFile();
861 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000862 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 private:
864 HANDLE file_;
865 HANDLE file_mapping_;
866 void* memory_;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000867 int size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000868};
869
870
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000871OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
872 // Open a physical file
873 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
874 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000875 if (file == INVALID_HANDLE_VALUE) return NULL;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000876
877 int size = static_cast<int>(GetFileSize(file, NULL));
878
879 // Create a file mapping for the physical file
880 HANDLE file_mapping = CreateFileMapping(file, NULL,
881 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
882 if (file_mapping == NULL) return NULL;
883
884 // Map a view of the file into memory
885 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
886 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
887}
888
889
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000890OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
891 void* initial) {
892 // Open a physical file
893 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
894 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
895 if (file == NULL) return NULL;
896 // Create a file mapping for the physical file
897 HANDLE file_mapping = CreateFileMapping(file, NULL,
898 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
899 if (file_mapping == NULL) return NULL;
900 // Map a view of the file into memory
901 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
yangguo@chromium.org5de00742014-07-01 11:58:10 +0000902 if (memory) memmove(memory, initial, size);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000903 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000904}
905
906
907Win32MemoryMappedFile::~Win32MemoryMappedFile() {
908 if (memory_ != NULL)
909 UnmapViewOfFile(memory_);
910 CloseHandle(file_mapping_);
911 CloseHandle(file_);
912}
913
914
915// The following code loads functions defined in DbhHelp.h and TlHelp32.h
ager@chromium.org32912102009-01-16 10:38:43 +0000916// dynamically. This is to avoid being depending on dbghelp.dll and
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000917// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
918// kernel32.dll at some point so loading functions defines in TlHelp32.h
919// dynamically might not be necessary any more - for some versions of Windows?).
920
921// Function pointers to functions dynamically loaded from dbghelp.dll.
922#define DBGHELP_FUNCTION_LIST(V) \
923 V(SymInitialize) \
924 V(SymGetOptions) \
925 V(SymSetOptions) \
926 V(SymGetSearchPath) \
927 V(SymLoadModule64) \
928 V(StackWalk64) \
929 V(SymGetSymFromAddr64) \
930 V(SymGetLineFromAddr64) \
931 V(SymFunctionTableAccess64) \
932 V(SymGetModuleBase64)
933
934// Function pointers to functions dynamically loaded from dbghelp.dll.
935#define TLHELP32_FUNCTION_LIST(V) \
936 V(CreateToolhelp32Snapshot) \
937 V(Module32FirstW) \
938 V(Module32NextW)
939
940// Define the decoration to use for the type and variable name used for
941// dynamically loaded DLL function..
942#define DLL_FUNC_TYPE(name) _##name##_
943#define DLL_FUNC_VAR(name) _##name
944
945// Define the type for each dynamically loaded DLL function. The function
946// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
947// from the Windows include files are redefined here to have the function
948// definitions to be as close to the ones in the original .h files as possible.
949#ifndef IN
950#define IN
951#endif
952#ifndef VOID
953#define VOID void
954#endif
955
iposva@chromium.org245aa852009-02-10 00:49:54 +0000956// DbgHelp isn't supported on MinGW yet
957#ifndef __MINGW32__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958// DbgHelp.h functions.
959typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
960 IN PSTR UserSearchPath,
961 IN BOOL fInvadeProcess);
962typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
963typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
964typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
965 IN HANDLE hProcess,
966 OUT PSTR SearchPath,
967 IN DWORD SearchPathLength);
968typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
969 IN HANDLE hProcess,
970 IN HANDLE hFile,
971 IN PSTR ImageName,
972 IN PSTR ModuleName,
973 IN DWORD64 BaseOfDll,
974 IN DWORD SizeOfDll);
975typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
976 DWORD MachineType,
977 HANDLE hProcess,
978 HANDLE hThread,
979 LPSTACKFRAME64 StackFrame,
980 PVOID ContextRecord,
981 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
982 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
983 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
984 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
985typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
986 IN HANDLE hProcess,
987 IN DWORD64 qwAddr,
988 OUT PDWORD64 pdwDisplacement,
989 OUT PIMAGEHLP_SYMBOL64 Symbol);
990typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
991 IN HANDLE hProcess,
992 IN DWORD64 qwAddr,
993 OUT PDWORD pdwDisplacement,
994 OUT PIMAGEHLP_LINE64 Line64);
995// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
996typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
997 HANDLE hProcess,
998 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
999typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1000 HANDLE hProcess,
1001 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1002
1003// TlHelp32.h functions.
1004typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1005 DWORD dwFlags,
1006 DWORD th32ProcessID);
1007typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1008 LPMODULEENTRY32W lpme);
1009typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1010 LPMODULEENTRY32W lpme);
1011
1012#undef IN
1013#undef VOID
1014
1015// Declare a variable for each dynamically loaded DLL function.
1016#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1017DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1018TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1019#undef DEF_DLL_FUNCTION
1020
1021// Load the functions. This function has a lot of "ugly" macros in order to
1022// keep down code duplication.
1023
1024static bool LoadDbgHelpAndTlHelp32() {
1025 static bool dbghelp_loaded = false;
1026
1027 if (dbghelp_loaded) return true;
1028
1029 HMODULE module;
1030
1031 // Load functions from the dbghelp.dll module.
1032 module = LoadLibrary(TEXT("dbghelp.dll"));
1033 if (module == NULL) {
1034 return false;
1035 }
1036
1037#define LOAD_DLL_FUNC(name) \
1038 DLL_FUNC_VAR(name) = \
1039 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1040
1041DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1042
1043#undef LOAD_DLL_FUNC
1044
1045 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1046 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1047 module = LoadLibrary(TEXT("kernel32.dll"));
1048 if (module == NULL) {
1049 return false;
1050 }
1051
1052#define LOAD_DLL_FUNC(name) \
1053 DLL_FUNC_VAR(name) = \
1054 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1055
1056TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1057
1058#undef LOAD_DLL_FUNC
1059
1060 // Check that all functions where loaded.
1061 bool result =
1062#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1063
1064DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1065TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1066
1067#undef DLL_FUNC_LOADED
1068 true;
1069
1070 dbghelp_loaded = result;
1071 return result;
ager@chromium.org32912102009-01-16 10:38:43 +00001072 // NOTE: The modules are never unloaded and will stay around until the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001073 // application is closed.
1074}
1075
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00001076#undef DBGHELP_FUNCTION_LIST
1077#undef TLHELP32_FUNCTION_LIST
1078#undef DLL_FUNC_VAR
1079#undef DLL_FUNC_TYPE
1080
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001081
1082// Load the symbols for generating stack traces.
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001083static std::vector<OS::SharedLibraryAddress> LoadSymbols(
1084 HANDLE process_handle) {
1085 static std::vector<OS::SharedLibraryAddress> result;
1086
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001087 static bool symbols_loaded = false;
1088
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001089 if (symbols_loaded) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001090
1091 BOOL ok;
1092
1093 // Initialize the symbol engine.
1094 ok = _SymInitialize(process_handle, // hProcess
1095 NULL, // UserSearchPath
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001096 false); // fInvadeProcess
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001097 if (!ok) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001098
1099 DWORD options = _SymGetOptions();
1100 options |= SYMOPT_LOAD_LINES;
1101 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1102 options = _SymSetOptions(options);
1103
1104 char buf[OS::kStackWalkMaxNameLen] = {0};
1105 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1106 if (!ok) {
1107 int err = GetLastError();
yangguo@chromium.org5de00742014-07-01 11:58:10 +00001108 OS::Print("%d\n", err);
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001109 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001110 }
1111
1112 HANDLE snapshot = _CreateToolhelp32Snapshot(
1113 TH32CS_SNAPMODULE, // dwFlags
1114 GetCurrentProcessId()); // th32ProcessId
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001115 if (snapshot == INVALID_HANDLE_VALUE) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001116 MODULEENTRY32W module_entry;
1117 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1118 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1119 while (cont) {
1120 DWORD64 base;
1121 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1122 // both unicode and ASCII strings even though the parameter is PSTR.
1123 base = _SymLoadModule64(
1124 process_handle, // hProcess
1125 0, // hFile
1126 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1127 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1128 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1129 module_entry.modBaseSize); // SizeOfDll
1130 if (base == 0) {
1131 int err = GetLastError();
1132 if (err != ERROR_MOD_NOT_FOUND &&
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001133 err != ERROR_INVALID_HANDLE) {
1134 result.clear();
1135 return result;
1136 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001137 }
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001138 int lib_name_length = WideCharToMultiByte(
1139 CP_UTF8, 0, module_entry.szExePath, -1, NULL, 0, NULL, NULL);
1140 std::string lib_name(lib_name_length, 0);
1141 WideCharToMultiByte(CP_UTF8, 0, module_entry.szExePath, -1, &lib_name[0],
1142 lib_name_length, NULL, NULL);
1143 result.push_back(OS::SharedLibraryAddress(
1144 lib_name, reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1145 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1146 module_entry.modBaseSize)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001147 cont = _Module32NextW(snapshot, &module_entry);
1148 }
1149 CloseHandle(snapshot);
1150
1151 symbols_loaded = true;
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001152 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001153}
1154
1155
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001156std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001157 // SharedLibraryEvents are logged when loading symbol information.
1158 // Only the shared libraries loaded at the time of the call to
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001159 // GetSharedLibraryAddresses are logged. DLLs loaded after
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001160 // initialization are not accounted for.
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001161 if (!LoadDbgHelpAndTlHelp32()) return std::vector<OS::SharedLibraryAddress>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001162 HANDLE process_handle = GetCurrentProcess();
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001163 return LoadSymbols(process_handle);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001164}
1165
1166
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00001167void OS::SignalCodeMovingGC() {
1168}
1169
1170
machenbach@chromium.orgcfdf67d2013-09-27 07:27:26 +00001171uint64_t OS::TotalPhysicalMemory() {
1172 MEMORYSTATUSEX memory_info;
1173 memory_info.dwLength = sizeof(memory_info);
1174 if (!GlobalMemoryStatusEx(&memory_info)) {
1175 UNREACHABLE();
1176 return 0;
1177 }
1178
1179 return static_cast<uint64_t>(memory_info.ullTotalPhys);
1180}
1181
1182
iposva@chromium.org245aa852009-02-10 00:49:54 +00001183#else // __MINGW32__
machenbach@chromium.org1845eb02014-06-13 00:05:05 +00001184std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
1185 return std::vector<OS::SharedLibraryAddress>();
1186}
1187
1188
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001189void OS::SignalCodeMovingGC() { }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001190#endif // __MINGW32__
1191
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001192
machenbach@chromium.org7e6132b2014-05-27 07:05:17 +00001193int OS::NumberOfProcessorsOnline() {
1194 SYSTEM_INFO info;
1195 GetSystemInfo(&info);
1196 return info.dwNumberOfProcessors;
1197}
1198
1199
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001200double OS::nan_value() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001201#ifdef _MSC_VER
yangguo@chromium.org5de00742014-07-01 11:58:10 +00001202 return std::numeric_limits<double>::quiet_NaN();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001203#else // _MSC_VER
1204 return NAN;
1205#endif // _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001206}
1207
ager@chromium.org236ad962008-09-25 09:45:57 +00001208
1209int OS::ActivationFrameAlignment() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001210#ifdef _WIN64
1211 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
mstarzinger@chromium.orge0e1b0d2013-07-08 08:38:06 +00001212#elif defined(__MINGW32__)
1213 // With gcc 4.4 the tree vectorization optimizer can generate code
1214 // that requires 16 byte alignment such as movdqa on x86.
1215 return 16;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001216#else
1217 return 8; // Floating-point math runs faster with 8-byte alignment.
1218#endif
ager@chromium.org236ad962008-09-25 09:45:57 +00001219}
1220
1221
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001222VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001223
1224
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001225VirtualMemory::VirtualMemory(size_t size)
1226 : address_(ReserveRegion(size)), size_(size) { }
1227
1228
1229VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1230 : address_(NULL), size_(0) {
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001231 DCHECK(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001232 size_t request_size = RoundUp(size + alignment,
1233 static_cast<intptr_t>(OS::AllocateAlignment()));
1234 void* address = ReserveRegion(request_size);
1235 if (address == NULL) return;
machenbach@chromium.org248dd432014-06-30 00:04:54 +00001236 uint8_t* base = RoundUp(static_cast<uint8_t*>(address), alignment);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001237 // Try reducing the size by freeing and then reallocating a specific area.
1238 bool result = ReleaseRegion(address, request_size);
1239 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001240 DCHECK(result);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001241 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1242 if (address != NULL) {
1243 request_size = size;
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001244 DCHECK(base == static_cast<uint8_t*>(address));
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001245 } else {
1246 // Resizing failed, just go with a bigger area.
1247 address = ReserveRegion(request_size);
1248 if (address == NULL) return;
1249 }
1250 address_ = address;
1251 size_ = request_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001252}
1253
1254
1255VirtualMemory::~VirtualMemory() {
1256 if (IsReserved()) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001257 bool result = ReleaseRegion(address(), size());
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001258 DCHECK(result);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001259 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001260 }
1261}
1262
1263
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001264bool VirtualMemory::IsReserved() {
1265 return address_ != NULL;
1266}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001267
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001268
1269void VirtualMemory::Reset() {
1270 address_ = NULL;
1271 size_ = 0;
1272}
1273
1274
1275bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001276 return CommitRegion(address, size, is_executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001277}
1278
1279
1280bool VirtualMemory::Uncommit(void* address, size_t size) {
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001281 DCHECK(IsReserved());
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001282 return UncommitRegion(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001283}
1284
1285
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001286bool VirtualMemory::Guard(void* address) {
1287 if (NULL == VirtualAlloc(address,
1288 OS::CommitPageSize(),
1289 MEM_COMMIT,
hpayer@chromium.orgc5d49712013-09-11 08:25:48 +00001290 PAGE_NOACCESS)) {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001291 return false;
1292 }
1293 return true;
1294}
1295
1296
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001297void* VirtualMemory::ReserveRegion(size_t size) {
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +00001298 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001299}
1300
1301
1302bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1303 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1304 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1305 return false;
1306 }
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001307 return true;
1308}
1309
1310
1311bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1312 return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1313}
1314
1315
1316bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1317 return VirtualFree(base, 0, MEM_RELEASE) != 0;
1318}
1319
1320
danno@chromium.org72204d52012-10-31 10:02:10 +00001321bool VirtualMemory::HasLazyCommits() {
1322 // TODO(alph): implement for the platform.
1323 return false;
1324}
1325
1326
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001327// ----------------------------------------------------------------------------
1328// Win32 thread support.
1329
1330// Definition of invalid thread handle and id.
1331static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001332
1333// Entry point for threads. The supplied argument is a pointer to the thread
1334// object. The entry function dispatches to the run method in the thread
1335// object. It is important that this function has __stdcall calling
1336// convention.
1337static unsigned int __stdcall ThreadEntry(void* arg) {
1338 Thread* thread = reinterpret_cast<Thread*>(arg);
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001339 thread->NotifyStartedAndRun();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001340 return 0;
1341}
1342
1343
machenbach@chromium.org248dd432014-06-30 00:04:54 +00001344class Thread::PlatformData {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001345 public:
1346 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1347 HANDLE thread_;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001348 unsigned thread_id_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001349};
1350
1351
1352// Initialize a Win32 thread object. The thread has an invalid thread
1353// handle until it is started.
1354
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001355Thread::Thread(const Options& options)
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00001356 : stack_size_(options.stack_size()),
1357 start_semaphore_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001358 data_ = new PlatformData(kNoThread);
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00001359 set_name(options.name());
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001360}
1361
1362
1363void Thread::set_name(const char* name) {
bmeurer@chromium.org70ec1a22014-06-16 11:20:10 +00001364 OS::StrNCpy(name_, sizeof(name_), name, strlen(name));
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001365 name_[sizeof(name_) - 1] = '\0';
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001366}
1367
1368
1369// Close our own handle for the thread.
1370Thread::~Thread() {
1371 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1372 delete data_;
1373}
1374
1375
1376// Create a new thread. It is important to use _beginthreadex() instead of
1377// the Win32 function CreateThread(), because the CreateThread() does not
1378// initialize thread specific structures in the C runtime library.
1379void Thread::Start() {
1380 data_->thread_ = reinterpret_cast<HANDLE>(
1381 _beginthreadex(NULL,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001382 static_cast<unsigned>(stack_size_),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001383 ThreadEntry,
1384 this,
1385 0,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001386 &data_->thread_id_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001387}
1388
1389
1390// Wait for thread to terminate.
1391void Thread::Join() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001392 if (data_->thread_id_ != GetCurrentThreadId()) {
1393 WaitForSingleObject(data_->thread_, INFINITE);
1394 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001395}
1396
1397
1398Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1399 DWORD result = TlsAlloc();
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001400 DCHECK(result != TLS_OUT_OF_INDEXES);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001401 return static_cast<LocalStorageKey>(result);
1402}
1403
1404
1405void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1406 BOOL result = TlsFree(static_cast<DWORD>(key));
1407 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001408 DCHECK(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409}
1410
1411
1412void* Thread::GetThreadLocal(LocalStorageKey key) {
1413 return TlsGetValue(static_cast<DWORD>(key));
1414}
1415
1416
1417void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1418 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1419 USE(result);
machenbach@chromium.orge3c177a2014-08-05 00:05:55 +00001420 DCHECK(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421}
1422
1423
1424
1425void Thread::YieldCPU() {
1426 Sleep(0);
1427}
1428
yangguo@chromium.org5de00742014-07-01 11:58:10 +00001429} } // namespace v8::base