1// Copyright 2012 the V8 project authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5// Platform-specific code for Win32. 6 7// 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 18#include <limits> 19 20#include "src/base/win32-headers.h" 21 22#include "src/base/bits.h" 23#include "src/base/lazy-instance.h" 24#include "src/base/macros.h" 25#include "src/base/platform/platform.h" 26#include "src/base/platform/time.h" 27#include "src/base/utils/random-number-generator.h" 28 29 30// Extra functions for MinGW. Most of these are the _s functions which are in 31// the Microsoft Visual Studio C++ CRT. 32#ifdef __MINGW32__ 33 34 35#ifndef __MINGW64_VERSION_MAJOR 36 37#define _TRUNCATE 0 38#define STRUNCATE 80 39 40inline void MemoryBarrier() { 41 int barrier = 0; 42 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier)); 43} 44 45#endif // __MINGW64_VERSION_MAJOR 46 47 48int localtime_s(tm* out_tm, const time_t* time) { 49 tm* posix_local_time_struct = localtime_r(time, out_tm); 50 if (posix_local_time_struct == NULL) return 1; 51 return 0; 52} 53 54 55int fopen_s(FILE** pFile, const char* filename, const char* mode) { 56 *pFile = fopen(filename, mode); 57 return *pFile != NULL ? 0 : 1; 58} 59 60int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count, 61 const char* format, va_list argptr) { 62 DCHECK(count == _TRUNCATE); 63 return _vsnprintf(buffer, sizeOfBuffer, format, argptr); 64} 65 66 67int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) { 68 CHECK(source != NULL); 69 CHECK(dest != NULL); 70 CHECK_GT(dest_size, 0); 71 72 if (count == _TRUNCATE) { 73 while (dest_size > 0 && *source != 0) { 74 *(dest++) = *(source++); 75 --dest_size; 76 } 77 if (dest_size == 0) { 78 *(dest - 1) = 0; 79 return STRUNCATE; 80 } 81 } else { 82 while (dest_size > 0 && count > 0 && *source != 0) { 83 *(dest++) = *(source++); 84 --dest_size; 85 --count; 86 } 87 } 88 CHECK_GT(dest_size, 0); 89 *dest = 0; 90 return 0; 91} 92 93#endif // __MINGW32__ 94 95namespace v8 { 96namespace base { 97 98namespace { 99 100bool g_hard_abort = false; 101 102} // namespace 103 104class TimezoneCache { 105 public: 106 TimezoneCache() : initialized_(false) { } 107 108 void Clear() { 109 initialized_ = false; 110 } 111 112 // Initialize timezone information. The timezone information is obtained from 113 // windows. If we cannot get the timezone information we fall back to CET. 114 void InitializeIfNeeded() { 115 // Just return if timezone information has already been initialized. 116 if (initialized_) return; 117 118 // Initialize POSIX time zone data. 119 _tzset(); 120 // Obtain timezone information from operating system. 121 memset(&tzinfo_, 0, sizeof(tzinfo_)); 122 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) { 123 // If we cannot get timezone information we fall back to CET. 124 tzinfo_.Bias = -60; 125 tzinfo_.StandardDate.wMonth = 10; 126 tzinfo_.StandardDate.wDay = 5; 127 tzinfo_.StandardDate.wHour = 3; 128 tzinfo_.StandardBias = 0; 129 tzinfo_.DaylightDate.wMonth = 3; 130 tzinfo_.DaylightDate.wDay = 5; 131 tzinfo_.DaylightDate.wHour = 2; 132 tzinfo_.DaylightBias = -60; 133 } 134 135 // Make standard and DST timezone names. 136 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1, 137 std_tz_name_, kTzNameSize, NULL, NULL); 138 std_tz_name_[kTzNameSize - 1] = '\0'; 139 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1, 140 dst_tz_name_, kTzNameSize, NULL, NULL); 141 dst_tz_name_[kTzNameSize - 1] = '\0'; 142 143 // If OS returned empty string or resource id (like "@tzres.dll,-211") 144 // simply guess the name from the UTC bias of the timezone. 145 // To properly resolve the resource identifier requires a library load, 146 // which is not possible in a sandbox. 147 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') { 148 OS::SNPrintF(std_tz_name_, kTzNameSize - 1, 149 "%s Standard Time", 150 GuessTimezoneNameFromBias(tzinfo_.Bias)); 151 } 152 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') { 153 OS::SNPrintF(dst_tz_name_, kTzNameSize - 1, 154 "%s Daylight Time", 155 GuessTimezoneNameFromBias(tzinfo_.Bias)); 156 } 157 // Timezone information initialized. 158 initialized_ = true; 159 } 160 161 // Guess the name of the timezone from the bias. 162 // The guess is very biased towards the northern hemisphere. 163 const char* GuessTimezoneNameFromBias(int bias) { 164 static const int kHour = 60; 165 switch (-bias) { 166 case -9*kHour: return "Alaska"; 167 case -8*kHour: return "Pacific"; 168 case -7*kHour: return "Mountain"; 169 case -6*kHour: return "Central"; 170 case -5*kHour: return "Eastern"; 171 case -4*kHour: return "Atlantic"; 172 case 0*kHour: return "GMT"; 173 case +1*kHour: return "Central Europe"; 174 case +2*kHour: return "Eastern Europe"; 175 case +3*kHour: return "Russia"; 176 case +5*kHour + 30: return "India"; 177 case +8*kHour: return "China"; 178 case +9*kHour: return "Japan"; 179 case +12*kHour: return "New Zealand"; 180 default: return "Local"; 181 } 182 } 183 184 185 private: 186 static const int kTzNameSize = 128; 187 bool initialized_; 188 char std_tz_name_[kTzNameSize]; 189 char dst_tz_name_[kTzNameSize]; 190 TIME_ZONE_INFORMATION tzinfo_; 191 friend class Win32Time; 192}; 193 194 195// ---------------------------------------------------------------------------- 196// The Time class represents time on win32. A timestamp is represented as 197// a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript 198// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC, 199// January 1, 1970. 200 201class Win32Time { 202 public: 203 // Constructors. 204 Win32Time(); 205 explicit Win32Time(double jstime); 206 Win32Time(int year, int mon, int day, int hour, int min, int sec); 207 208 // Convert timestamp to JavaScript representation. 209 double ToJSTime(); 210 211 // Set timestamp to current time. 212 void SetToCurrentTime(); 213 214 // Returns the local timezone offset in milliseconds east of UTC. This is 215 // the number of milliseconds you must add to UTC to get local time, i.e. 216 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This 217 // routine also takes into account whether daylight saving is effect 218 // at the time. 219 int64_t LocalOffset(TimezoneCache* cache); 220 221 // Returns the daylight savings time offset for the time in milliseconds. 222 int64_t DaylightSavingsOffset(TimezoneCache* cache); 223 224 // Returns a string identifying the current timezone for the 225 // timestamp taking into account daylight saving. 226 char* LocalTimezone(TimezoneCache* cache); 227 228 private: 229 // Constants for time conversion. 230 static const int64_t kTimeEpoc = 116444736000000000LL; 231 static const int64_t kTimeScaler = 10000; 232 static const int64_t kMsPerMinute = 60000; 233 234 // Constants for timezone information. 235 static const bool kShortTzNames = false; 236 237 // Return whether or not daylight savings time is in effect at this time. 238 bool InDST(TimezoneCache* cache); 239 240 // Accessor for FILETIME representation. 241 FILETIME& ft() { return time_.ft_; } 242 243 // Accessor for integer representation. 244 int64_t& t() { return time_.t_; } 245 246 // Although win32 uses 64-bit integers for representing timestamps, 247 // these are packed into a FILETIME structure. The FILETIME structure 248 // is just a struct representing a 64-bit integer. The TimeStamp union 249 // allows access to both a FILETIME and an integer representation of 250 // the timestamp. 251 union TimeStamp { 252 FILETIME ft_; 253 int64_t t_; 254 }; 255 256 TimeStamp time_; 257}; 258 259 260// Initialize timestamp to start of epoc. 261Win32Time::Win32Time() { 262 t() = 0; 263} 264 265 266// Initialize timestamp from a JavaScript timestamp. 267Win32Time::Win32Time(double jstime) { 268 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc; 269} 270 271 272// Initialize timestamp from date/time components. 273Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) { 274 SYSTEMTIME st; 275 st.wYear = year; 276 st.wMonth = mon; 277 st.wDay = day; 278 st.wHour = hour; 279 st.wMinute = min; 280 st.wSecond = sec; 281 st.wMilliseconds = 0; 282 SystemTimeToFileTime(&st, &ft()); 283} 284 285 286// Convert timestamp to JavaScript timestamp. 287double Win32Time::ToJSTime() { 288 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler); 289} 290 291 292// Set timestamp to current time. 293void Win32Time::SetToCurrentTime() { 294 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution. 295 // Because we're fast, we like fast timers which have at least a 296 // 1ms resolution. 297 // 298 // timeGetTime() provides 1ms granularity when combined with 299 // timeBeginPeriod(). If the host application for v8 wants fast 300 // timers, it can use timeBeginPeriod to increase the resolution. 301 // 302 // Using timeGetTime() has a drawback because it is a 32bit value 303 // and hence rolls-over every ~49days. 304 // 305 // To use the clock, we use GetSystemTimeAsFileTime as our base; 306 // and then use timeGetTime to extrapolate current time from the 307 // start time. To deal with rollovers, we resync the clock 308 // any time when more than kMaxClockElapsedTime has passed or 309 // whenever timeGetTime creates a rollover. 310 311 static bool initialized = false; 312 static TimeStamp init_time; 313 static DWORD init_ticks; 314 static const int64_t kHundredNanosecondsPerSecond = 10000000; 315 static const int64_t kMaxClockElapsedTime = 316 60*kHundredNanosecondsPerSecond; // 1 minute 317 318 // If we are uninitialized, we need to resync the clock. 319 bool needs_resync = !initialized; 320 321 // Get the current time. 322 TimeStamp time_now; 323 GetSystemTimeAsFileTime(&time_now.ft_); 324 DWORD ticks_now = timeGetTime(); 325 326 // Check if we need to resync due to clock rollover. 327 needs_resync |= ticks_now < init_ticks; 328 329 // Check if we need to resync due to elapsed time. 330 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime; 331 332 // Check if we need to resync due to backwards time change. 333 needs_resync |= time_now.t_ < init_time.t_; 334 335 // Resync the clock if necessary. 336 if (needs_resync) { 337 GetSystemTimeAsFileTime(&init_time.ft_); 338 init_ticks = ticks_now = timeGetTime(); 339 initialized = true; 340 } 341 342 // Finally, compute the actual time. Why is this so hard. 343 DWORD elapsed = ticks_now - init_ticks; 344 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000); 345} 346 347 348// Return the local timezone offset in milliseconds east of UTC. This 349// takes into account whether daylight saving is in effect at the time. 350// Only times in the 32-bit Unix range may be passed to this function. 351// Also, adding the time-zone offset to the input must not overflow. 352// The function EquivalentTime() in date.js guarantees this. 353int64_t Win32Time::LocalOffset(TimezoneCache* cache) { 354 cache->InitializeIfNeeded(); 355 356 Win32Time rounded_to_second(*this); 357 rounded_to_second.t() = 358 rounded_to_second.t() / 1000 / kTimeScaler * 1000 * kTimeScaler; 359 // Convert to local time using POSIX localtime function. 360 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime() 361 // very slow. Other browsers use localtime(). 362 363 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to 364 // POSIX seconds past 1/1/1970 0:00:00. 365 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000; 366 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) { 367 return 0; 368 } 369 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int. 370 time_t posix_time = static_cast<time_t>(unchecked_posix_time); 371 372 // Convert to local time, as struct with fields for day, hour, year, etc. 373 tm posix_local_time_struct; 374 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0; 375 376 if (posix_local_time_struct.tm_isdst > 0) { 377 return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute; 378 } else if (posix_local_time_struct.tm_isdst == 0) { 379 return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute; 380 } else { 381 return cache->tzinfo_.Bias * -kMsPerMinute; 382 } 383} 384 385 386// Return whether or not daylight savings time is in effect at this time. 387bool Win32Time::InDST(TimezoneCache* cache) { 388 cache->InitializeIfNeeded(); 389 390 // Determine if DST is in effect at the specified time. 391 bool in_dst = false; 392 if (cache->tzinfo_.StandardDate.wMonth != 0 || 393 cache->tzinfo_.DaylightDate.wMonth != 0) { 394 // Get the local timezone offset for the timestamp in milliseconds. 395 int64_t offset = LocalOffset(cache); 396 397 // Compute the offset for DST. The bias parameters in the timezone info 398 // are specified in minutes. These must be converted to milliseconds. 399 int64_t dstofs = 400 -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute; 401 402 // If the local time offset equals the timezone bias plus the daylight 403 // bias then DST is in effect. 404 in_dst = offset == dstofs; 405 } 406 407 return in_dst; 408} 409 410 411// Return the daylight savings time offset for this time. 412int64_t Win32Time::DaylightSavingsOffset(TimezoneCache* cache) { 413 return InDST(cache) ? 60 * kMsPerMinute : 0; 414} 415 416 417// Returns a string identifying the current timezone for the 418// timestamp taking into account daylight saving. 419char* Win32Time::LocalTimezone(TimezoneCache* cache) { 420 // Return the standard or DST time zone name based on whether daylight 421 // saving is in effect at the given time. 422 return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_; 423} 424 425 426// Returns the accumulated user time for thread. 427int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) { 428 FILETIME dummy; 429 uint64_t usertime; 430 431 // Get the amount of time that the thread has executed in user mode. 432 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy, 433 reinterpret_cast<FILETIME*>(&usertime))) return -1; 434 435 // Adjust the resolution to micro-seconds. 436 usertime /= 10; 437 438 // Convert to seconds and microseconds 439 *secs = static_cast<uint32_t>(usertime / 1000000); 440 *usecs = static_cast<uint32_t>(usertime % 1000000); 441 return 0; 442} 443 444 445// Returns current time as the number of milliseconds since 446// 00:00:00 UTC, January 1, 1970. 447double OS::TimeCurrentMillis() { 448 return Time::Now().ToJsTime(); 449} 450 451 452TimezoneCache* OS::CreateTimezoneCache() { 453 return new TimezoneCache(); 454} 455 456 457void OS::DisposeTimezoneCache(TimezoneCache* cache) { 458 delete cache; 459} 460 461 462void OS::ClearTimezoneCache(TimezoneCache* cache) { 463 cache->Clear(); 464} 465 466 467// Returns a string identifying the current timezone taking into 468// account daylight saving. 469const char* OS::LocalTimezone(double time, TimezoneCache* cache) { 470 return Win32Time(time).LocalTimezone(cache); 471} 472 473 474// Returns the local time offset in milliseconds east of UTC without 475// taking daylight savings time into account. 476double OS::LocalTimeOffset(TimezoneCache* cache) { 477 // Use current time, rounded to the millisecond. 478 Win32Time t(TimeCurrentMillis()); 479 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it. 480 return static_cast<double>(t.LocalOffset(cache) - 481 t.DaylightSavingsOffset(cache)); 482} 483 484 485// Returns the daylight savings offset in milliseconds for the given 486// time. 487double OS::DaylightSavingsOffset(double time, TimezoneCache* cache) { 488 int64_t offset = Win32Time(time).DaylightSavingsOffset(cache); 489 return static_cast<double>(offset); 490} 491 492 493int OS::GetLastError() { 494 return ::GetLastError(); 495} 496 497 498int OS::GetCurrentProcessId() { 499 return static_cast<int>(::GetCurrentProcessId()); 500} 501 502 503int OS::GetCurrentThreadId() { 504 return static_cast<int>(::GetCurrentThreadId()); 505} 506 507 508// ---------------------------------------------------------------------------- 509// Win32 console output. 510// 511// If a Win32 application is linked as a console application it has a normal 512// standard output and standard error. In this case normal printf works fine 513// for output. However, if the application is linked as a GUI application, 514// the process doesn't have a console, and therefore (debugging) output is lost. 515// This is the case if we are embedded in a windows program (like a browser). 516// In order to be able to get debug output in this case the the debugging 517// facility using OutputDebugString. This output goes to the active debugger 518// for the process (if any). Else the output can be monitored using DBMON.EXE. 519 520enum OutputMode { 521 UNKNOWN, // Output method has not yet been determined. 522 CONSOLE, // Output is written to stdout. 523 ODS // Output is written to debug facility. 524}; 525 526static OutputMode output_mode = UNKNOWN; // Current output mode. 527 528 529// Determine if the process has a console for output. 530static bool HasConsole() { 531 // Only check the first time. Eventual race conditions are not a problem, 532 // because all threads will eventually determine the same mode. 533 if (output_mode == UNKNOWN) { 534 // We cannot just check that the standard output is attached to a console 535 // because this would fail if output is redirected to a file. Therefore we 536 // say that a process does not have an output console if either the 537 // standard output handle is invalid or its file type is unknown. 538 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE && 539 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN) 540 output_mode = CONSOLE; 541 else 542 output_mode = ODS; 543 } 544 return output_mode == CONSOLE; 545} 546 547 548static void VPrintHelper(FILE* stream, const char* format, va_list args) { 549 if ((stream == stdout || stream == stderr) && !HasConsole()) { 550 // It is important to use safe print here in order to avoid 551 // overflowing the buffer. We might truncate the output, but this 552 // does not crash. 553 char buffer[4096]; 554 OS::VSNPrintF(buffer, sizeof(buffer), format, args); 555 OutputDebugStringA(buffer); 556 } else { 557 vfprintf(stream, format, args); 558 } 559} 560 561 562FILE* OS::FOpen(const char* path, const char* mode) { 563 FILE* result; 564 if (fopen_s(&result, path, mode) == 0) { 565 return result; 566 } else { 567 return NULL; 568 } 569} 570 571 572bool OS::Remove(const char* path) { 573 return (DeleteFileA(path) != 0); 574} 575 576char OS::DirectorySeparator() { return '\\'; } 577 578bool OS::isDirectorySeparator(const char ch) { 579 return ch == '/' || ch == '\\'; 580} 581 582 583FILE* OS::OpenTemporaryFile() { 584 // tmpfile_s tries to use the root dir, don't use it. 585 char tempPathBuffer[MAX_PATH]; 586 DWORD path_result = 0; 587 path_result = GetTempPathA(MAX_PATH, tempPathBuffer); 588 if (path_result > MAX_PATH || path_result == 0) return NULL; 589 UINT name_result = 0; 590 char tempNameBuffer[MAX_PATH]; 591 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer); 592 if (name_result == 0) return NULL; 593 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses. 594 if (result != NULL) { 595 Remove(tempNameBuffer); // Delete on close. 596 } 597 return result; 598} 599 600 601// Open log file in binary mode to avoid /n -> /r/n conversion. 602const char* const OS::LogFileOpenMode = "wb"; 603 604 605// Print (debug) message to console. 606void OS::Print(const char* format, ...) { 607 va_list args; 608 va_start(args, format); 609 VPrint(format, args); 610 va_end(args); 611} 612 613 614void OS::VPrint(const char* format, va_list args) { 615 VPrintHelper(stdout, format, args); 616} 617 618 619void OS::FPrint(FILE* out, const char* format, ...) { 620 va_list args; 621 va_start(args, format); 622 VFPrint(out, format, args); 623 va_end(args); 624} 625 626 627void OS::VFPrint(FILE* out, const char* format, va_list args) { 628 VPrintHelper(out, format, args); 629} 630 631 632// Print error message to console. 633void OS::PrintError(const char* format, ...) { 634 va_list args; 635 va_start(args, format); 636 VPrintError(format, args); 637 va_end(args); 638} 639 640 641void OS::VPrintError(const char* format, va_list args) { 642 VPrintHelper(stderr, format, args); 643} 644 645 646int OS::SNPrintF(char* str, int length, const char* format, ...) { 647 va_list args; 648 va_start(args, format); 649 int result = VSNPrintF(str, length, format, args); 650 va_end(args); 651 return result; 652} 653 654 655int OS::VSNPrintF(char* str, int length, const char* format, va_list args) { 656 int n = _vsnprintf_s(str, length, _TRUNCATE, format, args); 657 // Make sure to zero-terminate the string if the output was 658 // truncated or if there was an error. 659 if (n < 0 || n >= length) { 660 if (length > 0) 661 str[length - 1] = '\0'; 662 return -1; 663 } else { 664 return n; 665 } 666} 667 668 669char* OS::StrChr(char* str, int c) { 670 return const_cast<char*>(strchr(str, c)); 671} 672 673 674void OS::StrNCpy(char* dest, int length, const char* src, size_t n) { 675 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small. 676 size_t buffer_size = static_cast<size_t>(length); 677 if (n + 1 > buffer_size) // count for trailing '\0' 678 n = _TRUNCATE; 679 int result = strncpy_s(dest, length, src, n); 680 USE(result); 681 DCHECK(result == 0 || (n == _TRUNCATE && result == STRUNCATE)); 682} 683 684 685#undef _TRUNCATE 686#undef STRUNCATE 687 688 689// Get the system's page size used by VirtualAlloc() or the next power 690// of two. The reason for always returning a power of two is that the 691// rounding up in OS::Allocate expects that. 692static size_t GetPageSize() { 693 static size_t page_size = 0; 694 if (page_size == 0) { 695 SYSTEM_INFO info; 696 GetSystemInfo(&info); 697 page_size = base::bits::RoundUpToPowerOfTwo32(info.dwPageSize); 698 } 699 return page_size; 700} 701 702 703// The allocation alignment is the guaranteed alignment for 704// VirtualAlloc'ed blocks of memory. 705size_t OS::AllocateAlignment() { 706 static size_t allocate_alignment = 0; 707 if (allocate_alignment == 0) { 708 SYSTEM_INFO info; 709 GetSystemInfo(&info); 710 allocate_alignment = info.dwAllocationGranularity; 711 } 712 return allocate_alignment; 713} 714 715 716static LazyInstance<RandomNumberGenerator>::type 717 platform_random_number_generator = LAZY_INSTANCE_INITIALIZER; 718 719 720void OS::Initialize(int64_t random_seed, bool hard_abort, 721 const char* const gc_fake_mmap) { 722 if (random_seed) { 723 platform_random_number_generator.Pointer()->SetSeed(random_seed); 724 } 725 g_hard_abort = hard_abort; 726} 727 728 729void* OS::GetRandomMmapAddr() { 730 // The address range used to randomize RWX allocations in OS::Allocate 731 // Try not to map pages into the default range that windows loads DLLs 732 // Use a multiple of 64k to prevent committing unused memory. 733 // Note: This does not guarantee RWX regions will be within the 734 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax 735#ifdef V8_HOST_ARCH_64_BIT 736 static const uintptr_t kAllocationRandomAddressMin = 0x0000000080000000; 737 static const uintptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000; 738#else 739 static const uintptr_t kAllocationRandomAddressMin = 0x04000000; 740 static const uintptr_t kAllocationRandomAddressMax = 0x3FFF0000; 741#endif 742 uintptr_t address; 743 platform_random_number_generator.Pointer()->NextBytes(&address, 744 sizeof(address)); 745 address <<= kPageSizeBits; 746 address += kAllocationRandomAddressMin; 747 address &= kAllocationRandomAddressMax; 748 return reinterpret_cast<void *>(address); 749} 750 751 752static void* RandomizedVirtualAlloc(size_t size, int action, int protection) { 753 LPVOID base = NULL; 754 static BOOL use_aslr = -1; 755#ifdef V8_HOST_ARCH_32_BIT 756 // Don't bother randomizing on 32-bit hosts, because they lack the room and 757 // don't have viable ASLR anyway. 758 if (use_aslr == -1 && !IsWow64Process(GetCurrentProcess(), &use_aslr)) 759 use_aslr = FALSE; 760#else 761 use_aslr = TRUE; 762#endif 763 764 if (use_aslr && 765 (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS)) { 766 // For executable pages try and randomize the allocation address 767 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) { 768 base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection); 769 } 770 } 771 772 // After three attempts give up and let the OS find an address to use. 773 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection); 774 775 return base; 776} 777 778 779void* OS::Allocate(const size_t requested, 780 size_t* allocated, 781 bool is_executable) { 782 // VirtualAlloc rounds allocated size to page size automatically. 783 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize())); 784 785 // Windows XP SP2 allows Data Excution Prevention (DEP). 786 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; 787 788 LPVOID mbase = RandomizedVirtualAlloc(msize, 789 MEM_COMMIT | MEM_RESERVE, 790 prot); 791 792 if (mbase == NULL) return NULL; 793 794 DCHECK((reinterpret_cast<uintptr_t>(mbase) % OS::AllocateAlignment()) == 0); 795 796 *allocated = msize; 797 return mbase; 798} 799 800void* OS::AllocateGuarded(const size_t requested) { 801 return VirtualAlloc(nullptr, requested, MEM_RESERVE, PAGE_NOACCESS); 802} 803 804void OS::Free(void* address, const size_t size) { 805 // TODO(1240712): VirtualFree has a return value which is ignored here. 806 VirtualFree(address, 0, MEM_RELEASE); 807 USE(size); 808} 809 810 811intptr_t OS::CommitPageSize() { 812 return 4096; 813} 814 815 816void OS::ProtectCode(void* address, const size_t size) { 817 DWORD old_protect; 818 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect); 819} 820 821 822void OS::Guard(void* address, const size_t size) { 823 DWORD oldprotect; 824 VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect); 825} 826 827void OS::Unprotect(void* address, const size_t size) { 828 LPVOID result = VirtualAlloc(address, size, MEM_COMMIT, PAGE_READWRITE); 829 DCHECK_IMPLIES(result != nullptr, GetLastError() == 0); 830} 831 832void OS::Sleep(TimeDelta interval) { 833 ::Sleep(static_cast<DWORD>(interval.InMilliseconds())); 834} 835 836 837void OS::Abort() { 838 if (g_hard_abort) { 839 V8_IMMEDIATE_CRASH(); 840 } 841 // Make the MSVCRT do a silent abort. 842 raise(SIGABRT); 843 844 // Make sure function doesn't return. 845 abort(); 846} 847 848 849void OS::DebugBreak() { 850#if V8_CC_MSVC 851 // To avoid Visual Studio runtime support the following code can be used 852 // instead 853 // __asm { int 3 } 854 __debugbreak(); 855#else 856 ::DebugBreak(); 857#endif 858} 859 860 861class Win32MemoryMappedFile final : public OS::MemoryMappedFile { 862 public: 863 Win32MemoryMappedFile(HANDLE file, HANDLE file_mapping, void* memory, 864 size_t size) 865 : file_(file), 866 file_mapping_(file_mapping), 867 memory_(memory), 868 size_(size) {} 869 ~Win32MemoryMappedFile() final; 870 void* memory() const final { return memory_; } 871 size_t size() const final { return size_; } 872 873 private: 874 HANDLE const file_; 875 HANDLE const file_mapping_; 876 void* const memory_; 877 size_t const size_; 878}; 879 880 881// static 882OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) { 883 // Open a physical file 884 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 885 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); 886 if (file == INVALID_HANDLE_VALUE) return NULL; 887 888 DWORD size = GetFileSize(file, NULL); 889 890 // Create a file mapping for the physical file 891 HANDLE file_mapping = 892 CreateFileMapping(file, NULL, PAGE_READWRITE, 0, size, NULL); 893 if (file_mapping == NULL) return NULL; 894 895 // Map a view of the file into memory 896 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size); 897 return new Win32MemoryMappedFile(file, file_mapping, memory, size); 898} 899 900 901// static 902OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, 903 size_t size, void* initial) { 904 // Open a physical file 905 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 906 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 907 OPEN_ALWAYS, 0, NULL); 908 if (file == NULL) return NULL; 909 // Create a file mapping for the physical file 910 HANDLE file_mapping = CreateFileMapping(file, NULL, PAGE_READWRITE, 0, 911 static_cast<DWORD>(size), NULL); 912 if (file_mapping == NULL) return NULL; 913 // Map a view of the file into memory 914 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size); 915 if (memory) memmove(memory, initial, size); 916 return new Win32MemoryMappedFile(file, file_mapping, memory, size); 917} 918 919 920Win32MemoryMappedFile::~Win32MemoryMappedFile() { 921 if (memory_) UnmapViewOfFile(memory_); 922 CloseHandle(file_mapping_); 923 CloseHandle(file_); 924} 925 926 927// The following code loads functions defined in DbhHelp.h and TlHelp32.h 928// dynamically. This is to avoid being depending on dbghelp.dll and 929// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to 930// kernel32.dll at some point so loading functions defines in TlHelp32.h 931// dynamically might not be necessary any more - for some versions of Windows?). 932 933// Function pointers to functions dynamically loaded from dbghelp.dll. 934#define DBGHELP_FUNCTION_LIST(V) \ 935 V(SymInitialize) \ 936 V(SymGetOptions) \ 937 V(SymSetOptions) \ 938 V(SymGetSearchPath) \ 939 V(SymLoadModule64) \ 940 V(StackWalk64) \ 941 V(SymGetSymFromAddr64) \ 942 V(SymGetLineFromAddr64) \ 943 V(SymFunctionTableAccess64) \ 944 V(SymGetModuleBase64) 945 946// Function pointers to functions dynamically loaded from dbghelp.dll. 947#define TLHELP32_FUNCTION_LIST(V) \ 948 V(CreateToolhelp32Snapshot) \ 949 V(Module32FirstW) \ 950 V(Module32NextW) 951 952// Define the decoration to use for the type and variable name used for 953// dynamically loaded DLL function.. 954#define DLL_FUNC_TYPE(name) _##name##_ 955#define DLL_FUNC_VAR(name) _##name 956 957// Define the type for each dynamically loaded DLL function. The function 958// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros 959// from the Windows include files are redefined here to have the function 960// definitions to be as close to the ones in the original .h files as possible. 961#ifndef IN 962#define IN 963#endif 964#ifndef VOID 965#define VOID void 966#endif 967 968// DbgHelp isn't supported on MinGW yet 969#ifndef __MINGW32__ 970// DbgHelp.h functions. 971typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess, 972 IN PSTR UserSearchPath, 973 IN BOOL fInvadeProcess); 974typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID); 975typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions); 976typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))( 977 IN HANDLE hProcess, 978 OUT PSTR SearchPath, 979 IN DWORD SearchPathLength); 980typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))( 981 IN HANDLE hProcess, 982 IN HANDLE hFile, 983 IN PSTR ImageName, 984 IN PSTR ModuleName, 985 IN DWORD64 BaseOfDll, 986 IN DWORD SizeOfDll); 987typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))( 988 DWORD MachineType, 989 HANDLE hProcess, 990 HANDLE hThread, 991 LPSTACKFRAME64 StackFrame, 992 PVOID ContextRecord, 993 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, 994 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, 995 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, 996 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); 997typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))( 998 IN HANDLE hProcess, 999 IN DWORD64 qwAddr, 1000 OUT PDWORD64 pdwDisplacement, 1001 OUT PIMAGEHLP_SYMBOL64 Symbol); 1002typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))( 1003 IN HANDLE hProcess, 1004 IN DWORD64 qwAddr, 1005 OUT PDWORD pdwDisplacement, 1006 OUT PIMAGEHLP_LINE64 Line64); 1007// DbgHelp.h typedefs. Implementation found in dbghelp.dll. 1008typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))( 1009 HANDLE hProcess, 1010 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64 1011typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))( 1012 HANDLE hProcess, 1013 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64 1014 1015// TlHelp32.h functions. 1016typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))( 1017 DWORD dwFlags, 1018 DWORD th32ProcessID); 1019typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot, 1020 LPMODULEENTRY32W lpme); 1021typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot, 1022 LPMODULEENTRY32W lpme); 1023 1024#undef IN 1025#undef VOID 1026 1027// Declare a variable for each dynamically loaded DLL function. 1028#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL; 1029DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION) 1030TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION) 1031#undef DEF_DLL_FUNCTION 1032 1033// Load the functions. This function has a lot of "ugly" macros in order to 1034// keep down code duplication. 1035 1036static bool LoadDbgHelpAndTlHelp32() { 1037 static bool dbghelp_loaded = false; 1038 1039 if (dbghelp_loaded) return true; 1040 1041 HMODULE module; 1042 1043 // Load functions from the dbghelp.dll module. 1044 module = LoadLibrary(TEXT("dbghelp.dll")); 1045 if (module == NULL) { 1046 return false; 1047 } 1048 1049#define LOAD_DLL_FUNC(name) \ 1050 DLL_FUNC_VAR(name) = \ 1051 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name)); 1052 1053DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC) 1054 1055#undef LOAD_DLL_FUNC 1056 1057 // Load functions from the kernel32.dll module (the TlHelp32.h function used 1058 // to be in tlhelp32.dll but are now moved to kernel32.dll). 1059 module = LoadLibrary(TEXT("kernel32.dll")); 1060 if (module == NULL) { 1061 return false; 1062 } 1063 1064#define LOAD_DLL_FUNC(name) \ 1065 DLL_FUNC_VAR(name) = \ 1066 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name)); 1067 1068TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC) 1069 1070#undef LOAD_DLL_FUNC 1071 1072 // Check that all functions where loaded. 1073 bool result = 1074#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) && 1075 1076DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED) 1077TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED) 1078 1079#undef DLL_FUNC_LOADED 1080 true; 1081 1082 dbghelp_loaded = result; 1083 return result; 1084 // NOTE: The modules are never unloaded and will stay around until the 1085 // application is closed. 1086} 1087 1088#undef DBGHELP_FUNCTION_LIST 1089#undef TLHELP32_FUNCTION_LIST 1090#undef DLL_FUNC_VAR 1091#undef DLL_FUNC_TYPE 1092 1093 1094// Load the symbols for generating stack traces. 1095static std::vector<OS::SharedLibraryAddress> LoadSymbols( 1096 HANDLE process_handle) { 1097 static std::vector<OS::SharedLibraryAddress> result; 1098 1099 static bool symbols_loaded = false; 1100 1101 if (symbols_loaded) return result; 1102 1103 BOOL ok; 1104 1105 // Initialize the symbol engine. 1106 ok = _SymInitialize(process_handle, // hProcess 1107 NULL, // UserSearchPath 1108 false); // fInvadeProcess 1109 if (!ok) return result; 1110 1111 DWORD options = _SymGetOptions(); 1112 options |= SYMOPT_LOAD_LINES; 1113 options |= SYMOPT_FAIL_CRITICAL_ERRORS; 1114 options = _SymSetOptions(options); 1115 1116 char buf[OS::kStackWalkMaxNameLen] = {0}; 1117 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen); 1118 if (!ok) { 1119 int err = GetLastError(); 1120 OS::Print("%d\n", err); 1121 return result; 1122 } 1123 1124 HANDLE snapshot = _CreateToolhelp32Snapshot( 1125 TH32CS_SNAPMODULE, // dwFlags 1126 GetCurrentProcessId()); // th32ProcessId 1127 if (snapshot == INVALID_HANDLE_VALUE) return result; 1128 MODULEENTRY32W module_entry; 1129 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure. 1130 BOOL cont = _Module32FirstW(snapshot, &module_entry); 1131 while (cont) { 1132 DWORD64 base; 1133 // NOTE the SymLoadModule64 function has the peculiarity of accepting a 1134 // both unicode and ASCII strings even though the parameter is PSTR. 1135 base = _SymLoadModule64( 1136 process_handle, // hProcess 1137 0, // hFile 1138 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName 1139 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName 1140 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll 1141 module_entry.modBaseSize); // SizeOfDll 1142 if (base == 0) { 1143 int err = GetLastError(); 1144 if (err != ERROR_MOD_NOT_FOUND && 1145 err != ERROR_INVALID_HANDLE) { 1146 result.clear(); 1147 return result; 1148 } 1149 } 1150 int lib_name_length = WideCharToMultiByte( 1151 CP_UTF8, 0, module_entry.szExePath, -1, NULL, 0, NULL, NULL); 1152 std::string lib_name(lib_name_length, 0); 1153 WideCharToMultiByte(CP_UTF8, 0, module_entry.szExePath, -1, &lib_name[0], 1154 lib_name_length, NULL, NULL); 1155 result.push_back(OS::SharedLibraryAddress( 1156 lib_name, reinterpret_cast<uintptr_t>(module_entry.modBaseAddr), 1157 reinterpret_cast<uintptr_t>(module_entry.modBaseAddr + 1158 module_entry.modBaseSize))); 1159 cont = _Module32NextW(snapshot, &module_entry); 1160 } 1161 CloseHandle(snapshot); 1162 1163 symbols_loaded = true; 1164 return result; 1165} 1166 1167 1168std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() { 1169 // SharedLibraryEvents are logged when loading symbol information. 1170 // Only the shared libraries loaded at the time of the call to 1171 // GetSharedLibraryAddresses are logged. DLLs loaded after 1172 // initialization are not accounted for. 1173 if (!LoadDbgHelpAndTlHelp32()) return std::vector<OS::SharedLibraryAddress>(); 1174 HANDLE process_handle = GetCurrentProcess(); 1175 return LoadSymbols(process_handle); 1176} 1177 1178 1179void OS::SignalCodeMovingGC() { 1180} 1181 1182 1183#else // __MINGW32__ 1184std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() { 1185 return std::vector<OS::SharedLibraryAddress>(); 1186} 1187 1188 1189void OS::SignalCodeMovingGC() { } 1190#endif // __MINGW32__ 1191 1192 1193int OS::ActivationFrameAlignment() { 1194#ifdef _WIN64 1195 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned. 1196#elif defined(__MINGW32__) 1197 // With gcc 4.4 the tree vectorization optimizer can generate code 1198 // that requires 16 byte alignment such as movdqa on x86. 1199 return 16; 1200#else 1201 return 8; // Floating-point math runs faster with 8-byte alignment. 1202#endif 1203} 1204 1205 1206VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { } 1207 1208 1209VirtualMemory::VirtualMemory(size_t size) 1210 : address_(ReserveRegion(size)), size_(size) { } 1211 1212 1213VirtualMemory::VirtualMemory(size_t size, size_t alignment) 1214 : address_(NULL), size_(0) { 1215 DCHECK((alignment % OS::AllocateAlignment()) == 0); 1216 size_t request_size = RoundUp(size + alignment, 1217 static_cast<intptr_t>(OS::AllocateAlignment())); 1218 void* address = ReserveRegion(request_size); 1219 if (address == NULL) return; 1220 uint8_t* base = RoundUp(static_cast<uint8_t*>(address), alignment); 1221 // Try reducing the size by freeing and then reallocating a specific area. 1222 bool result = ReleaseRegion(address, request_size); 1223 USE(result); 1224 DCHECK(result); 1225 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS); 1226 if (address != NULL) { 1227 request_size = size; 1228 DCHECK(base == static_cast<uint8_t*>(address)); 1229 } else { 1230 // Resizing failed, just go with a bigger area. 1231 address = ReserveRegion(request_size); 1232 if (address == NULL) return; 1233 } 1234 address_ = address; 1235 size_ = request_size; 1236} 1237 1238 1239VirtualMemory::~VirtualMemory() { 1240 if (IsReserved()) { 1241 bool result = ReleaseRegion(address(), size()); 1242 DCHECK(result); 1243 USE(result); 1244 } 1245} 1246 1247 1248bool VirtualMemory::IsReserved() { 1249 return address_ != NULL; 1250} 1251 1252 1253void VirtualMemory::Reset() { 1254 address_ = NULL; 1255 size_ = 0; 1256} 1257 1258 1259bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) { 1260 return CommitRegion(address, size, is_executable); 1261} 1262 1263 1264bool VirtualMemory::Uncommit(void* address, size_t size) { 1265 DCHECK(IsReserved()); 1266 return UncommitRegion(address, size); 1267} 1268 1269 1270bool VirtualMemory::Guard(void* address) { 1271 if (NULL == VirtualAlloc(address, 1272 OS::CommitPageSize(), 1273 MEM_COMMIT, 1274 PAGE_NOACCESS)) { 1275 return false; 1276 } 1277 return true; 1278} 1279 1280 1281void* VirtualMemory::ReserveRegion(size_t size) { 1282 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS); 1283} 1284 1285 1286bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) { 1287 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; 1288 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) { 1289 return false; 1290 } 1291 return true; 1292} 1293 1294 1295bool VirtualMemory::UncommitRegion(void* base, size_t size) { 1296 return VirtualFree(base, size, MEM_DECOMMIT) != 0; 1297} 1298 1299bool VirtualMemory::ReleasePartialRegion(void* base, size_t size, 1300 void* free_start, size_t free_size) { 1301 return VirtualFree(free_start, free_size, MEM_DECOMMIT) != 0; 1302} 1303 1304bool VirtualMemory::ReleaseRegion(void* base, size_t size) { 1305 return VirtualFree(base, 0, MEM_RELEASE) != 0; 1306} 1307 1308 1309bool VirtualMemory::HasLazyCommits() { 1310 // TODO(alph): implement for the platform. 1311 return false; 1312} 1313 1314 1315// ---------------------------------------------------------------------------- 1316// Win32 thread support. 1317 1318// Definition of invalid thread handle and id. 1319static const HANDLE kNoThread = INVALID_HANDLE_VALUE; 1320 1321// Entry point for threads. The supplied argument is a pointer to the thread 1322// object. The entry function dispatches to the run method in the thread 1323// object. It is important that this function has __stdcall calling 1324// convention. 1325static unsigned int __stdcall ThreadEntry(void* arg) { 1326 Thread* thread = reinterpret_cast<Thread*>(arg); 1327 thread->NotifyStartedAndRun(); 1328 return 0; 1329} 1330 1331 1332class Thread::PlatformData { 1333 public: 1334 explicit PlatformData(HANDLE thread) : thread_(thread) {} 1335 HANDLE thread_; 1336 unsigned thread_id_; 1337}; 1338 1339 1340// Initialize a Win32 thread object. The thread has an invalid thread 1341// handle until it is started. 1342 1343Thread::Thread(const Options& options) 1344 : stack_size_(options.stack_size()), 1345 start_semaphore_(NULL) { 1346 data_ = new PlatformData(kNoThread); 1347 set_name(options.name()); 1348} 1349 1350 1351void Thread::set_name(const char* name) { 1352 OS::StrNCpy(name_, sizeof(name_), name, strlen(name)); 1353 name_[sizeof(name_) - 1] = '\0'; 1354} 1355 1356 1357// Close our own handle for the thread. 1358Thread::~Thread() { 1359 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_); 1360 delete data_; 1361} 1362 1363 1364// Create a new thread. It is important to use _beginthreadex() instead of 1365// the Win32 function CreateThread(), because the CreateThread() does not 1366// initialize thread specific structures in the C runtime library. 1367void Thread::Start() { 1368 data_->thread_ = reinterpret_cast<HANDLE>( 1369 _beginthreadex(NULL, 1370 static_cast<unsigned>(stack_size_), 1371 ThreadEntry, 1372 this, 1373 0, 1374 &data_->thread_id_)); 1375} 1376 1377 1378// Wait for thread to terminate. 1379void Thread::Join() { 1380 if (data_->thread_id_ != GetCurrentThreadId()) { 1381 WaitForSingleObject(data_->thread_, INFINITE); 1382 } 1383} 1384 1385 1386Thread::LocalStorageKey Thread::CreateThreadLocalKey() { 1387 DWORD result = TlsAlloc(); 1388 DCHECK(result != TLS_OUT_OF_INDEXES); 1389 return static_cast<LocalStorageKey>(result); 1390} 1391 1392 1393void Thread::DeleteThreadLocalKey(LocalStorageKey key) { 1394 BOOL result = TlsFree(static_cast<DWORD>(key)); 1395 USE(result); 1396 DCHECK(result); 1397} 1398 1399 1400void* Thread::GetThreadLocal(LocalStorageKey key) { 1401 return TlsGetValue(static_cast<DWORD>(key)); 1402} 1403 1404 1405void Thread::SetThreadLocal(LocalStorageKey key, void* value) { 1406 BOOL result = TlsSetValue(static_cast<DWORD>(key), value); 1407 USE(result); 1408 DCHECK(result); 1409} 1410 1411} // namespace base 1412} // namespace v8 1413