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