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.
5 // Platform-specific code for Win32.
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.
13 #ifdef MINGW_HAS_SECURE_API
14 #undef MINGW_HAS_SECURE_API
15 #endif // MINGW_HAS_SECURE_API
18 #include "win32-headers.h"
23 #include "isolate-inl.h"
28 // Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
29 // defined in strings.h.
30 int strncasecmp(const char* s1, const char* s2, int n) {
31 return _strnicmp(s1, s2, n);
37 // Extra functions for MinGW. Most of these are the _s functions which are in
38 // the Microsoft Visual Studio C++ CRT.
42 #ifndef __MINGW64_VERSION_MAJOR
47 inline void MemoryBarrier() {
49 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
52 #endif // __MINGW64_VERSION_MAJOR
55 int localtime_s(tm* out_tm, const time_t* time) {
56 tm* posix_local_time_struct = localtime(time);
57 if (posix_local_time_struct == NULL) return 1;
58 *out_tm = *posix_local_time_struct;
63 int fopen_s(FILE** pFile, const char* filename, const char* mode) {
64 *pFile = fopen(filename, mode);
65 return *pFile != NULL ? 0 : 1;
68 int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
69 const char* format, va_list argptr) {
70 ASSERT(count == _TRUNCATE);
71 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
75 int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
76 CHECK(source != NULL);
78 CHECK_GT(dest_size, 0);
80 if (count == _TRUNCATE) {
81 while (dest_size > 0 && *source != 0) {
82 *(dest++) = *(source++);
90 while (dest_size > 0 && count > 0 && *source != 0) {
91 *(dest++) = *(source++);
96 CHECK_GT(dest_size, 0);
101 #endif // __MINGW32__
106 intptr_t OS::MaxVirtualMemory() {
111 #if V8_TARGET_ARCH_IA32
112 static void MemMoveWrapper(void* dest, const void* src, size_t size) {
113 memmove(dest, src, size);
117 // Initialize to library version so we can call this at any time during startup.
118 static OS::MemMoveFunction memmove_function = &MemMoveWrapper;
120 // Defined in codegen-ia32.cc.
121 OS::MemMoveFunction CreateMemMoveFunction();
123 // Copy memory area to disjoint memory area.
124 void OS::MemMove(void* dest, const void* src, size_t size) {
125 if (size == 0) return;
126 // Note: here we rely on dependent reads being ordered. This is true
127 // on all architectures we currently support.
128 (*memmove_function)(dest, src, size);
131 #endif // V8_TARGET_ARCH_IA32
134 typedef double (*ModuloFunction)(double, double);
135 static ModuloFunction modulo_function = NULL;
136 // Defined in codegen-x64.cc.
137 ModuloFunction CreateModuloFunction();
139 void init_modulo_function() {
140 modulo_function = CreateModuloFunction();
144 double modulo(double x, double y) {
145 // Note: here we rely on dependent reads being ordered. This is true
146 // on all architectures we currently support.
147 return (*modulo_function)(x, y);
151 double modulo(double x, double y) {
152 // Workaround MS fmod bugs. ECMA-262 says:
153 // dividend is finite and divisor is an infinity => result equals dividend
154 // dividend is a zero and divisor is nonzero finite => result equals dividend
155 if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) &&
156 !(x == 0 && (y != 0 && std::isfinite(y)))) {
165 #define UNARY_MATH_FUNCTION(name, generator) \
166 static UnaryMathFunction fast_##name##_function = NULL; \
167 void init_fast_##name##_function() { \
168 fast_##name##_function = generator; \
170 double fast_##name(double x) { \
171 return (*fast_##name##_function)(x); \
174 UNARY_MATH_FUNCTION(exp, CreateExpFunction())
175 UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
177 #undef UNARY_MATH_FUNCTION
180 void lazily_initialize_fast_exp() {
181 if (fast_exp_function == NULL) {
182 init_fast_exp_function();
189 init_modulo_function();
191 // fast_exp is initialized lazily.
192 init_fast_sqrt_function();
196 class TimezoneCache {
198 TimezoneCache() : initialized_(false) { }
201 initialized_ = false;
204 // Initialize timezone information. The timezone information is obtained from
205 // windows. If we cannot get the timezone information we fall back to CET.
206 void InitializeIfNeeded() {
207 // Just return if timezone information has already been initialized.
208 if (initialized_) return;
210 // Initialize POSIX time zone data.
212 // Obtain timezone information from operating system.
213 memset(&tzinfo_, 0, sizeof(tzinfo_));
214 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
215 // If we cannot get timezone information we fall back to CET.
217 tzinfo_.StandardDate.wMonth = 10;
218 tzinfo_.StandardDate.wDay = 5;
219 tzinfo_.StandardDate.wHour = 3;
220 tzinfo_.StandardBias = 0;
221 tzinfo_.DaylightDate.wMonth = 3;
222 tzinfo_.DaylightDate.wDay = 5;
223 tzinfo_.DaylightDate.wHour = 2;
224 tzinfo_.DaylightBias = -60;
227 // Make standard and DST timezone names.
228 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
229 std_tz_name_, kTzNameSize, NULL, NULL);
230 std_tz_name_[kTzNameSize - 1] = '\0';
231 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
232 dst_tz_name_, kTzNameSize, NULL, NULL);
233 dst_tz_name_[kTzNameSize - 1] = '\0';
235 // If OS returned empty string or resource id (like "@tzres.dll,-211")
236 // simply guess the name from the UTC bias of the timezone.
237 // To properly resolve the resource identifier requires a library load,
238 // which is not possible in a sandbox.
239 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
240 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
242 GuessTimezoneNameFromBias(tzinfo_.Bias));
244 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
245 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
247 GuessTimezoneNameFromBias(tzinfo_.Bias));
249 // Timezone information initialized.
253 // Guess the name of the timezone from the bias.
254 // The guess is very biased towards the northern hemisphere.
255 const char* GuessTimezoneNameFromBias(int bias) {
256 static const int kHour = 60;
258 case -9*kHour: return "Alaska";
259 case -8*kHour: return "Pacific";
260 case -7*kHour: return "Mountain";
261 case -6*kHour: return "Central";
262 case -5*kHour: return "Eastern";
263 case -4*kHour: return "Atlantic";
264 case 0*kHour: return "GMT";
265 case +1*kHour: return "Central Europe";
266 case +2*kHour: return "Eastern Europe";
267 case +3*kHour: return "Russia";
268 case +5*kHour + 30: return "India";
269 case +8*kHour: return "China";
270 case +9*kHour: return "Japan";
271 case +12*kHour: return "New Zealand";
272 default: return "Local";
278 static const int kTzNameSize = 128;
280 char std_tz_name_[kTzNameSize];
281 char dst_tz_name_[kTzNameSize];
282 TIME_ZONE_INFORMATION tzinfo_;
283 friend class Win32Time;
287 // ----------------------------------------------------------------------------
288 // The Time class represents time on win32. A timestamp is represented as
289 // a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
290 // timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
297 explicit Win32Time(double jstime);
298 Win32Time(int year, int mon, int day, int hour, int min, int sec);
300 // Convert timestamp to JavaScript representation.
303 // Set timestamp to current time.
304 void SetToCurrentTime();
306 // Returns the local timezone offset in milliseconds east of UTC. This is
307 // the number of milliseconds you must add to UTC to get local time, i.e.
308 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
309 // routine also takes into account whether daylight saving is effect
311 int64_t LocalOffset(TimezoneCache* cache);
313 // Returns the daylight savings time offset for the time in milliseconds.
314 int64_t DaylightSavingsOffset(TimezoneCache* cache);
316 // Returns a string identifying the current timezone for the
317 // timestamp taking into account daylight saving.
318 char* LocalTimezone(TimezoneCache* cache);
321 // Constants for time conversion.
322 static const int64_t kTimeEpoc = 116444736000000000LL;
323 static const int64_t kTimeScaler = 10000;
324 static const int64_t kMsPerMinute = 60000;
326 // Constants for timezone information.
327 static const bool kShortTzNames = false;
329 // Return whether or not daylight savings time is in effect at this time.
330 bool InDST(TimezoneCache* cache);
332 // Accessor for FILETIME representation.
333 FILETIME& ft() { return time_.ft_; }
335 // Accessor for integer representation.
336 int64_t& t() { return time_.t_; }
338 // Although win32 uses 64-bit integers for representing timestamps,
339 // these are packed into a FILETIME structure. The FILETIME structure
340 // is just a struct representing a 64-bit integer. The TimeStamp union
341 // allows access to both a FILETIME and an integer representation of
352 // Initialize timestamp to start of epoc.
353 Win32Time::Win32Time() {
358 // Initialize timestamp from a JavaScript timestamp.
359 Win32Time::Win32Time(double jstime) {
360 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
364 // Initialize timestamp from date/time components.
365 Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
373 st.wMilliseconds = 0;
374 SystemTimeToFileTime(&st, &ft());
378 // Convert timestamp to JavaScript timestamp.
379 double Win32Time::ToJSTime() {
380 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
384 // Set timestamp to current time.
385 void Win32Time::SetToCurrentTime() {
386 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
387 // Because we're fast, we like fast timers which have at least a
390 // timeGetTime() provides 1ms granularity when combined with
391 // timeBeginPeriod(). If the host application for v8 wants fast
392 // timers, it can use timeBeginPeriod to increase the resolution.
394 // Using timeGetTime() has a drawback because it is a 32bit value
395 // and hence rolls-over every ~49days.
397 // To use the clock, we use GetSystemTimeAsFileTime as our base;
398 // and then use timeGetTime to extrapolate current time from the
399 // start time. To deal with rollovers, we resync the clock
400 // any time when more than kMaxClockElapsedTime has passed or
401 // whenever timeGetTime creates a rollover.
403 static bool initialized = false;
404 static TimeStamp init_time;
405 static DWORD init_ticks;
406 static const int64_t kHundredNanosecondsPerSecond = 10000000;
407 static const int64_t kMaxClockElapsedTime =
408 60*kHundredNanosecondsPerSecond; // 1 minute
410 // If we are uninitialized, we need to resync the clock.
411 bool needs_resync = !initialized;
413 // Get the current time.
415 GetSystemTimeAsFileTime(&time_now.ft_);
416 DWORD ticks_now = timeGetTime();
418 // Check if we need to resync due to clock rollover.
419 needs_resync |= ticks_now < init_ticks;
421 // Check if we need to resync due to elapsed time.
422 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
424 // Check if we need to resync due to backwards time change.
425 needs_resync |= time_now.t_ < init_time.t_;
427 // Resync the clock if necessary.
429 GetSystemTimeAsFileTime(&init_time.ft_);
430 init_ticks = ticks_now = timeGetTime();
434 // Finally, compute the actual time. Why is this so hard.
435 DWORD elapsed = ticks_now - init_ticks;
436 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
440 // Return the local timezone offset in milliseconds east of UTC. This
441 // takes into account whether daylight saving is in effect at the time.
442 // Only times in the 32-bit Unix range may be passed to this function.
443 // Also, adding the time-zone offset to the input must not overflow.
444 // The function EquivalentTime() in date.js guarantees this.
445 int64_t Win32Time::LocalOffset(TimezoneCache* cache) {
446 cache->InitializeIfNeeded();
448 Win32Time rounded_to_second(*this);
449 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
451 // Convert to local time using POSIX localtime function.
452 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
453 // very slow. Other browsers use localtime().
455 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
456 // POSIX seconds past 1/1/1970 0:00:00.
457 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
458 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
461 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
462 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
464 // Convert to local time, as struct with fields for day, hour, year, etc.
465 tm posix_local_time_struct;
466 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
468 if (posix_local_time_struct.tm_isdst > 0) {
469 return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
470 } else if (posix_local_time_struct.tm_isdst == 0) {
471 return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
473 return cache->tzinfo_.Bias * -kMsPerMinute;
478 // Return whether or not daylight savings time is in effect at this time.
479 bool Win32Time::InDST(TimezoneCache* cache) {
480 cache->InitializeIfNeeded();
482 // Determine if DST is in effect at the specified time.
484 if (cache->tzinfo_.StandardDate.wMonth != 0 ||
485 cache->tzinfo_.DaylightDate.wMonth != 0) {
486 // Get the local timezone offset for the timestamp in milliseconds.
487 int64_t offset = LocalOffset(cache);
489 // Compute the offset for DST. The bias parameters in the timezone info
490 // are specified in minutes. These must be converted to milliseconds.
492 -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
494 // If the local time offset equals the timezone bias plus the daylight
495 // bias then DST is in effect.
496 in_dst = offset == dstofs;
503 // Return the daylight savings time offset for this time.
504 int64_t Win32Time::DaylightSavingsOffset(TimezoneCache* cache) {
505 return InDST(cache) ? 60 * kMsPerMinute : 0;
509 // Returns a string identifying the current timezone for the
510 // timestamp taking into account daylight saving.
511 char* Win32Time::LocalTimezone(TimezoneCache* cache) {
512 // Return the standard or DST time zone name based on whether daylight
513 // saving is in effect at the given time.
514 return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
518 void OS::PostSetUp() {
519 // Math functions depend on CPU features therefore they are initialized after
522 #if V8_TARGET_ARCH_IA32
523 OS::MemMoveFunction generated_memmove = CreateMemMoveFunction();
524 if (generated_memmove != NULL) {
525 memmove_function = generated_memmove;
531 // Returns the accumulated user time for thread.
532 int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
536 // Get the amount of time that the thread has executed in user mode.
537 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
538 reinterpret_cast<FILETIME*>(&usertime))) return -1;
540 // Adjust the resolution to micro-seconds.
543 // Convert to seconds and microseconds
544 *secs = static_cast<uint32_t>(usertime / 1000000);
545 *usecs = static_cast<uint32_t>(usertime % 1000000);
550 // Returns current time as the number of milliseconds since
551 // 00:00:00 UTC, January 1, 1970.
552 double OS::TimeCurrentMillis() {
553 return Time::Now().ToJsTime();
557 TimezoneCache* OS::CreateTimezoneCache() {
558 return new TimezoneCache();
562 void OS::DisposeTimezoneCache(TimezoneCache* cache) {
567 void OS::ClearTimezoneCache(TimezoneCache* cache) {
572 // Returns a string identifying the current timezone taking into
573 // account daylight saving.
574 const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
575 return Win32Time(time).LocalTimezone(cache);
579 // Returns the local time offset in milliseconds east of UTC without
580 // taking daylight savings time into account.
581 double OS::LocalTimeOffset(TimezoneCache* cache) {
582 // Use current time, rounded to the millisecond.
583 Win32Time t(TimeCurrentMillis());
584 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
585 return static_cast<double>(t.LocalOffset(cache) -
586 t.DaylightSavingsOffset(cache));
590 // Returns the daylight savings offset in milliseconds for the given
592 double OS::DaylightSavingsOffset(double time, TimezoneCache* cache) {
593 int64_t offset = Win32Time(time).DaylightSavingsOffset(cache);
594 return static_cast<double>(offset);
598 int OS::GetLastError() {
599 return ::GetLastError();
603 int OS::GetCurrentProcessId() {
604 return static_cast<int>(::GetCurrentProcessId());
608 // ----------------------------------------------------------------------------
609 // Win32 console output.
611 // If a Win32 application is linked as a console application it has a normal
612 // standard output and standard error. In this case normal printf works fine
613 // for output. However, if the application is linked as a GUI application,
614 // the process doesn't have a console, and therefore (debugging) output is lost.
615 // This is the case if we are embedded in a windows program (like a browser).
616 // In order to be able to get debug output in this case the the debugging
617 // facility using OutputDebugString. This output goes to the active debugger
618 // for the process (if any). Else the output can be monitored using DBMON.EXE.
621 UNKNOWN, // Output method has not yet been determined.
622 CONSOLE, // Output is written to stdout.
623 ODS // Output is written to debug facility.
626 static OutputMode output_mode = UNKNOWN; // Current output mode.
629 // Determine if the process has a console for output.
630 static bool HasConsole() {
631 // Only check the first time. Eventual race conditions are not a problem,
632 // because all threads will eventually determine the same mode.
633 if (output_mode == UNKNOWN) {
634 // We cannot just check that the standard output is attached to a console
635 // because this would fail if output is redirected to a file. Therefore we
636 // say that a process does not have an output console if either the
637 // standard output handle is invalid or its file type is unknown.
638 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
639 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
640 output_mode = CONSOLE;
644 return output_mode == CONSOLE;
648 static void VPrintHelper(FILE* stream, const char* format, va_list args) {
649 if ((stream == stdout || stream == stderr) && !HasConsole()) {
650 // It is important to use safe print here in order to avoid
651 // overflowing the buffer. We might truncate the output, but this
653 EmbeddedVector<char, 4096> buffer;
654 OS::VSNPrintF(buffer, format, args);
655 OutputDebugStringA(buffer.start());
657 vfprintf(stream, format, args);
662 FILE* OS::FOpen(const char* path, const char* mode) {
664 if (fopen_s(&result, path, mode) == 0) {
672 bool OS::Remove(const char* path) {
673 return (DeleteFileA(path) != 0);
677 FILE* OS::OpenTemporaryFile() {
678 // tmpfile_s tries to use the root dir, don't use it.
679 char tempPathBuffer[MAX_PATH];
680 DWORD path_result = 0;
681 path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
682 if (path_result > MAX_PATH || path_result == 0) return NULL;
683 UINT name_result = 0;
684 char tempNameBuffer[MAX_PATH];
685 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
686 if (name_result == 0) return NULL;
687 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
688 if (result != NULL) {
689 Remove(tempNameBuffer); // Delete on close.
695 // Open log file in binary mode to avoid /n -> /r/n conversion.
696 const char* const OS::LogFileOpenMode = "wb";
699 // Print (debug) message to console.
700 void OS::Print(const char* format, ...) {
702 va_start(args, format);
703 VPrint(format, args);
708 void OS::VPrint(const char* format, va_list args) {
709 VPrintHelper(stdout, format, args);
713 void OS::FPrint(FILE* out, const char* format, ...) {
715 va_start(args, format);
716 VFPrint(out, format, args);
721 void OS::VFPrint(FILE* out, const char* format, va_list args) {
722 VPrintHelper(out, format, args);
726 // Print error message to console.
727 void OS::PrintError(const char* format, ...) {
729 va_start(args, format);
730 VPrintError(format, args);
735 void OS::VPrintError(const char* format, va_list args) {
736 VPrintHelper(stderr, format, args);
740 int OS::SNPrintF(Vector<char> str, const char* format, ...) {
742 va_start(args, format);
743 int result = VSNPrintF(str, format, args);
749 int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
750 int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
751 // Make sure to zero-terminate the string if the output was
752 // truncated or if there was an error.
753 if (n < 0 || n >= str.length()) {
754 if (str.length() > 0)
755 str[str.length() - 1] = '\0';
763 char* OS::StrChr(char* str, int c) {
764 return const_cast<char*>(strchr(str, c));
768 void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
769 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
770 size_t buffer_size = static_cast<size_t>(dest.length());
771 if (n + 1 > buffer_size) // count for trailing '\0'
773 int result = strncpy_s(dest.start(), dest.length(), src, n);
775 ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
783 // Get the system's page size used by VirtualAlloc() or the next power
784 // of two. The reason for always returning a power of two is that the
785 // rounding up in OS::Allocate expects that.
786 static size_t GetPageSize() {
787 static size_t page_size = 0;
788 if (page_size == 0) {
790 GetSystemInfo(&info);
791 page_size = RoundUpToPowerOf2(info.dwPageSize);
797 // The allocation alignment is the guaranteed alignment for
798 // VirtualAlloc'ed blocks of memory.
799 size_t OS::AllocateAlignment() {
800 static size_t allocate_alignment = 0;
801 if (allocate_alignment == 0) {
803 GetSystemInfo(&info);
804 allocate_alignment = info.dwAllocationGranularity;
806 return allocate_alignment;
810 void* OS::GetRandomMmapAddr() {
811 Isolate* isolate = Isolate::UncheckedCurrent();
812 // Note that the current isolate isn't set up in a call path via
813 // CpuFeatures::Probe. We don't care about randomization in this case because
814 // the code page is immediately freed.
815 if (isolate != NULL) {
816 // The address range used to randomize RWX allocations in OS::Allocate
817 // Try not to map pages into the default range that windows loads DLLs
818 // Use a multiple of 64k to prevent committing unused memory.
819 // Note: This does not guarantee RWX regions will be within the
820 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
821 #ifdef V8_HOST_ARCH_64_BIT
822 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
823 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
825 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
826 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
829 (isolate->random_number_generator()->NextInt() << kPageSizeBits) |
830 kAllocationRandomAddressMin;
831 address &= kAllocationRandomAddressMax;
832 return reinterpret_cast<void *>(address);
838 static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
841 if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
842 // For exectutable pages try and randomize the allocation address
843 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
844 base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection);
848 // After three attempts give up and let the OS find an address to use.
849 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
855 void* OS::Allocate(const size_t requested,
857 bool is_executable) {
858 // VirtualAlloc rounds allocated size to page size automatically.
859 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
861 // Windows XP SP2 allows Data Excution Prevention (DEP).
862 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
864 LPVOID mbase = RandomizedVirtualAlloc(msize,
865 MEM_COMMIT | MEM_RESERVE,
869 LOG(Isolate::Current(), StringEvent("OS::Allocate", "VirtualAlloc failed"));
873 ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
880 void OS::Free(void* address, const size_t size) {
881 // TODO(1240712): VirtualFree has a return value which is ignored here.
882 VirtualFree(address, 0, MEM_RELEASE);
887 intptr_t OS::CommitPageSize() {
892 void OS::ProtectCode(void* address, const size_t size) {
894 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
898 void OS::Guard(void* address, const size_t size) {
900 VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect);
904 void OS::Sleep(int milliseconds) {
905 ::Sleep(milliseconds);
910 if (FLAG_hard_abort) {
911 V8_IMMEDIATE_CRASH();
913 // Make the MSVCRT do a silent abort.
918 void OS::DebugBreak() {
920 // To avoid Visual Studio runtime support the following code can be used
930 class Win32MemoryMappedFile : public OS::MemoryMappedFile {
932 Win32MemoryMappedFile(HANDLE file,
937 file_mapping_(file_mapping),
940 virtual ~Win32MemoryMappedFile();
941 virtual void* memory() { return memory_; }
942 virtual int size() { return size_; }
945 HANDLE file_mapping_;
951 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
952 // Open a physical file
953 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
954 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
955 if (file == INVALID_HANDLE_VALUE) return NULL;
957 int size = static_cast<int>(GetFileSize(file, NULL));
959 // Create a file mapping for the physical file
960 HANDLE file_mapping = CreateFileMapping(file, NULL,
961 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
962 if (file_mapping == NULL) return NULL;
964 // Map a view of the file into memory
965 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
966 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
970 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
972 // Open a physical file
973 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
974 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
975 if (file == NULL) return NULL;
976 // Create a file mapping for the physical file
977 HANDLE file_mapping = CreateFileMapping(file, NULL,
978 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
979 if (file_mapping == NULL) return NULL;
980 // Map a view of the file into memory
981 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
982 if (memory) OS::MemMove(memory, initial, size);
983 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
987 Win32MemoryMappedFile::~Win32MemoryMappedFile() {
989 UnmapViewOfFile(memory_);
990 CloseHandle(file_mapping_);
995 // The following code loads functions defined in DbhHelp.h and TlHelp32.h
996 // dynamically. This is to avoid being depending on dbghelp.dll and
997 // tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
998 // kernel32.dll at some point so loading functions defines in TlHelp32.h
999 // dynamically might not be necessary any more - for some versions of Windows?).
1001 // Function pointers to functions dynamically loaded from dbghelp.dll.
1002 #define DBGHELP_FUNCTION_LIST(V) \
1006 V(SymGetSearchPath) \
1007 V(SymLoadModule64) \
1009 V(SymGetSymFromAddr64) \
1010 V(SymGetLineFromAddr64) \
1011 V(SymFunctionTableAccess64) \
1012 V(SymGetModuleBase64)
1014 // Function pointers to functions dynamically loaded from dbghelp.dll.
1015 #define TLHELP32_FUNCTION_LIST(V) \
1016 V(CreateToolhelp32Snapshot) \
1020 // Define the decoration to use for the type and variable name used for
1021 // dynamically loaded DLL function..
1022 #define DLL_FUNC_TYPE(name) _##name##_
1023 #define DLL_FUNC_VAR(name) _##name
1025 // Define the type for each dynamically loaded DLL function. The function
1026 // definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1027 // from the Windows include files are redefined here to have the function
1028 // definitions to be as close to the ones in the original .h files as possible.
1036 // DbgHelp isn't supported on MinGW yet
1038 // DbgHelp.h functions.
1039 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
1040 IN PSTR UserSearchPath,
1041 IN BOOL fInvadeProcess);
1042 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
1043 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
1044 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
1046 OUT PSTR SearchPath,
1047 IN DWORD SearchPathLength);
1048 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
1053 IN DWORD64 BaseOfDll,
1054 IN DWORD SizeOfDll);
1055 typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
1059 LPSTACKFRAME64 StackFrame,
1060 PVOID ContextRecord,
1061 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1062 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1063 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1064 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1065 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
1068 OUT PDWORD64 pdwDisplacement,
1069 OUT PIMAGEHLP_SYMBOL64 Symbol);
1070 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
1073 OUT PDWORD pdwDisplacement,
1074 OUT PIMAGEHLP_LINE64 Line64);
1075 // DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1076 typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
1078 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1079 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1081 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1083 // TlHelp32.h functions.
1084 typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1086 DWORD th32ProcessID);
1087 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1088 LPMODULEENTRY32W lpme);
1089 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1090 LPMODULEENTRY32W lpme);
1095 // Declare a variable for each dynamically loaded DLL function.
1096 #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1097 DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1098 TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1099 #undef DEF_DLL_FUNCTION
1101 // Load the functions. This function has a lot of "ugly" macros in order to
1102 // keep down code duplication.
1104 static bool LoadDbgHelpAndTlHelp32() {
1105 static bool dbghelp_loaded = false;
1107 if (dbghelp_loaded) return true;
1111 // Load functions from the dbghelp.dll module.
1112 module = LoadLibrary(TEXT("dbghelp.dll"));
1113 if (module == NULL) {
1117 #define LOAD_DLL_FUNC(name) \
1118 DLL_FUNC_VAR(name) = \
1119 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1121 DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1123 #undef LOAD_DLL_FUNC
1125 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1126 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1127 module = LoadLibrary(TEXT("kernel32.dll"));
1128 if (module == NULL) {
1132 #define LOAD_DLL_FUNC(name) \
1133 DLL_FUNC_VAR(name) = \
1134 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1136 TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1138 #undef LOAD_DLL_FUNC
1140 // Check that all functions where loaded.
1142 #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1144 DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1145 TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1147 #undef DLL_FUNC_LOADED
1150 dbghelp_loaded = result;
1152 // NOTE: The modules are never unloaded and will stay around until the
1153 // application is closed.
1156 #undef DBGHELP_FUNCTION_LIST
1157 #undef TLHELP32_FUNCTION_LIST
1159 #undef DLL_FUNC_TYPE
1162 // Load the symbols for generating stack traces.
1163 static bool LoadSymbols(Isolate* isolate, HANDLE process_handle) {
1164 static bool symbols_loaded = false;
1166 if (symbols_loaded) return true;
1170 // Initialize the symbol engine.
1171 ok = _SymInitialize(process_handle, // hProcess
1172 NULL, // UserSearchPath
1173 false); // fInvadeProcess
1174 if (!ok) return false;
1176 DWORD options = _SymGetOptions();
1177 options |= SYMOPT_LOAD_LINES;
1178 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1179 options = _SymSetOptions(options);
1181 char buf[OS::kStackWalkMaxNameLen] = {0};
1182 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1184 int err = GetLastError();
1185 PrintF("%d\n", err);
1189 HANDLE snapshot = _CreateToolhelp32Snapshot(
1190 TH32CS_SNAPMODULE, // dwFlags
1191 GetCurrentProcessId()); // th32ProcessId
1192 if (snapshot == INVALID_HANDLE_VALUE) return false;
1193 MODULEENTRY32W module_entry;
1194 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1195 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1198 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1199 // both unicode and ASCII strings even though the parameter is PSTR.
1200 base = _SymLoadModule64(
1201 process_handle, // hProcess
1203 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1204 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1205 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1206 module_entry.modBaseSize); // SizeOfDll
1208 int err = GetLastError();
1209 if (err != ERROR_MOD_NOT_FOUND &&
1210 err != ERROR_INVALID_HANDLE) return false;
1214 module_entry.szExePath,
1215 reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1216 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1217 module_entry.modBaseSize)));
1218 cont = _Module32NextW(snapshot, &module_entry);
1220 CloseHandle(snapshot);
1222 symbols_loaded = true;
1227 void OS::LogSharedLibraryAddresses(Isolate* isolate) {
1228 // SharedLibraryEvents are logged when loading symbol information.
1229 // Only the shared libraries loaded at the time of the call to
1230 // LogSharedLibraryAddresses are logged. DLLs loaded after
1231 // initialization are not accounted for.
1232 if (!LoadDbgHelpAndTlHelp32()) return;
1233 HANDLE process_handle = GetCurrentProcess();
1234 LoadSymbols(isolate, process_handle);
1238 void OS::SignalCodeMovingGC() {
1242 uint64_t OS::TotalPhysicalMemory() {
1243 MEMORYSTATUSEX memory_info;
1244 memory_info.dwLength = sizeof(memory_info);
1245 if (!GlobalMemoryStatusEx(&memory_info)) {
1250 return static_cast<uint64_t>(memory_info.ullTotalPhys);
1254 #else // __MINGW32__
1255 void OS::LogSharedLibraryAddresses(Isolate* isolate) { }
1256 void OS::SignalCodeMovingGC() { }
1257 #endif // __MINGW32__
1260 uint64_t OS::CpuFeaturesImpliedByPlatform() {
1261 return 0; // Windows runs on anything.
1265 double OS::nan_value() {
1267 // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
1268 // in mask set, so value equals mask.
1269 static const __int64 nanval = kQuietNaNMask;
1270 return *reinterpret_cast<const double*>(&nanval);
1277 int OS::ActivationFrameAlignment() {
1279 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1280 #elif defined(__MINGW32__)
1281 // With gcc 4.4 the tree vectorization optimizer can generate code
1282 // that requires 16 byte alignment such as movdqa on x86.
1285 return 8; // Floating-point math runs faster with 8-byte alignment.
1290 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
1293 VirtualMemory::VirtualMemory(size_t size)
1294 : address_(ReserveRegion(size)), size_(size) { }
1297 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1298 : address_(NULL), size_(0) {
1299 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
1300 size_t request_size = RoundUp(size + alignment,
1301 static_cast<intptr_t>(OS::AllocateAlignment()));
1302 void* address = ReserveRegion(request_size);
1303 if (address == NULL) return;
1304 Address base = RoundUp(static_cast<Address>(address), alignment);
1305 // Try reducing the size by freeing and then reallocating a specific area.
1306 bool result = ReleaseRegion(address, request_size);
1309 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1310 if (address != NULL) {
1311 request_size = size;
1312 ASSERT(base == static_cast<Address>(address));
1314 // Resizing failed, just go with a bigger area.
1315 address = ReserveRegion(request_size);
1316 if (address == NULL) return;
1319 size_ = request_size;
1323 VirtualMemory::~VirtualMemory() {
1325 bool result = ReleaseRegion(address(), size());
1332 bool VirtualMemory::IsReserved() {
1333 return address_ != NULL;
1337 void VirtualMemory::Reset() {
1343 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1344 return CommitRegion(address, size, is_executable);
1348 bool VirtualMemory::Uncommit(void* address, size_t size) {
1349 ASSERT(IsReserved());
1350 return UncommitRegion(address, size);
1354 bool VirtualMemory::Guard(void* address) {
1355 if (NULL == VirtualAlloc(address,
1356 OS::CommitPageSize(),
1365 void* VirtualMemory::ReserveRegion(size_t size) {
1366 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
1370 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1371 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1372 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1379 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1380 return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1384 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1385 return VirtualFree(base, 0, MEM_RELEASE) != 0;
1389 bool VirtualMemory::HasLazyCommits() {
1390 // TODO(alph): implement for the platform.
1395 // ----------------------------------------------------------------------------
1396 // Win32 thread support.
1398 // Definition of invalid thread handle and id.
1399 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
1401 // Entry point for threads. The supplied argument is a pointer to the thread
1402 // object. The entry function dispatches to the run method in the thread
1403 // object. It is important that this function has __stdcall calling
1405 static unsigned int __stdcall ThreadEntry(void* arg) {
1406 Thread* thread = reinterpret_cast<Thread*>(arg);
1407 thread->NotifyStartedAndRun();
1412 class Thread::PlatformData : public Malloced {
1414 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1416 unsigned thread_id_;
1420 // Initialize a Win32 thread object. The thread has an invalid thread
1421 // handle until it is started.
1423 Thread::Thread(const Options& options)
1424 : stack_size_(options.stack_size()),
1425 start_semaphore_(NULL) {
1426 data_ = new PlatformData(kNoThread);
1427 set_name(options.name());
1431 void Thread::set_name(const char* name) {
1432 OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
1433 name_[sizeof(name_) - 1] = '\0';
1437 // Close our own handle for the thread.
1439 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1444 // Create a new thread. It is important to use _beginthreadex() instead of
1445 // the Win32 function CreateThread(), because the CreateThread() does not
1446 // initialize thread specific structures in the C runtime library.
1447 void Thread::Start() {
1448 data_->thread_ = reinterpret_cast<HANDLE>(
1449 _beginthreadex(NULL,
1450 static_cast<unsigned>(stack_size_),
1454 &data_->thread_id_));
1458 // Wait for thread to terminate.
1459 void Thread::Join() {
1460 if (data_->thread_id_ != GetCurrentThreadId()) {
1461 WaitForSingleObject(data_->thread_, INFINITE);
1466 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1467 DWORD result = TlsAlloc();
1468 ASSERT(result != TLS_OUT_OF_INDEXES);
1469 return static_cast<LocalStorageKey>(result);
1473 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1474 BOOL result = TlsFree(static_cast<DWORD>(key));
1480 void* Thread::GetThreadLocal(LocalStorageKey key) {
1481 return TlsGetValue(static_cast<DWORD>(key));
1485 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1486 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1493 void Thread::YieldCPU() {
1497 } } // namespace v8::internal