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
20 #include "src/base/win32-headers.h"
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"
30 // Extra functions for MinGW. Most of these are the _s functions which are in
31 // the Microsoft Visual Studio C++ CRT.
35 #ifndef __MINGW64_VERSION_MAJOR
40 inline void MemoryBarrier() {
42 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
45 #endif // __MINGW64_VERSION_MAJOR
48 int localtime_s(tm* out_tm, const time_t* time) {
49 tm* posix_local_time_struct = localtime(time);
50 if (posix_local_time_struct == NULL) return 1;
51 *out_tm = *posix_local_time_struct;
56 int fopen_s(FILE** pFile, const char* filename, const char* mode) {
57 *pFile = fopen(filename, mode);
58 return *pFile != NULL ? 0 : 1;
61 int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
62 const char* format, va_list argptr) {
63 DCHECK(count == _TRUNCATE);
64 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
68 int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
69 CHECK(source != NULL);
71 CHECK_GT(dest_size, 0);
73 if (count == _TRUNCATE) {
74 while (dest_size > 0 && *source != 0) {
75 *(dest++) = *(source++);
83 while (dest_size > 0 && count > 0 && *source != 0) {
84 *(dest++) = *(source++);
89 CHECK_GT(dest_size, 0);
101 bool g_hard_abort = false;
105 class TimezoneCache {
107 TimezoneCache() : initialized_(false) { }
110 initialized_ = false;
113 // Initialize timezone information. The timezone information is obtained from
114 // windows. If we cannot get the timezone information we fall back to CET.
115 void InitializeIfNeeded() {
116 // Just return if timezone information has already been initialized.
117 if (initialized_) return;
119 // Initialize POSIX time zone data.
121 // Obtain timezone information from operating system.
122 memset(&tzinfo_, 0, sizeof(tzinfo_));
123 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
124 // If we cannot get timezone information we fall back to CET.
126 tzinfo_.StandardDate.wMonth = 10;
127 tzinfo_.StandardDate.wDay = 5;
128 tzinfo_.StandardDate.wHour = 3;
129 tzinfo_.StandardBias = 0;
130 tzinfo_.DaylightDate.wMonth = 3;
131 tzinfo_.DaylightDate.wDay = 5;
132 tzinfo_.DaylightDate.wHour = 2;
133 tzinfo_.DaylightBias = -60;
136 // Make standard and DST timezone names.
137 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
138 std_tz_name_, kTzNameSize, NULL, NULL);
139 std_tz_name_[kTzNameSize - 1] = '\0';
140 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
141 dst_tz_name_, kTzNameSize, NULL, NULL);
142 dst_tz_name_[kTzNameSize - 1] = '\0';
144 // If OS returned empty string or resource id (like "@tzres.dll,-211")
145 // simply guess the name from the UTC bias of the timezone.
146 // To properly resolve the resource identifier requires a library load,
147 // which is not possible in a sandbox.
148 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
149 OS::SNPrintF(std_tz_name_, kTzNameSize - 1,
151 GuessTimezoneNameFromBias(tzinfo_.Bias));
153 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
154 OS::SNPrintF(dst_tz_name_, kTzNameSize - 1,
156 GuessTimezoneNameFromBias(tzinfo_.Bias));
158 // Timezone information initialized.
162 // Guess the name of the timezone from the bias.
163 // The guess is very biased towards the northern hemisphere.
164 const char* GuessTimezoneNameFromBias(int bias) {
165 static const int kHour = 60;
167 case -9*kHour: return "Alaska";
168 case -8*kHour: return "Pacific";
169 case -7*kHour: return "Mountain";
170 case -6*kHour: return "Central";
171 case -5*kHour: return "Eastern";
172 case -4*kHour: return "Atlantic";
173 case 0*kHour: return "GMT";
174 case +1*kHour: return "Central Europe";
175 case +2*kHour: return "Eastern Europe";
176 case +3*kHour: return "Russia";
177 case +5*kHour + 30: return "India";
178 case +8*kHour: return "China";
179 case +9*kHour: return "Japan";
180 case +12*kHour: return "New Zealand";
181 default: return "Local";
187 static const int kTzNameSize = 128;
189 char std_tz_name_[kTzNameSize];
190 char dst_tz_name_[kTzNameSize];
191 TIME_ZONE_INFORMATION tzinfo_;
192 friend class Win32Time;
196 // ----------------------------------------------------------------------------
197 // The Time class represents time on win32. A timestamp is represented as
198 // a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
199 // timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
206 explicit Win32Time(double jstime);
207 Win32Time(int year, int mon, int day, int hour, int min, int sec);
209 // Convert timestamp to JavaScript representation.
212 // Set timestamp to current time.
213 void SetToCurrentTime();
215 // Returns the local timezone offset in milliseconds east of UTC. This is
216 // the number of milliseconds you must add to UTC to get local time, i.e.
217 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
218 // routine also takes into account whether daylight saving is effect
220 int64_t LocalOffset(TimezoneCache* cache);
222 // Returns the daylight savings time offset for the time in milliseconds.
223 int64_t DaylightSavingsOffset(TimezoneCache* cache);
225 // Returns a string identifying the current timezone for the
226 // timestamp taking into account daylight saving.
227 char* LocalTimezone(TimezoneCache* cache);
230 // Constants for time conversion.
231 static const int64_t kTimeEpoc = 116444736000000000LL;
232 static const int64_t kTimeScaler = 10000;
233 static const int64_t kMsPerMinute = 60000;
235 // Constants for timezone information.
236 static const bool kShortTzNames = false;
238 // Return whether or not daylight savings time is in effect at this time.
239 bool InDST(TimezoneCache* cache);
241 // Accessor for FILETIME representation.
242 FILETIME& ft() { return time_.ft_; }
244 // Accessor for integer representation.
245 int64_t& t() { return time_.t_; }
247 // Although win32 uses 64-bit integers for representing timestamps,
248 // these are packed into a FILETIME structure. The FILETIME structure
249 // is just a struct representing a 64-bit integer. The TimeStamp union
250 // allows access to both a FILETIME and an integer representation of
261 // Initialize timestamp to start of epoc.
262 Win32Time::Win32Time() {
267 // Initialize timestamp from a JavaScript timestamp.
268 Win32Time::Win32Time(double jstime) {
269 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
273 // Initialize timestamp from date/time components.
274 Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
282 st.wMilliseconds = 0;
283 SystemTimeToFileTime(&st, &ft());
287 // Convert timestamp to JavaScript timestamp.
288 double Win32Time::ToJSTime() {
289 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
293 // Set timestamp to current time.
294 void Win32Time::SetToCurrentTime() {
295 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
296 // Because we're fast, we like fast timers which have at least a
299 // timeGetTime() provides 1ms granularity when combined with
300 // timeBeginPeriod(). If the host application for v8 wants fast
301 // timers, it can use timeBeginPeriod to increase the resolution.
303 // Using timeGetTime() has a drawback because it is a 32bit value
304 // and hence rolls-over every ~49days.
306 // To use the clock, we use GetSystemTimeAsFileTime as our base;
307 // and then use timeGetTime to extrapolate current time from the
308 // start time. To deal with rollovers, we resync the clock
309 // any time when more than kMaxClockElapsedTime has passed or
310 // whenever timeGetTime creates a rollover.
312 static bool initialized = false;
313 static TimeStamp init_time;
314 static DWORD init_ticks;
315 static const int64_t kHundredNanosecondsPerSecond = 10000000;
316 static const int64_t kMaxClockElapsedTime =
317 60*kHundredNanosecondsPerSecond; // 1 minute
319 // If we are uninitialized, we need to resync the clock.
320 bool needs_resync = !initialized;
322 // Get the current time.
324 GetSystemTimeAsFileTime(&time_now.ft_);
325 DWORD ticks_now = timeGetTime();
327 // Check if we need to resync due to clock rollover.
328 needs_resync |= ticks_now < init_ticks;
330 // Check if we need to resync due to elapsed time.
331 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
333 // Check if we need to resync due to backwards time change.
334 needs_resync |= time_now.t_ < init_time.t_;
336 // Resync the clock if necessary.
338 GetSystemTimeAsFileTime(&init_time.ft_);
339 init_ticks = ticks_now = timeGetTime();
343 // Finally, compute the actual time. Why is this so hard.
344 DWORD elapsed = ticks_now - init_ticks;
345 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
349 // Return the local timezone offset in milliseconds east of UTC. This
350 // takes into account whether daylight saving is in effect at the time.
351 // Only times in the 32-bit Unix range may be passed to this function.
352 // Also, adding the time-zone offset to the input must not overflow.
353 // The function EquivalentTime() in date.js guarantees this.
354 int64_t Win32Time::LocalOffset(TimezoneCache* cache) {
355 cache->InitializeIfNeeded();
357 Win32Time rounded_to_second(*this);
358 rounded_to_second.t() =
359 rounded_to_second.t() / 1000 / kTimeScaler * 1000 * kTimeScaler;
360 // Convert to local time using POSIX localtime function.
361 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
362 // very slow. Other browsers use localtime().
364 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
365 // POSIX seconds past 1/1/1970 0:00:00.
366 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
367 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
370 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
371 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
373 // Convert to local time, as struct with fields for day, hour, year, etc.
374 tm posix_local_time_struct;
375 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
377 if (posix_local_time_struct.tm_isdst > 0) {
378 return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
379 } else if (posix_local_time_struct.tm_isdst == 0) {
380 return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
382 return cache->tzinfo_.Bias * -kMsPerMinute;
387 // Return whether or not daylight savings time is in effect at this time.
388 bool Win32Time::InDST(TimezoneCache* cache) {
389 cache->InitializeIfNeeded();
391 // Determine if DST is in effect at the specified time.
393 if (cache->tzinfo_.StandardDate.wMonth != 0 ||
394 cache->tzinfo_.DaylightDate.wMonth != 0) {
395 // Get the local timezone offset for the timestamp in milliseconds.
396 int64_t offset = LocalOffset(cache);
398 // Compute the offset for DST. The bias parameters in the timezone info
399 // are specified in minutes. These must be converted to milliseconds.
401 -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
403 // If the local time offset equals the timezone bias plus the daylight
404 // bias then DST is in effect.
405 in_dst = offset == dstofs;
412 // Return the daylight savings time offset for this time.
413 int64_t Win32Time::DaylightSavingsOffset(TimezoneCache* cache) {
414 return InDST(cache) ? 60 * kMsPerMinute : 0;
418 // Returns a string identifying the current timezone for the
419 // timestamp taking into account daylight saving.
420 char* Win32Time::LocalTimezone(TimezoneCache* cache) {
421 // Return the standard or DST time zone name based on whether daylight
422 // saving is in effect at the given time.
423 return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
427 // Returns the accumulated user time for thread.
428 int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
432 // Get the amount of time that the thread has executed in user mode.
433 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
434 reinterpret_cast<FILETIME*>(&usertime))) return -1;
436 // Adjust the resolution to micro-seconds.
439 // Convert to seconds and microseconds
440 *secs = static_cast<uint32_t>(usertime / 1000000);
441 *usecs = static_cast<uint32_t>(usertime % 1000000);
446 // Returns current time as the number of milliseconds since
447 // 00:00:00 UTC, January 1, 1970.
448 double OS::TimeCurrentMillis() {
449 return Time::Now().ToJsTime();
453 TimezoneCache* OS::CreateTimezoneCache() {
454 return new TimezoneCache();
458 void OS::DisposeTimezoneCache(TimezoneCache* cache) {
463 void OS::ClearTimezoneCache(TimezoneCache* cache) {
468 // Returns a string identifying the current timezone taking into
469 // account daylight saving.
470 const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
471 return Win32Time(time).LocalTimezone(cache);
475 // Returns the local time offset in milliseconds east of UTC without
476 // taking daylight savings time into account.
477 double OS::LocalTimeOffset(TimezoneCache* cache) {
478 // Use current time, rounded to the millisecond.
479 Win32Time t(TimeCurrentMillis());
480 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
481 return static_cast<double>(t.LocalOffset(cache) -
482 t.DaylightSavingsOffset(cache));
486 // Returns the daylight savings offset in milliseconds for the given
488 double OS::DaylightSavingsOffset(double time, TimezoneCache* cache) {
489 int64_t offset = Win32Time(time).DaylightSavingsOffset(cache);
490 return static_cast<double>(offset);
494 int OS::GetLastError() {
495 return ::GetLastError();
499 int OS::GetCurrentProcessId() {
500 return static_cast<int>(::GetCurrentProcessId());
504 int OS::GetCurrentThreadId() {
505 return static_cast<int>(::GetCurrentThreadId());
509 // ----------------------------------------------------------------------------
510 // Win32 console output.
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.
522 UNKNOWN, // Output method has not yet been determined.
523 CONSOLE, // Output is written to stdout.
524 ODS // Output is written to debug facility.
527 static OutputMode output_mode = UNKNOWN; // Current output mode.
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;
545 return output_mode == CONSOLE;
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
555 OS::VSNPrintF(buffer, sizeof(buffer), format, args);
556 OutputDebugStringA(buffer);
558 vfprintf(stream, format, args);
563 FILE* OS::FOpen(const char* path, const char* mode) {
565 if (fopen_s(&result, path, mode) == 0) {
573 bool OS::Remove(const char* path) {
574 return (DeleteFileA(path) != 0);
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.
596 // Open log file in binary mode to avoid /n -> /r/n conversion.
597 const char* const OS::LogFileOpenMode = "wb";
600 // Print (debug) message to console.
601 void OS::Print(const char* format, ...) {
603 va_start(args, format);
604 VPrint(format, args);
609 void OS::VPrint(const char* format, va_list args) {
610 VPrintHelper(stdout, format, args);
614 void OS::FPrint(FILE* out, const char* format, ...) {
616 va_start(args, format);
617 VFPrint(out, format, args);
622 void OS::VFPrint(FILE* out, const char* format, va_list args) {
623 VPrintHelper(out, format, args);
627 // Print error message to console.
628 void OS::PrintError(const char* format, ...) {
630 va_start(args, format);
631 VPrintError(format, args);
636 void OS::VPrintError(const char* format, va_list args) {
637 VPrintHelper(stderr, format, args);
641 int OS::SNPrintF(char* str, int length, const char* format, ...) {
643 va_start(args, format);
644 int result = VSNPrintF(str, length, format, args);
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) {
656 str[length - 1] = '\0';
664 char* OS::StrChr(char* str, int c) {
665 return const_cast<char*>(strchr(str, c));
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'
674 int result = strncpy_s(dest, length, src, n);
676 DCHECK(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
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) {
691 GetSystemInfo(&info);
692 page_size = base::bits::RoundUpToPowerOfTwo32(info.dwPageSize);
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) {
704 GetSystemInfo(&info);
705 allocate_alignment = info.dwAllocationGranularity;
707 return allocate_alignment;
711 static LazyInstance<RandomNumberGenerator>::type
712 platform_random_number_generator = LAZY_INSTANCE_INITIALIZER;
715 void OS::Initialize(int64_t random_seed, bool hard_abort,
716 const char* const gc_fake_mmap) {
718 platform_random_number_generator.Pointer()->SetSeed(random_seed);
720 g_hard_abort = hard_abort;
724 void* OS::GetRandomMmapAddr() {
725 // The address range used to randomize RWX allocations in OS::Allocate
726 // Try not to map pages into the default range that windows loads DLLs
727 // Use a multiple of 64k to prevent committing unused memory.
728 // Note: This does not guarantee RWX regions will be within the
729 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
730 #ifdef V8_HOST_ARCH_64_BIT
731 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
732 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
734 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
735 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
738 (platform_random_number_generator.Pointer()->NextInt() << kPageSizeBits) |
739 kAllocationRandomAddressMin;
740 address &= kAllocationRandomAddressMax;
741 return reinterpret_cast<void *>(address);
745 static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
748 if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
749 // For exectutable pages try and randomize the allocation address
750 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
751 base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection);
755 // After three attempts give up and let the OS find an address to use.
756 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
762 void* OS::Allocate(const size_t requested,
764 bool is_executable) {
765 // VirtualAlloc rounds allocated size to page size automatically.
766 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
768 // Windows XP SP2 allows Data Excution Prevention (DEP).
769 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
771 LPVOID mbase = RandomizedVirtualAlloc(msize,
772 MEM_COMMIT | MEM_RESERVE,
775 if (mbase == NULL) return NULL;
777 DCHECK((reinterpret_cast<uintptr_t>(mbase) % OS::AllocateAlignment()) == 0);
784 void OS::Free(void* address, const size_t size) {
785 // TODO(1240712): VirtualFree has a return value which is ignored here.
786 VirtualFree(address, 0, MEM_RELEASE);
791 intptr_t OS::CommitPageSize() {
796 void OS::ProtectCode(void* address, const size_t size) {
798 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
802 void OS::Guard(void* address, const size_t size) {
804 VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect);
808 void OS::Sleep(int milliseconds) {
809 ::Sleep(milliseconds);
815 V8_IMMEDIATE_CRASH();
817 // Make the MSVCRT do a silent abort.
822 void OS::DebugBreak() {
824 // To avoid Visual Studio runtime support the following code can be used
834 class Win32MemoryMappedFile : public OS::MemoryMappedFile {
836 Win32MemoryMappedFile(HANDLE file,
841 file_mapping_(file_mapping),
844 virtual ~Win32MemoryMappedFile();
845 virtual void* memory() { return memory_; }
846 virtual int size() { return size_; }
849 HANDLE file_mapping_;
855 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
856 // Open a physical file
857 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
858 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
859 if (file == INVALID_HANDLE_VALUE) return NULL;
861 int size = static_cast<int>(GetFileSize(file, NULL));
863 // Create a file mapping for the physical file
864 HANDLE file_mapping = CreateFileMapping(file, NULL,
865 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
866 if (file_mapping == NULL) return NULL;
868 // Map a view of the file into memory
869 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
870 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
874 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
876 // Open a physical file
877 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
878 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
879 if (file == NULL) return NULL;
880 // Create a file mapping for the physical file
881 HANDLE file_mapping = CreateFileMapping(file, NULL,
882 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
883 if (file_mapping == NULL) return NULL;
884 // Map a view of the file into memory
885 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
886 if (memory) memmove(memory, initial, size);
887 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
891 Win32MemoryMappedFile::~Win32MemoryMappedFile() {
893 UnmapViewOfFile(memory_);
894 CloseHandle(file_mapping_);
899 // The following code loads functions defined in DbhHelp.h and TlHelp32.h
900 // dynamically. This is to avoid being depending on dbghelp.dll and
901 // tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
902 // kernel32.dll at some point so loading functions defines in TlHelp32.h
903 // dynamically might not be necessary any more - for some versions of Windows?).
905 // Function pointers to functions dynamically loaded from dbghelp.dll.
906 #define DBGHELP_FUNCTION_LIST(V) \
910 V(SymGetSearchPath) \
913 V(SymGetSymFromAddr64) \
914 V(SymGetLineFromAddr64) \
915 V(SymFunctionTableAccess64) \
916 V(SymGetModuleBase64)
918 // Function pointers to functions dynamically loaded from dbghelp.dll.
919 #define TLHELP32_FUNCTION_LIST(V) \
920 V(CreateToolhelp32Snapshot) \
924 // Define the decoration to use for the type and variable name used for
925 // dynamically loaded DLL function..
926 #define DLL_FUNC_TYPE(name) _##name##_
927 #define DLL_FUNC_VAR(name) _##name
929 // Define the type for each dynamically loaded DLL function. The function
930 // definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
931 // from the Windows include files are redefined here to have the function
932 // definitions to be as close to the ones in the original .h files as possible.
940 // DbgHelp isn't supported on MinGW yet
942 // DbgHelp.h functions.
943 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
944 IN PSTR UserSearchPath,
945 IN BOOL fInvadeProcess);
946 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
947 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
948 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
951 IN DWORD SearchPathLength);
952 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
957 IN DWORD64 BaseOfDll,
959 typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
963 LPSTACKFRAME64 StackFrame,
965 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
966 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
967 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
968 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
969 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
972 OUT PDWORD64 pdwDisplacement,
973 OUT PIMAGEHLP_SYMBOL64 Symbol);
974 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
977 OUT PDWORD pdwDisplacement,
978 OUT PIMAGEHLP_LINE64 Line64);
979 // DbgHelp.h typedefs. Implementation found in dbghelp.dll.
980 typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
982 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
983 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
985 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
987 // TlHelp32.h functions.
988 typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
990 DWORD th32ProcessID);
991 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
992 LPMODULEENTRY32W lpme);
993 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
994 LPMODULEENTRY32W lpme);
999 // Declare a variable for each dynamically loaded DLL function.
1000 #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1001 DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1002 TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1003 #undef DEF_DLL_FUNCTION
1005 // Load the functions. This function has a lot of "ugly" macros in order to
1006 // keep down code duplication.
1008 static bool LoadDbgHelpAndTlHelp32() {
1009 static bool dbghelp_loaded = false;
1011 if (dbghelp_loaded) return true;
1015 // Load functions from the dbghelp.dll module.
1016 module = LoadLibrary(TEXT("dbghelp.dll"));
1017 if (module == NULL) {
1021 #define LOAD_DLL_FUNC(name) \
1022 DLL_FUNC_VAR(name) = \
1023 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1025 DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1027 #undef LOAD_DLL_FUNC
1029 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1030 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1031 module = LoadLibrary(TEXT("kernel32.dll"));
1032 if (module == NULL) {
1036 #define LOAD_DLL_FUNC(name) \
1037 DLL_FUNC_VAR(name) = \
1038 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1040 TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1042 #undef LOAD_DLL_FUNC
1044 // Check that all functions where loaded.
1046 #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1048 DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1049 TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1051 #undef DLL_FUNC_LOADED
1054 dbghelp_loaded = result;
1056 // NOTE: The modules are never unloaded and will stay around until the
1057 // application is closed.
1060 #undef DBGHELP_FUNCTION_LIST
1061 #undef TLHELP32_FUNCTION_LIST
1063 #undef DLL_FUNC_TYPE
1066 // Load the symbols for generating stack traces.
1067 static std::vector<OS::SharedLibraryAddress> LoadSymbols(
1068 HANDLE process_handle) {
1069 static std::vector<OS::SharedLibraryAddress> result;
1071 static bool symbols_loaded = false;
1073 if (symbols_loaded) return result;
1077 // Initialize the symbol engine.
1078 ok = _SymInitialize(process_handle, // hProcess
1079 NULL, // UserSearchPath
1080 false); // fInvadeProcess
1081 if (!ok) return result;
1083 DWORD options = _SymGetOptions();
1084 options |= SYMOPT_LOAD_LINES;
1085 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1086 options = _SymSetOptions(options);
1088 char buf[OS::kStackWalkMaxNameLen] = {0};
1089 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1091 int err = GetLastError();
1092 OS::Print("%d\n", err);
1096 HANDLE snapshot = _CreateToolhelp32Snapshot(
1097 TH32CS_SNAPMODULE, // dwFlags
1098 GetCurrentProcessId()); // th32ProcessId
1099 if (snapshot == INVALID_HANDLE_VALUE) return result;
1100 MODULEENTRY32W module_entry;
1101 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1102 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1105 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1106 // both unicode and ASCII strings even though the parameter is PSTR.
1107 base = _SymLoadModule64(
1108 process_handle, // hProcess
1110 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1111 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1112 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1113 module_entry.modBaseSize); // SizeOfDll
1115 int err = GetLastError();
1116 if (err != ERROR_MOD_NOT_FOUND &&
1117 err != ERROR_INVALID_HANDLE) {
1122 int lib_name_length = WideCharToMultiByte(
1123 CP_UTF8, 0, module_entry.szExePath, -1, NULL, 0, NULL, NULL);
1124 std::string lib_name(lib_name_length, 0);
1125 WideCharToMultiByte(CP_UTF8, 0, module_entry.szExePath, -1, &lib_name[0],
1126 lib_name_length, NULL, NULL);
1127 result.push_back(OS::SharedLibraryAddress(
1128 lib_name, reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1129 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1130 module_entry.modBaseSize)));
1131 cont = _Module32NextW(snapshot, &module_entry);
1133 CloseHandle(snapshot);
1135 symbols_loaded = true;
1140 std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
1141 // SharedLibraryEvents are logged when loading symbol information.
1142 // Only the shared libraries loaded at the time of the call to
1143 // GetSharedLibraryAddresses are logged. DLLs loaded after
1144 // initialization are not accounted for.
1145 if (!LoadDbgHelpAndTlHelp32()) return std::vector<OS::SharedLibraryAddress>();
1146 HANDLE process_handle = GetCurrentProcess();
1147 return LoadSymbols(process_handle);
1151 void OS::SignalCodeMovingGC() {
1155 #else // __MINGW32__
1156 std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
1157 return std::vector<OS::SharedLibraryAddress>();
1161 void OS::SignalCodeMovingGC() { }
1162 #endif // __MINGW32__
1165 int OS::ActivationFrameAlignment() {
1167 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1168 #elif defined(__MINGW32__)
1169 // With gcc 4.4 the tree vectorization optimizer can generate code
1170 // that requires 16 byte alignment such as movdqa on x86.
1173 return 8; // Floating-point math runs faster with 8-byte alignment.
1178 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
1181 VirtualMemory::VirtualMemory(size_t size)
1182 : address_(ReserveRegion(size)), size_(size) { }
1185 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1186 : address_(NULL), size_(0) {
1187 DCHECK((alignment % OS::AllocateAlignment()) == 0);
1188 size_t request_size = RoundUp(size + alignment,
1189 static_cast<intptr_t>(OS::AllocateAlignment()));
1190 void* address = ReserveRegion(request_size);
1191 if (address == NULL) return;
1192 uint8_t* base = RoundUp(static_cast<uint8_t*>(address), alignment);
1193 // Try reducing the size by freeing and then reallocating a specific area.
1194 bool result = ReleaseRegion(address, request_size);
1197 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1198 if (address != NULL) {
1199 request_size = size;
1200 DCHECK(base == static_cast<uint8_t*>(address));
1202 // Resizing failed, just go with a bigger area.
1203 address = ReserveRegion(request_size);
1204 if (address == NULL) return;
1207 size_ = request_size;
1211 VirtualMemory::~VirtualMemory() {
1213 bool result = ReleaseRegion(address(), size());
1220 bool VirtualMemory::IsReserved() {
1221 return address_ != NULL;
1225 void VirtualMemory::Reset() {
1231 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1232 return CommitRegion(address, size, is_executable);
1236 bool VirtualMemory::Uncommit(void* address, size_t size) {
1237 DCHECK(IsReserved());
1238 return UncommitRegion(address, size);
1242 bool VirtualMemory::Guard(void* address) {
1243 if (NULL == VirtualAlloc(address,
1244 OS::CommitPageSize(),
1253 void* VirtualMemory::ReserveRegion(size_t size) {
1254 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
1258 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1259 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1260 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1267 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1268 return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1272 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1273 return VirtualFree(base, 0, MEM_RELEASE) != 0;
1277 bool VirtualMemory::HasLazyCommits() {
1278 // TODO(alph): implement for the platform.
1283 // ----------------------------------------------------------------------------
1284 // Win32 thread support.
1286 // Definition of invalid thread handle and id.
1287 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
1289 // Entry point for threads. The supplied argument is a pointer to the thread
1290 // object. The entry function dispatches to the run method in the thread
1291 // object. It is important that this function has __stdcall calling
1293 static unsigned int __stdcall ThreadEntry(void* arg) {
1294 Thread* thread = reinterpret_cast<Thread*>(arg);
1295 thread->NotifyStartedAndRun();
1300 class Thread::PlatformData {
1302 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1304 unsigned thread_id_;
1308 // Initialize a Win32 thread object. The thread has an invalid thread
1309 // handle until it is started.
1311 Thread::Thread(const Options& options)
1312 : stack_size_(options.stack_size()),
1313 start_semaphore_(NULL) {
1314 data_ = new PlatformData(kNoThread);
1315 set_name(options.name());
1319 void Thread::set_name(const char* name) {
1320 OS::StrNCpy(name_, sizeof(name_), name, strlen(name));
1321 name_[sizeof(name_) - 1] = '\0';
1325 // Close our own handle for the thread.
1327 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1332 // Create a new thread. It is important to use _beginthreadex() instead of
1333 // the Win32 function CreateThread(), because the CreateThread() does not
1334 // initialize thread specific structures in the C runtime library.
1335 void Thread::Start() {
1336 data_->thread_ = reinterpret_cast<HANDLE>(
1337 _beginthreadex(NULL,
1338 static_cast<unsigned>(stack_size_),
1342 &data_->thread_id_));
1346 // Wait for thread to terminate.
1347 void Thread::Join() {
1348 if (data_->thread_id_ != GetCurrentThreadId()) {
1349 WaitForSingleObject(data_->thread_, INFINITE);
1354 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1355 DWORD result = TlsAlloc();
1356 DCHECK(result != TLS_OUT_OF_INDEXES);
1357 return static_cast<LocalStorageKey>(result);
1361 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1362 BOOL result = TlsFree(static_cast<DWORD>(key));
1368 void* Thread::GetThreadLocal(LocalStorageKey key) {
1369 return TlsGetValue(static_cast<DWORD>(key));
1373 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1374 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1381 void Thread::YieldCPU() {
1385 } } // namespace v8::base