• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <windows.h>
19 
20 // This has to come after windows.h.
21 #include <VersionHelpers.h>
22 #include <dbghelp.h>   // For SymLoadModule64 and al.
23 #include <mmsystem.h>  // For timeGetTime().
24 #include <tlhelp32.h>  // For Module32First and al.
25 
26 #include <limits>
27 
28 #include "src/base/bits.h"
29 #include "src/base/lazy-instance.h"
30 #include "src/base/macros.h"
31 #include "src/base/platform/platform.h"
32 #include "src/base/platform/time.h"
33 #include "src/base/timezone-cache.h"
34 #include "src/base/utils/random-number-generator.h"
35 #include "src/base/win32-headers.h"
36 
37 #if defined(_MSC_VER)
38 #include <crtdbg.h>
39 #endif               // defined(_MSC_VER)
40 
41 // Check that type sizes and alignments match.
42 STATIC_ASSERT(sizeof(V8_CONDITION_VARIABLE) == sizeof(CONDITION_VARIABLE));
43 STATIC_ASSERT(alignof(V8_CONDITION_VARIABLE) == alignof(CONDITION_VARIABLE));
44 STATIC_ASSERT(sizeof(V8_SRWLOCK) == sizeof(SRWLOCK));
45 STATIC_ASSERT(alignof(V8_SRWLOCK) == alignof(SRWLOCK));
46 STATIC_ASSERT(sizeof(V8_CRITICAL_SECTION) == sizeof(CRITICAL_SECTION));
47 STATIC_ASSERT(alignof(V8_CRITICAL_SECTION) == alignof(CRITICAL_SECTION));
48 
49 // Check that CRITICAL_SECTION offsets match.
50 STATIC_ASSERT(offsetof(V8_CRITICAL_SECTION, DebugInfo) ==
51               offsetof(CRITICAL_SECTION, DebugInfo));
52 STATIC_ASSERT(offsetof(V8_CRITICAL_SECTION, LockCount) ==
53               offsetof(CRITICAL_SECTION, LockCount));
54 STATIC_ASSERT(offsetof(V8_CRITICAL_SECTION, RecursionCount) ==
55               offsetof(CRITICAL_SECTION, RecursionCount));
56 STATIC_ASSERT(offsetof(V8_CRITICAL_SECTION, OwningThread) ==
57               offsetof(CRITICAL_SECTION, OwningThread));
58 STATIC_ASSERT(offsetof(V8_CRITICAL_SECTION, LockSemaphore) ==
59               offsetof(CRITICAL_SECTION, LockSemaphore));
60 STATIC_ASSERT(offsetof(V8_CRITICAL_SECTION, SpinCount) ==
61               offsetof(CRITICAL_SECTION, SpinCount));
62 
63 // Extra functions for MinGW. Most of these are the _s functions which are in
64 // the Microsoft Visual Studio C++ CRT.
65 #ifdef __MINGW32__
66 
67 
68 #ifndef __MINGW64_VERSION_MAJOR
69 
70 #define _TRUNCATE 0
71 #define STRUNCATE 80
72 
MemoryFence()73 inline void MemoryFence() {
74   int barrier = 0;
75   __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
76 }
77 
78 #endif  // __MINGW64_VERSION_MAJOR
79 
80 
localtime_s(tm * out_tm,const time_t * time)81 int localtime_s(tm* out_tm, const time_t* time) {
82   tm* posix_local_time_struct = localtime_r(time, out_tm);
83   if (posix_local_time_struct == nullptr) return 1;
84   return 0;
85 }
86 
87 
fopen_s(FILE ** pFile,const char * filename,const char * mode)88 int fopen_s(FILE** pFile, const char* filename, const char* mode) {
89   *pFile = fopen(filename, mode);
90   return *pFile != nullptr ? 0 : 1;
91 }
92 
_wfopen_s(FILE ** pFile,const wchar_t * filename,const wchar_t * mode)93 int _wfopen_s(FILE** pFile, const wchar_t* filename, const wchar_t* mode) {
94   *pFile = _wfopen(filename, mode);
95   return *pFile != nullptr ? 0 : 1;
96 }
97 
_vsnprintf_s(char * buffer,size_t sizeOfBuffer,size_t count,const char * format,va_list argptr)98 int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
99                  const char* format, va_list argptr) {
100   DCHECK(count == _TRUNCATE);
101   return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
102 }
103 
104 
strncpy_s(char * dest,size_t dest_size,const char * source,size_t count)105 int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
106   CHECK(source != nullptr);
107   CHECK(dest != nullptr);
108   CHECK_GT(dest_size, 0);
109 
110   if (count == _TRUNCATE) {
111     while (dest_size > 0 && *source != 0) {
112       *(dest++) = *(source++);
113       --dest_size;
114     }
115     if (dest_size == 0) {
116       *(dest - 1) = 0;
117       return STRUNCATE;
118     }
119   } else {
120     while (dest_size > 0 && count > 0 && *source != 0) {
121       *(dest++) = *(source++);
122       --dest_size;
123       --count;
124     }
125   }
126   CHECK_GT(dest_size, 0);
127   *dest = 0;
128   return 0;
129 }
130 
131 #endif  // __MINGW32__
132 
133 namespace v8 {
134 namespace base {
135 
136 namespace {
137 
138 bool g_hard_abort = false;
139 
140 }  // namespace
141 
142 class WindowsTimezoneCache : public TimezoneCache {
143  public:
WindowsTimezoneCache()144   WindowsTimezoneCache() : initialized_(false) {}
145 
~WindowsTimezoneCache()146   ~WindowsTimezoneCache() override {}
147 
Clear(TimeZoneDetection)148   void Clear(TimeZoneDetection) override { initialized_ = false; }
149 
150   const char* LocalTimezone(double time) override;
151 
152   double LocalTimeOffset(double time, bool is_utc) override;
153 
154   double DaylightSavingsOffset(double time) override;
155 
156   // Initialize timezone information. The timezone information is obtained from
157   // windows. If we cannot get the timezone information we fall back to CET.
InitializeIfNeeded()158   void InitializeIfNeeded() {
159     // Just return if timezone information has already been initialized.
160     if (initialized_) return;
161 
162     // Initialize POSIX time zone data.
163     _tzset();
164     // Obtain timezone information from operating system.
165     memset(&tzinfo_, 0, sizeof(tzinfo_));
166     if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
167       // If we cannot get timezone information we fall back to CET.
168       tzinfo_.Bias = -60;
169       tzinfo_.StandardDate.wMonth = 10;
170       tzinfo_.StandardDate.wDay = 5;
171       tzinfo_.StandardDate.wHour = 3;
172       tzinfo_.StandardBias = 0;
173       tzinfo_.DaylightDate.wMonth = 3;
174       tzinfo_.DaylightDate.wDay = 5;
175       tzinfo_.DaylightDate.wHour = 2;
176       tzinfo_.DaylightBias = -60;
177     }
178 
179     // Make standard and DST timezone names.
180     WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1, std_tz_name_,
181                         kTzNameSize, nullptr, nullptr);
182     std_tz_name_[kTzNameSize - 1] = '\0';
183     WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1, dst_tz_name_,
184                         kTzNameSize, nullptr, nullptr);
185     dst_tz_name_[kTzNameSize - 1] = '\0';
186 
187     // If OS returned empty string or resource id (like "@tzres.dll,-211")
188     // simply guess the name from the UTC bias of the timezone.
189     // To properly resolve the resource identifier requires a library load,
190     // which is not possible in a sandbox.
191     if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
192       OS::SNPrintF(std_tz_name_, kTzNameSize - 1,
193                    "%s Standard Time",
194                    GuessTimezoneNameFromBias(tzinfo_.Bias));
195     }
196     if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
197       OS::SNPrintF(dst_tz_name_, kTzNameSize - 1,
198                    "%s Daylight Time",
199                    GuessTimezoneNameFromBias(tzinfo_.Bias));
200     }
201     // Timezone information initialized.
202     initialized_ = true;
203   }
204 
205   // Guess the name of the timezone from the bias.
206   // The guess is very biased towards the northern hemisphere.
GuessTimezoneNameFromBias(int bias)207   const char* GuessTimezoneNameFromBias(int bias) {
208     static const int kHour = 60;
209     switch (-bias) {
210       case -9*kHour: return "Alaska";
211       case -8*kHour: return "Pacific";
212       case -7*kHour: return "Mountain";
213       case -6*kHour: return "Central";
214       case -5*kHour: return "Eastern";
215       case -4*kHour: return "Atlantic";
216       case  0*kHour: return "GMT";
217       case +1*kHour: return "Central Europe";
218       case +2*kHour: return "Eastern Europe";
219       case +3*kHour: return "Russia";
220       case +5*kHour + 30: return "India";
221       case +8*kHour: return "China";
222       case +9*kHour: return "Japan";
223       case +12*kHour: return "New Zealand";
224       default: return "Local";
225     }
226   }
227 
228 
229  private:
230   static const int kTzNameSize = 128;
231   bool initialized_;
232   char std_tz_name_[kTzNameSize];
233   char dst_tz_name_[kTzNameSize];
234   TIME_ZONE_INFORMATION tzinfo_;
235   friend class Win32Time;
236 };
237 
238 
239 // ----------------------------------------------------------------------------
240 // The Time class represents time on win32. A timestamp is represented as
241 // a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
242 // timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
243 // January 1, 1970.
244 
245 class Win32Time {
246  public:
247   // Constructors.
248   Win32Time();
249   explicit Win32Time(double jstime);
250   Win32Time(int year, int mon, int day, int hour, int min, int sec);
251 
252   // Convert timestamp to JavaScript representation.
253   double ToJSTime();
254 
255   // Set timestamp to current time.
256   void SetToCurrentTime();
257 
258   // Returns the local timezone offset in milliseconds east of UTC. This is
259   // the number of milliseconds you must add to UTC to get local time, i.e.
260   // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
261   // routine also takes into account whether daylight saving is effect
262   // at the time.
263   int64_t LocalOffset(WindowsTimezoneCache* cache);
264 
265   // Returns the daylight savings time offset for the time in milliseconds.
266   int64_t DaylightSavingsOffset(WindowsTimezoneCache* cache);
267 
268   // Returns a string identifying the current timezone for the
269   // timestamp taking into account daylight saving.
270   char* LocalTimezone(WindowsTimezoneCache* cache);
271 
272  private:
273   // Constants for time conversion.
274   static const int64_t kTimeEpoc = 116444736000000000LL;
275   static const int64_t kTimeScaler = 10000;
276   static const int64_t kMsPerMinute = 60000;
277 
278   // Constants for timezone information.
279   static const bool kShortTzNames = false;
280 
281   // Return whether or not daylight savings time is in effect at this time.
282   bool InDST(WindowsTimezoneCache* cache);
283 
284   // Accessor for FILETIME representation.
ft()285   FILETIME& ft() { return time_.ft_; }
286 
287   // Accessor for integer representation.
t()288   int64_t& t() { return time_.t_; }
289 
290   // Although win32 uses 64-bit integers for representing timestamps,
291   // these are packed into a FILETIME structure. The FILETIME structure
292   // is just a struct representing a 64-bit integer. The TimeStamp union
293   // allows access to both a FILETIME and an integer representation of
294   // the timestamp.
295   union TimeStamp {
296     FILETIME ft_;
297     int64_t t_;
298   };
299 
300   TimeStamp time_;
301 };
302 
303 
304 // Initialize timestamp to start of epoc.
Win32Time()305 Win32Time::Win32Time() {
306   t() = 0;
307 }
308 
309 
310 // Initialize timestamp from a JavaScript timestamp.
Win32Time(double jstime)311 Win32Time::Win32Time(double jstime) {
312   t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
313 }
314 
315 
316 // Initialize timestamp from date/time components.
Win32Time(int year,int mon,int day,int hour,int min,int sec)317 Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
318   SYSTEMTIME st;
319   st.wYear = year;
320   st.wMonth = mon;
321   st.wDay = day;
322   st.wHour = hour;
323   st.wMinute = min;
324   st.wSecond = sec;
325   st.wMilliseconds = 0;
326   SystemTimeToFileTime(&st, &ft());
327 }
328 
329 
330 // Convert timestamp to JavaScript timestamp.
ToJSTime()331 double Win32Time::ToJSTime() {
332   return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
333 }
334 
335 
336 // Set timestamp to current time.
SetToCurrentTime()337 void Win32Time::SetToCurrentTime() {
338   // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
339   // Because we're fast, we like fast timers which have at least a
340   // 1ms resolution.
341   //
342   // timeGetTime() provides 1ms granularity when combined with
343   // timeBeginPeriod().  If the host application for v8 wants fast
344   // timers, it can use timeBeginPeriod to increase the resolution.
345   //
346   // Using timeGetTime() has a drawback because it is a 32bit value
347   // and hence rolls-over every ~49days.
348   //
349   // To use the clock, we use GetSystemTimeAsFileTime as our base;
350   // and then use timeGetTime to extrapolate current time from the
351   // start time.  To deal with rollovers, we resync the clock
352   // any time when more than kMaxClockElapsedTime has passed or
353   // whenever timeGetTime creates a rollover.
354 
355   static bool initialized = false;
356   static TimeStamp init_time;
357   static DWORD init_ticks;
358   static const int64_t kHundredNanosecondsPerSecond = 10000000;
359   static const int64_t kMaxClockElapsedTime =
360       60*kHundredNanosecondsPerSecond;  // 1 minute
361 
362   // If we are uninitialized, we need to resync the clock.
363   bool needs_resync = !initialized;
364 
365   // Get the current time.
366   TimeStamp time_now;
367   GetSystemTimeAsFileTime(&time_now.ft_);
368   DWORD ticks_now = timeGetTime();
369 
370   // Check if we need to resync due to clock rollover.
371   needs_resync |= ticks_now < init_ticks;
372 
373   // Check if we need to resync due to elapsed time.
374   needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
375 
376   // Check if we need to resync due to backwards time change.
377   needs_resync |= time_now.t_ < init_time.t_;
378 
379   // Resync the clock if necessary.
380   if (needs_resync) {
381     GetSystemTimeAsFileTime(&init_time.ft_);
382     init_ticks = ticks_now = timeGetTime();
383     initialized = true;
384   }
385 
386   // Finally, compute the actual time.  Why is this so hard.
387   DWORD elapsed = ticks_now - init_ticks;
388   this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
389 }
390 
391 
392 // Return the local timezone offset in milliseconds east of UTC. This
393 // takes into account whether daylight saving is in effect at the time.
394 // Only times in the 32-bit Unix range may be passed to this function.
395 // Also, adding the time-zone offset to the input must not overflow.
396 // The function EquivalentTime() in date.js guarantees this.
LocalOffset(WindowsTimezoneCache * cache)397 int64_t Win32Time::LocalOffset(WindowsTimezoneCache* cache) {
398   cache->InitializeIfNeeded();
399 
400   Win32Time rounded_to_second(*this);
401   rounded_to_second.t() =
402       rounded_to_second.t() / 1000 / kTimeScaler * 1000 * kTimeScaler;
403   // Convert to local time using POSIX localtime function.
404   // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
405   // very slow.  Other browsers use localtime().
406 
407   // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
408   // POSIX seconds past 1/1/1970 0:00:00.
409   double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
410   if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
411     return 0;
412   }
413   // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
414   time_t posix_time = static_cast<time_t>(unchecked_posix_time);
415 
416   // Convert to local time, as struct with fields for day, hour, year, etc.
417   tm posix_local_time_struct;
418   if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
419 
420   if (posix_local_time_struct.tm_isdst > 0) {
421     return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
422   } else if (posix_local_time_struct.tm_isdst == 0) {
423     return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
424   } else {
425     return cache->tzinfo_.Bias * -kMsPerMinute;
426   }
427 }
428 
429 
430 // Return whether or not daylight savings time is in effect at this time.
InDST(WindowsTimezoneCache * cache)431 bool Win32Time::InDST(WindowsTimezoneCache* cache) {
432   cache->InitializeIfNeeded();
433 
434   // Determine if DST is in effect at the specified time.
435   bool in_dst = false;
436   if (cache->tzinfo_.StandardDate.wMonth != 0 ||
437       cache->tzinfo_.DaylightDate.wMonth != 0) {
438     // Get the local timezone offset for the timestamp in milliseconds.
439     int64_t offset = LocalOffset(cache);
440 
441     // Compute the offset for DST. The bias parameters in the timezone info
442     // are specified in minutes. These must be converted to milliseconds.
443     int64_t dstofs =
444         -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
445 
446     // If the local time offset equals the timezone bias plus the daylight
447     // bias then DST is in effect.
448     in_dst = offset == dstofs;
449   }
450 
451   return in_dst;
452 }
453 
454 
455 // Return the daylight savings time offset for this time.
DaylightSavingsOffset(WindowsTimezoneCache * cache)456 int64_t Win32Time::DaylightSavingsOffset(WindowsTimezoneCache* cache) {
457   return InDST(cache) ? 60 * kMsPerMinute : 0;
458 }
459 
460 
461 // Returns a string identifying the current timezone for the
462 // timestamp taking into account daylight saving.
LocalTimezone(WindowsTimezoneCache * cache)463 char* Win32Time::LocalTimezone(WindowsTimezoneCache* cache) {
464   // Return the standard or DST time zone name based on whether daylight
465   // saving is in effect at the given time.
466   return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
467 }
468 
469 
470 // Returns the accumulated user time for thread.
GetUserTime(uint32_t * secs,uint32_t * usecs)471 int OS::GetUserTime(uint32_t* secs,  uint32_t* usecs) {
472   FILETIME dummy;
473   uint64_t usertime;
474 
475   // Get the amount of time that the thread has executed in user mode.
476   if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
477                       reinterpret_cast<FILETIME*>(&usertime))) return -1;
478 
479   // Adjust the resolution to micro-seconds.
480   usertime /= 10;
481 
482   // Convert to seconds and microseconds
483   *secs = static_cast<uint32_t>(usertime / 1000000);
484   *usecs = static_cast<uint32_t>(usertime % 1000000);
485   return 0;
486 }
487 
488 
489 // Returns current time as the number of milliseconds since
490 // 00:00:00 UTC, January 1, 1970.
TimeCurrentMillis()491 double OS::TimeCurrentMillis() {
492   return Time::Now().ToJsTime();
493 }
494 
495 // Returns a string identifying the current timezone taking into
496 // account daylight saving.
LocalTimezone(double time)497 const char* WindowsTimezoneCache::LocalTimezone(double time) {
498   return Win32Time(time).LocalTimezone(this);
499 }
500 
501 // Returns the local time offset in milliseconds east of UTC without
502 // taking daylight savings time into account.
LocalTimeOffset(double time_ms,bool is_utc)503 double WindowsTimezoneCache::LocalTimeOffset(double time_ms, bool is_utc) {
504   // Ignore is_utc and time_ms for now. That way, the behavior wouldn't
505   // change with icu_timezone_data disabled.
506   // Use current time, rounded to the millisecond.
507   Win32Time t(OS::TimeCurrentMillis());
508   // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
509   return static_cast<double>(t.LocalOffset(this) -
510                              t.DaylightSavingsOffset(this));
511 }
512 
513 // Returns the daylight savings offset in milliseconds for the given
514 // time.
DaylightSavingsOffset(double time)515 double WindowsTimezoneCache::DaylightSavingsOffset(double time) {
516   int64_t offset = Win32Time(time).DaylightSavingsOffset(this);
517   return static_cast<double>(offset);
518 }
519 
CreateTimezoneCache()520 TimezoneCache* OS::CreateTimezoneCache() { return new WindowsTimezoneCache(); }
521 
GetLastError()522 int OS::GetLastError() {
523   return ::GetLastError();
524 }
525 
526 
GetCurrentProcessId()527 int OS::GetCurrentProcessId() {
528   return static_cast<int>(::GetCurrentProcessId());
529 }
530 
531 
GetCurrentThreadId()532 int OS::GetCurrentThreadId() {
533   return static_cast<int>(::GetCurrentThreadId());
534 }
535 
ExitProcess(int exit_code)536 void OS::ExitProcess(int exit_code) {
537   // Use TerminateProcess to avoid races between isolate threads and
538   // static destructors.
539   fflush(stdout);
540   fflush(stderr);
541   TerminateProcess(GetCurrentProcess(), exit_code);
542   // Termination the current process does not return. {TerminateProcess} is not
543   // marked [[noreturn]] though, since it can also be used to terminate another
544   // process.
545   UNREACHABLE();
546 }
547 
548 // ----------------------------------------------------------------------------
549 // Win32 console output.
550 //
551 // If a Win32 application is linked as a console application it has a normal
552 // standard output and standard error. In this case normal printf works fine
553 // for output. However, if the application is linked as a GUI application,
554 // the process doesn't have a console, and therefore (debugging) output is lost.
555 // This is the case if we are embedded in a windows program (like a browser).
556 // In order to be able to get debug output in this case the the debugging
557 // facility using OutputDebugString. This output goes to the active debugger
558 // for the process (if any). Else the output can be monitored using DBMON.EXE.
559 
560 enum OutputMode {
561   UNKNOWN,  // Output method has not yet been determined.
562   CONSOLE,  // Output is written to stdout.
563   ODS       // Output is written to debug facility.
564 };
565 
566 static OutputMode output_mode = UNKNOWN;  // Current output mode.
567 
568 
569 // Determine if the process has a console for output.
HasConsole()570 static bool HasConsole() {
571   // Only check the first time. Eventual race conditions are not a problem,
572   // because all threads will eventually determine the same mode.
573   if (output_mode == UNKNOWN) {
574     // We cannot just check that the standard output is attached to a console
575     // because this would fail if output is redirected to a file. Therefore we
576     // say that a process does not have an output console if either the
577     // standard output handle is invalid or its file type is unknown.
578     if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
579         GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
580       output_mode = CONSOLE;
581     else
582       output_mode = ODS;
583   }
584   return output_mode == CONSOLE;
585 }
586 
587 
VPrintHelper(FILE * stream,const char * format,va_list args)588 static void VPrintHelper(FILE* stream, const char* format, va_list args) {
589   if ((stream == stdout || stream == stderr) && !HasConsole()) {
590     // It is important to use safe print here in order to avoid
591     // overflowing the buffer. We might truncate the output, but this
592     // does not crash.
593     char buffer[4096];
594     OS::VSNPrintF(buffer, sizeof(buffer), format, args);
595     OutputDebugStringA(buffer);
596   } else {
597     vfprintf(stream, format, args);
598   }
599 }
600 
601 // Convert utf-8 encoded string to utf-16 encoded.
ConvertUtf8StringToUtf16(const char * str)602 static std::wstring ConvertUtf8StringToUtf16(const char* str) {
603   // On Windows wchar_t must be a 16-bit value.
604   static_assert(sizeof(wchar_t) == 2, "wrong wchar_t size");
605   std::wstring utf16_str;
606   int name_length = static_cast<int>(strlen(str));
607   int len = MultiByteToWideChar(CP_UTF8, 0, str, name_length, nullptr, 0);
608   if (len > 0) {
609     utf16_str.resize(len);
610     MultiByteToWideChar(CP_UTF8, 0, str, name_length, &utf16_str[0], len);
611   }
612   return utf16_str;
613 }
614 
FOpen(const char * path,const char * mode)615 FILE* OS::FOpen(const char* path, const char* mode) {
616   FILE* result;
617   std::wstring utf16_path = ConvertUtf8StringToUtf16(path);
618   std::wstring utf16_mode = ConvertUtf8StringToUtf16(mode);
619   if (_wfopen_s(&result, utf16_path.c_str(), utf16_mode.c_str()) == 0) {
620     return result;
621   } else {
622     return nullptr;
623   }
624 }
625 
626 
Remove(const char * path)627 bool OS::Remove(const char* path) {
628   return (DeleteFileA(path) != 0);
629 }
630 
DirectorySeparator()631 char OS::DirectorySeparator() { return '\\'; }
632 
isDirectorySeparator(const char ch)633 bool OS::isDirectorySeparator(const char ch) {
634   return ch == '/' || ch == '\\';
635 }
636 
637 
OpenTemporaryFile()638 FILE* OS::OpenTemporaryFile() {
639   // tmpfile_s tries to use the root dir, don't use it.
640   char tempPathBuffer[MAX_PATH];
641   DWORD path_result = 0;
642   path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
643   if (path_result > MAX_PATH || path_result == 0) return nullptr;
644   UINT name_result = 0;
645   char tempNameBuffer[MAX_PATH];
646   name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
647   if (name_result == 0) return nullptr;
648   FILE* result = FOpen(tempNameBuffer, "w+");  // Same mode as tmpfile uses.
649   if (result != nullptr) {
650     Remove(tempNameBuffer);  // Delete on close.
651   }
652   return result;
653 }
654 
655 
656 // Open log file in binary mode to avoid /n -> /r/n conversion.
657 const char* const OS::LogFileOpenMode = "wb+";
658 
659 // Print (debug) message to console.
Print(const char * format,...)660 void OS::Print(const char* format, ...) {
661   va_list args;
662   va_start(args, format);
663   VPrint(format, args);
664   va_end(args);
665 }
666 
667 
VPrint(const char * format,va_list args)668 void OS::VPrint(const char* format, va_list args) {
669   VPrintHelper(stdout, format, args);
670 }
671 
672 
FPrint(FILE * out,const char * format,...)673 void OS::FPrint(FILE* out, const char* format, ...) {
674   va_list args;
675   va_start(args, format);
676   VFPrint(out, format, args);
677   va_end(args);
678 }
679 
680 
VFPrint(FILE * out,const char * format,va_list args)681 void OS::VFPrint(FILE* out, const char* format, va_list args) {
682   VPrintHelper(out, format, args);
683 }
684 
685 
686 // Print error message to console.
PrintError(const char * format,...)687 void OS::PrintError(const char* format, ...) {
688   va_list args;
689   va_start(args, format);
690   VPrintError(format, args);
691   va_end(args);
692 }
693 
694 
VPrintError(const char * format,va_list args)695 void OS::VPrintError(const char* format, va_list args) {
696   VPrintHelper(stderr, format, args);
697 }
698 
699 
SNPrintF(char * str,int length,const char * format,...)700 int OS::SNPrintF(char* str, int length, const char* format, ...) {
701   va_list args;
702   va_start(args, format);
703   int result = VSNPrintF(str, length, format, args);
704   va_end(args);
705   return result;
706 }
707 
708 
VSNPrintF(char * str,int length,const char * format,va_list args)709 int OS::VSNPrintF(char* str, int length, const char* format, va_list args) {
710   int n = _vsnprintf_s(str, length, _TRUNCATE, format, args);
711   // Make sure to zero-terminate the string if the output was
712   // truncated or if there was an error.
713   if (n < 0 || n >= length) {
714     if (length > 0)
715       str[length - 1] = '\0';
716     return -1;
717   } else {
718     return n;
719   }
720 }
721 
722 
StrNCpy(char * dest,int length,const char * src,size_t n)723 void OS::StrNCpy(char* dest, int length, const char* src, size_t n) {
724   // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
725   size_t buffer_size = static_cast<size_t>(length);
726   if (n + 1 > buffer_size)  // count for trailing '\0'
727     n = _TRUNCATE;
728   int result = strncpy_s(dest, length, src, n);
729   USE(result);
730   DCHECK(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
731 }
732 
733 
734 #undef _TRUNCATE
735 #undef STRUNCATE
736 
737 DEFINE_LAZY_LEAKY_OBJECT_GETTER(RandomNumberGenerator,
738                                 GetPlatformRandomNumberGenerator)
739 static LazyMutex rng_mutex = LAZY_MUTEX_INITIALIZER;
740 
Initialize(bool hard_abort,const char * const gc_fake_mmap)741 void OS::Initialize(bool hard_abort, const char* const gc_fake_mmap) {
742   g_hard_abort = hard_abort;
743 }
744 
745 typedef PVOID(__stdcall* VirtualAlloc2_t)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
746                                           MEM_EXTENDED_PARAMETER*, ULONG);
747 VirtualAlloc2_t VirtualAlloc2 = nullptr;
748 
749 typedef PVOID(__stdcall* MapViewOfFile3_t)(HANDLE, HANDLE, PVOID, ULONG64,
750                                            SIZE_T, ULONG, ULONG,
751                                            MEM_EXTENDED_PARAMETER*, ULONG);
752 MapViewOfFile3_t MapViewOfFile3 = nullptr;
753 
754 typedef PVOID(__stdcall* UnmapViewOfFile2_t)(HANDLE, PVOID, ULONG);
755 UnmapViewOfFile2_t UnmapViewOfFile2 = nullptr;
756 
EnsureWin32MemoryAPILoaded()757 void OS::EnsureWin32MemoryAPILoaded() {
758   static bool loaded = false;
759   if (!loaded) {
760     VirtualAlloc2 = (VirtualAlloc2_t)GetProcAddress(
761         GetModuleHandle(L"kernelbase.dll"), "VirtualAlloc2");
762 
763     MapViewOfFile3 = (MapViewOfFile3_t)GetProcAddress(
764         GetModuleHandle(L"kernelbase.dll"), "MapViewOfFile3");
765 
766     UnmapViewOfFile2 = (UnmapViewOfFile2_t)GetProcAddress(
767         GetModuleHandle(L"kernelbase.dll"), "UnmapViewOfFile2");
768 
769     loaded = true;
770   }
771 }
772 
773 // static
AllocatePageSize()774 size_t OS::AllocatePageSize() {
775   static size_t allocate_alignment = 0;
776   if (allocate_alignment == 0) {
777     SYSTEM_INFO info;
778     GetSystemInfo(&info);
779     allocate_alignment = info.dwAllocationGranularity;
780   }
781   return allocate_alignment;
782 }
783 
784 // static
CommitPageSize()785 size_t OS::CommitPageSize() {
786   static size_t page_size = 0;
787   if (page_size == 0) {
788     SYSTEM_INFO info;
789     GetSystemInfo(&info);
790     page_size = info.dwPageSize;
791     DCHECK_EQ(4096, page_size);
792   }
793   return page_size;
794 }
795 
796 // static
SetRandomMmapSeed(int64_t seed)797 void OS::SetRandomMmapSeed(int64_t seed) {
798   if (seed) {
799     MutexGuard guard(rng_mutex.Pointer());
800     GetPlatformRandomNumberGenerator()->SetSeed(seed);
801   }
802 }
803 
804 // static
GetRandomMmapAddr()805 void* OS::GetRandomMmapAddr() {
806 // The address range used to randomize RWX allocations in OS::Allocate
807 // Try not to map pages into the default range that windows loads DLLs
808 // Use a multiple of 64k to prevent committing unused memory.
809 // Note: This does not guarantee RWX regions will be within the
810 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
811 #ifdef V8_HOST_ARCH_64_BIT
812   static const uintptr_t kAllocationRandomAddressMin = 0x0000000080000000;
813   static const uintptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
814 #else
815   static const uintptr_t kAllocationRandomAddressMin = 0x04000000;
816   static const uintptr_t kAllocationRandomAddressMax = 0x3FFF0000;
817 #endif
818   uintptr_t address;
819   {
820     MutexGuard guard(rng_mutex.Pointer());
821     GetPlatformRandomNumberGenerator()->NextBytes(&address, sizeof(address));
822   }
823   address <<= kPageSizeBits;
824   address += kAllocationRandomAddressMin;
825   address &= kAllocationRandomAddressMax;
826   return reinterpret_cast<void*>(address);
827 }
828 
829 namespace {
830 
GetProtectionFromMemoryPermission(OS::MemoryPermission access)831 DWORD GetProtectionFromMemoryPermission(OS::MemoryPermission access) {
832   switch (access) {
833     case OS::MemoryPermission::kNoAccess:
834     case OS::MemoryPermission::kNoAccessWillJitLater:
835       return PAGE_NOACCESS;
836     case OS::MemoryPermission::kRead:
837       return PAGE_READONLY;
838     case OS::MemoryPermission::kReadWrite:
839       return PAGE_READWRITE;
840     case OS::MemoryPermission::kReadWriteExecute:
841       if (IsWindows10OrGreater())
842         return PAGE_EXECUTE_READWRITE | PAGE_TARGETS_INVALID;
843       return PAGE_EXECUTE_READWRITE;
844     case OS::MemoryPermission::kReadExecute:
845       if (IsWindows10OrGreater())
846         return PAGE_EXECUTE_READ | PAGE_TARGETS_INVALID;
847       return PAGE_EXECUTE_READ;
848   }
849   UNREACHABLE();
850 }
851 
852 // Desired access parameter for MapViewOfFile
GetFileViewAccessFromMemoryPermission(OS::MemoryPermission access)853 DWORD GetFileViewAccessFromMemoryPermission(OS::MemoryPermission access) {
854   switch (access) {
855     case OS::MemoryPermission::kNoAccess:
856     case OS::MemoryPermission::kNoAccessWillJitLater:
857     case OS::MemoryPermission::kRead:
858       return FILE_MAP_READ;
859     case OS::MemoryPermission::kReadWrite:
860       return FILE_MAP_READ | FILE_MAP_WRITE;
861     default:
862       // Execute access is not supported
863       break;
864   }
865   UNREACHABLE();
866 }
867 
VirtualAllocWrapper(void * address,size_t size,DWORD flags,DWORD protect)868 void* VirtualAllocWrapper(void* address, size_t size, DWORD flags,
869                           DWORD protect) {
870   if (VirtualAlloc2) {
871     return VirtualAlloc2(nullptr, address, size, flags, protect, NULL, 0);
872   } else {
873     return VirtualAlloc(address, size, flags, protect);
874   }
875 }
876 
VirtualAllocWithHint(size_t size,DWORD flags,DWORD protect,void * hint)877 uint8_t* VirtualAllocWithHint(size_t size, DWORD flags, DWORD protect,
878                               void* hint) {
879   LPVOID base = VirtualAllocWrapper(hint, size, flags, protect);
880 
881   // On failure, let the OS find an address to use.
882   if (hint && base == nullptr) {
883     base = VirtualAllocWrapper(nullptr, size, flags, protect);
884   }
885 
886   return reinterpret_cast<uint8_t*>(base);
887 }
888 
AllocateInternal(void * hint,size_t size,size_t alignment,size_t page_size,DWORD flags,DWORD protect)889 void* AllocateInternal(void* hint, size_t size, size_t alignment,
890                        size_t page_size, DWORD flags, DWORD protect) {
891   // First, try an exact size aligned allocation.
892   uint8_t* base = VirtualAllocWithHint(size, flags, protect, hint);
893   if (base == nullptr) return nullptr;  // Can't allocate, we're OOM.
894 
895   // If address is suitably aligned, we're done.
896   uint8_t* aligned_base = reinterpret_cast<uint8_t*>(
897       RoundUp(reinterpret_cast<uintptr_t>(base), alignment));
898   if (base == aligned_base) return reinterpret_cast<void*>(base);
899 
900   // Otherwise, free it and try a larger allocation.
901   CHECK(VirtualFree(base, 0, MEM_RELEASE));
902 
903   // Clear the hint. It's unlikely we can allocate at this address.
904   hint = nullptr;
905 
906   // Add the maximum misalignment so we are guaranteed an aligned base address
907   // in the allocated region.
908   size_t padded_size = size + (alignment - page_size);
909   const int kMaxAttempts = 3;
910   aligned_base = nullptr;
911   for (int i = 0; i < kMaxAttempts; ++i) {
912     base = VirtualAllocWithHint(padded_size, flags, protect, hint);
913     if (base == nullptr) return nullptr;  // Can't allocate, we're OOM.
914 
915     // Try to trim the allocation by freeing the padded allocation and then
916     // calling VirtualAlloc at the aligned base.
917     CHECK(VirtualFree(base, 0, MEM_RELEASE));
918     aligned_base = reinterpret_cast<uint8_t*>(
919         RoundUp(reinterpret_cast<uintptr_t>(base), alignment));
920     base = reinterpret_cast<uint8_t*>(
921         VirtualAllocWrapper(aligned_base, size, flags, protect));
922     // We might not get the reduced allocation due to a race. In that case,
923     // base will be nullptr.
924     if (base != nullptr) break;
925   }
926   DCHECK_IMPLIES(base, base == aligned_base);
927   return reinterpret_cast<void*>(base);
928 }
929 
930 }  // namespace
931 
932 // static
Allocate(void * hint,size_t size,size_t alignment,MemoryPermission access)933 void* OS::Allocate(void* hint, size_t size, size_t alignment,
934                    MemoryPermission access) {
935   size_t page_size = AllocatePageSize();
936   DCHECK_EQ(0, size % page_size);
937   DCHECK_EQ(0, alignment % page_size);
938   DCHECK_LE(page_size, alignment);
939   hint = AlignedAddress(hint, alignment);
940 
941   DWORD flags = (access == OS::MemoryPermission::kNoAccess)
942                     ? MEM_RESERVE
943                     : MEM_RESERVE | MEM_COMMIT;
944   DWORD protect = GetProtectionFromMemoryPermission(access);
945 
946   return AllocateInternal(hint, size, alignment, page_size, flags, protect);
947 }
948 
949 // static
Free(void * address,size_t size)950 void OS::Free(void* address, size_t size) {
951   DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % AllocatePageSize());
952   DCHECK_EQ(0, size % AllocatePageSize());
953   USE(size);
954   CHECK_NE(0, VirtualFree(address, 0, MEM_RELEASE));
955 }
956 
957 // static
AllocateShared(void * hint,size_t size,MemoryPermission permission,PlatformSharedMemoryHandle handle,uint64_t offset)958 void* OS::AllocateShared(void* hint, size_t size, MemoryPermission permission,
959                          PlatformSharedMemoryHandle handle, uint64_t offset) {
960   DCHECK_EQ(0, reinterpret_cast<uintptr_t>(hint) % AllocatePageSize());
961   DCHECK_EQ(0, size % AllocatePageSize());
962   DCHECK_EQ(0, offset % AllocatePageSize());
963 
964   DWORD off_hi = static_cast<DWORD>(offset >> 32);
965   DWORD off_lo = static_cast<DWORD>(offset);
966   DWORD access = GetFileViewAccessFromMemoryPermission(permission);
967 
968   HANDLE file_mapping = FileMappingFromSharedMemoryHandle(handle);
969   void* result =
970       MapViewOfFileEx(file_mapping, access, off_hi, off_lo, size, hint);
971 
972   if (!result) {
973     // Retry without hint.
974     result = MapViewOfFile(file_mapping, access, off_hi, off_lo, size);
975   }
976 
977   return result;
978 }
979 
980 // static
FreeShared(void * address,size_t size)981 void OS::FreeShared(void* address, size_t size) {
982   CHECK(UnmapViewOfFile(address));
983 }
984 
985 // static
Release(void * address,size_t size)986 void OS::Release(void* address, size_t size) {
987   DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
988   DCHECK_EQ(0, size % CommitPageSize());
989   CHECK_NE(0, VirtualFree(address, size, MEM_DECOMMIT));
990 }
991 
992 // static
SetPermissions(void * address,size_t size,MemoryPermission access)993 bool OS::SetPermissions(void* address, size_t size, MemoryPermission access) {
994   DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
995   DCHECK_EQ(0, size % CommitPageSize());
996   if (access == MemoryPermission::kNoAccess) {
997     return VirtualFree(address, size, MEM_DECOMMIT) != 0;
998   }
999   DWORD protect = GetProtectionFromMemoryPermission(access);
1000   return VirtualAllocWrapper(address, size, MEM_COMMIT, protect) != nullptr;
1001 }
1002 
1003 // static
DiscardSystemPages(void * address,size_t size)1004 bool OS::DiscardSystemPages(void* address, size_t size) {
1005   // On Windows, discarded pages are not returned to the system immediately and
1006   // not guaranteed to be zeroed when returned to the application.
1007   using DiscardVirtualMemoryFunction =
1008       DWORD(WINAPI*)(PVOID virtualAddress, SIZE_T size);
1009   static std::atomic<DiscardVirtualMemoryFunction> discard_virtual_memory(
1010       reinterpret_cast<DiscardVirtualMemoryFunction>(-1));
1011   if (discard_virtual_memory ==
1012       reinterpret_cast<DiscardVirtualMemoryFunction>(-1))
1013     discard_virtual_memory =
1014         reinterpret_cast<DiscardVirtualMemoryFunction>(GetProcAddress(
1015             GetModuleHandle(L"Kernel32.dll"), "DiscardVirtualMemory"));
1016   // Use DiscardVirtualMemory when available because it releases faster than
1017   // MEM_RESET.
1018   DiscardVirtualMemoryFunction discard_function = discard_virtual_memory.load();
1019   if (discard_function) {
1020     DWORD ret = discard_function(address, size);
1021     if (!ret) return true;
1022   }
1023   // DiscardVirtualMemory is buggy in Win10 SP0, so fall back to MEM_RESET on
1024   // failure.
1025   void* ptr = VirtualAllocWrapper(address, size, MEM_RESET, PAGE_READWRITE);
1026   CHECK(ptr);
1027   return ptr;
1028 }
1029 
1030 // static
DecommitPages(void * address,size_t size)1031 bool OS::DecommitPages(void* address, size_t size) {
1032   DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
1033   DCHECK_EQ(0, size % CommitPageSize());
1034   // https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualfree:
1035   // "If a page is decommitted but not released, its state changes to reserved.
1036   // Subsequently, you can call VirtualAlloc to commit it, or VirtualFree to
1037   // release it. Attempts to read from or write to a reserved page results in an
1038   // access violation exception."
1039   // https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc
1040   // for MEM_COMMIT: "The function also guarantees that when the caller later
1041   // initially accesses the memory, the contents will be zero."
1042   return VirtualFree(address, size, MEM_DECOMMIT) != 0;
1043 }
1044 
1045 // static
CanReserveAddressSpace()1046 bool OS::CanReserveAddressSpace() {
1047   return VirtualAlloc2 != nullptr && MapViewOfFile3 != nullptr &&
1048          UnmapViewOfFile2 != nullptr;
1049 }
1050 
1051 // static
CreateAddressSpaceReservation(void * hint,size_t size,size_t alignment,MemoryPermission max_permission)1052 Optional<AddressSpaceReservation> OS::CreateAddressSpaceReservation(
1053     void* hint, size_t size, size_t alignment,
1054     MemoryPermission max_permission) {
1055   CHECK(CanReserveAddressSpace());
1056 
1057   size_t page_size = AllocatePageSize();
1058   DCHECK_EQ(0, size % page_size);
1059   DCHECK_EQ(0, alignment % page_size);
1060   DCHECK_LE(page_size, alignment);
1061   hint = AlignedAddress(hint, alignment);
1062 
1063   // On Windows, address space reservations are backed by placeholder mappings.
1064   void* reservation =
1065       AllocateInternal(hint, size, alignment, page_size,
1066                        MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS);
1067   if (!reservation) return {};
1068 
1069   return AddressSpaceReservation(reservation, size);
1070 }
1071 
1072 // static
FreeAddressSpaceReservation(AddressSpaceReservation reservation)1073 void OS::FreeAddressSpaceReservation(AddressSpaceReservation reservation) {
1074   OS::Free(reservation.base(), reservation.size());
1075 }
1076 
1077 // static
CreateSharedMemoryHandleForTesting(size_t size)1078 PlatformSharedMemoryHandle OS::CreateSharedMemoryHandleForTesting(size_t size) {
1079   HANDLE handle = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr,
1080                                     PAGE_READWRITE, 0, size, nullptr);
1081   if (!handle) return kInvalidSharedMemoryHandle;
1082   return SharedMemoryHandleFromFileMapping(handle);
1083 }
1084 
1085 // static
DestroySharedMemoryHandle(PlatformSharedMemoryHandle handle)1086 void OS::DestroySharedMemoryHandle(PlatformSharedMemoryHandle handle) {
1087   DCHECK_NE(kInvalidSharedMemoryHandle, handle);
1088   HANDLE file_mapping = FileMappingFromSharedMemoryHandle(handle);
1089   CHECK(CloseHandle(file_mapping));
1090 }
1091 
1092 // static
HasLazyCommits()1093 bool OS::HasLazyCommits() {
1094   // TODO(alph): implement for the platform.
1095   return false;
1096 }
1097 
Sleep(TimeDelta interval)1098 void OS::Sleep(TimeDelta interval) {
1099   ::Sleep(static_cast<DWORD>(interval.InMilliseconds()));
1100 }
1101 
1102 
Abort()1103 void OS::Abort() {
1104   // Give a chance to debug the failure.
1105   if (IsDebuggerPresent()) {
1106     DebugBreak();
1107   }
1108 
1109   // Before aborting, make sure to flush output buffers.
1110   fflush(stdout);
1111   fflush(stderr);
1112 
1113   if (g_hard_abort) {
1114     IMMEDIATE_CRASH();
1115   }
1116   // Make the MSVCRT do a silent abort.
1117   raise(SIGABRT);
1118 
1119   // Make sure function doesn't return.
1120   abort();
1121 }
1122 
1123 
DebugBreak()1124 void OS::DebugBreak() {
1125 #if V8_CC_MSVC
1126   // To avoid Visual Studio runtime support the following code can be used
1127   // instead
1128   // __asm { int 3 }
1129   __debugbreak();
1130 #else
1131   ::DebugBreak();
1132 #endif
1133 }
1134 
1135 
1136 class Win32MemoryMappedFile final : public OS::MemoryMappedFile {
1137  public:
Win32MemoryMappedFile(HANDLE file,HANDLE file_mapping,void * memory,size_t size)1138   Win32MemoryMappedFile(HANDLE file, HANDLE file_mapping, void* memory,
1139                         size_t size)
1140       : file_(file),
1141         file_mapping_(file_mapping),
1142         memory_(memory),
1143         size_(size) {}
1144   ~Win32MemoryMappedFile() final;
memory() const1145   void* memory() const final { return memory_; }
size() const1146   size_t size() const final { return size_; }
1147 
1148  private:
1149   HANDLE const file_;
1150   HANDLE const file_mapping_;
1151   void* const memory_;
1152   size_t const size_;
1153 };
1154 
1155 
1156 // static
open(const char * name,FileMode mode)1157 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name,
1158                                                  FileMode mode) {
1159   // Open a physical file.
1160   DWORD access = GENERIC_READ;
1161   if (mode == FileMode::kReadWrite) {
1162     access |= GENERIC_WRITE;
1163   }
1164 
1165   std::wstring utf16_name = ConvertUtf8StringToUtf16(name);
1166   HANDLE file = CreateFileW(utf16_name.c_str(), access,
1167                             FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
1168                             OPEN_EXISTING, 0, nullptr);
1169   if (file == INVALID_HANDLE_VALUE) return nullptr;
1170 
1171   DWORD size = GetFileSize(file, nullptr);
1172   if (size == 0) return new Win32MemoryMappedFile(file, nullptr, nullptr, 0);
1173 
1174   DWORD protection =
1175       (mode == FileMode::kReadOnly) ? PAGE_READONLY : PAGE_READWRITE;
1176   // Create a file mapping for the physical file.
1177   HANDLE file_mapping =
1178       CreateFileMapping(file, nullptr, protection, 0, size, nullptr);
1179   if (file_mapping == nullptr) return nullptr;
1180 
1181   // Map a view of the file into memory.
1182   DWORD view_access =
1183       (mode == FileMode::kReadOnly) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;
1184   void* memory = MapViewOfFile(file_mapping, view_access, 0, 0, size);
1185   return new Win32MemoryMappedFile(file, file_mapping, memory, size);
1186 }
1187 
1188 // static
create(const char * name,size_t size,void * initial)1189 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name,
1190                                                    size_t size, void* initial) {
1191   std::wstring utf16_name = ConvertUtf8StringToUtf16(name);
1192   // Open a physical file.
1193   HANDLE file = CreateFileW(utf16_name.c_str(), GENERIC_READ | GENERIC_WRITE,
1194                             FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
1195                             OPEN_ALWAYS, 0, nullptr);
1196   if (file == nullptr) return nullptr;
1197   if (size == 0) return new Win32MemoryMappedFile(file, nullptr, nullptr, 0);
1198   // Create a file mapping for the physical file.
1199   HANDLE file_mapping = CreateFileMapping(file, nullptr, PAGE_READWRITE, 0,
1200                                           static_cast<DWORD>(size), nullptr);
1201   if (file_mapping == nullptr) return nullptr;
1202   // Map a view of the file into memory.
1203   void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
1204   if (memory) memmove(memory, initial, size);
1205   return new Win32MemoryMappedFile(file, file_mapping, memory, size);
1206 }
1207 
1208 
~Win32MemoryMappedFile()1209 Win32MemoryMappedFile::~Win32MemoryMappedFile() {
1210   if (memory_) UnmapViewOfFile(memory_);
1211   if (file_mapping_) CloseHandle(file_mapping_);
1212   CloseHandle(file_);
1213 }
1214 
CreateSubReservation(void * address,size_t size,OS::MemoryPermission max_permission)1215 Optional<AddressSpaceReservation> AddressSpaceReservation::CreateSubReservation(
1216     void* address, size_t size, OS::MemoryPermission max_permission) {
1217   // Nothing to do, the sub reservation must already have been split by now.
1218   DCHECK(Contains(address, size));
1219   DCHECK_EQ(0, size % OS::AllocatePageSize());
1220   DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % OS::AllocatePageSize());
1221 
1222   return AddressSpaceReservation(address, size);
1223 }
1224 
FreeSubReservation(AddressSpaceReservation reservation)1225 bool AddressSpaceReservation::FreeSubReservation(
1226     AddressSpaceReservation reservation) {
1227   // Nothing to do.
1228   // Pages allocated inside the reservation must've already been freed.
1229   return true;
1230 }
1231 
SplitPlaceholder(void * address,size_t size)1232 bool AddressSpaceReservation::SplitPlaceholder(void* address, size_t size) {
1233   DCHECK(Contains(address, size));
1234   return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
1235 }
1236 
MergePlaceholders(void * address,size_t size)1237 bool AddressSpaceReservation::MergePlaceholders(void* address, size_t size) {
1238   DCHECK(Contains(address, size));
1239   return VirtualFree(address, size, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS);
1240 }
1241 
Allocate(void * address,size_t size,OS::MemoryPermission access)1242 bool AddressSpaceReservation::Allocate(void* address, size_t size,
1243                                        OS::MemoryPermission access) {
1244   DCHECK(Contains(address, size));
1245   CHECK(VirtualAlloc2);
1246   DWORD flags = (access == OS::MemoryPermission::kNoAccess)
1247                     ? MEM_RESERVE | MEM_REPLACE_PLACEHOLDER
1248                     : MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER;
1249   DWORD protect = GetProtectionFromMemoryPermission(access);
1250   return VirtualAlloc2(nullptr, address, size, flags, protect, nullptr, 0);
1251 }
1252 
Free(void * address,size_t size)1253 bool AddressSpaceReservation::Free(void* address, size_t size) {
1254   DCHECK(Contains(address, size));
1255   return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
1256 }
1257 
AllocateShared(void * address,size_t size,OS::MemoryPermission access,PlatformSharedMemoryHandle handle,uint64_t offset)1258 bool AddressSpaceReservation::AllocateShared(void* address, size_t size,
1259                                              OS::MemoryPermission access,
1260                                              PlatformSharedMemoryHandle handle,
1261                                              uint64_t offset) {
1262   DCHECK(Contains(address, size));
1263   CHECK(MapViewOfFile3);
1264 
1265   DWORD protect = GetProtectionFromMemoryPermission(access);
1266   HANDLE file_mapping = FileMappingFromSharedMemoryHandle(handle);
1267   return MapViewOfFile3(file_mapping, nullptr, address, offset, size,
1268                         MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0);
1269 }
1270 
FreeShared(void * address,size_t size)1271 bool AddressSpaceReservation::FreeShared(void* address, size_t size) {
1272   DCHECK(Contains(address, size));
1273   CHECK(UnmapViewOfFile2);
1274 
1275   return UnmapViewOfFile2(nullptr, address, MEM_PRESERVE_PLACEHOLDER);
1276 }
1277 
SetPermissions(void * address,size_t size,OS::MemoryPermission access)1278 bool AddressSpaceReservation::SetPermissions(void* address, size_t size,
1279                                              OS::MemoryPermission access) {
1280   DCHECK(Contains(address, size));
1281   return OS::SetPermissions(address, size, access);
1282 }
1283 
DiscardSystemPages(void * address,size_t size)1284 bool AddressSpaceReservation::DiscardSystemPages(void* address, size_t size) {
1285   DCHECK(Contains(address, size));
1286   return OS::DiscardSystemPages(address, size);
1287 }
1288 
DecommitPages(void * address,size_t size)1289 bool AddressSpaceReservation::DecommitPages(void* address, size_t size) {
1290   DCHECK(Contains(address, size));
1291   return OS::DecommitPages(address, size);
1292 }
1293 
1294 // The following code loads functions defined in DbhHelp.h and TlHelp32.h
1295 // dynamically. This is to avoid being depending on dbghelp.dll and
1296 // tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
1297 // kernel32.dll at some point so loading functions defines in TlHelp32.h
1298 // dynamically might not be necessary any more - for some versions of Windows?).
1299 
1300 // Function pointers to functions dynamically loaded from dbghelp.dll.
1301 #define DBGHELP_FUNCTION_LIST(V)  \
1302   V(SymInitialize)                \
1303   V(SymGetOptions)                \
1304   V(SymSetOptions)                \
1305   V(SymGetSearchPath)             \
1306   V(SymLoadModule64)              \
1307   V(StackWalk64)                  \
1308   V(SymGetSymFromAddr64)          \
1309   V(SymGetLineFromAddr64)         \
1310   V(SymFunctionTableAccess64)     \
1311   V(SymGetModuleBase64)
1312 
1313 // Function pointers to functions dynamically loaded from dbghelp.dll.
1314 #define TLHELP32_FUNCTION_LIST(V)  \
1315   V(CreateToolhelp32Snapshot)      \
1316   V(Module32FirstW)                \
1317   V(Module32NextW)
1318 
1319 // Define the decoration to use for the type and variable name used for
1320 // dynamically loaded DLL function..
1321 #define DLL_FUNC_TYPE(name) _##name##_
1322 #define DLL_FUNC_VAR(name) _##name
1323 
1324 // Define the type for each dynamically loaded DLL function. The function
1325 // definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1326 // from the Windows include files are redefined here to have the function
1327 // definitions to be as close to the ones in the original .h files as possible.
1328 #ifndef IN
1329 #define IN
1330 #endif
1331 #ifndef VOID
1332 #define VOID void
1333 #endif
1334 
1335 // DbgHelp isn't supported on MinGW yet
1336 #ifndef __MINGW32__
1337 // DbgHelp.h functions.
1338 using DLL_FUNC_TYPE(SymInitialize) = BOOL(__stdcall*)(IN HANDLE hProcess,
1339                                                       IN PSTR UserSearchPath,
1340                                                       IN BOOL fInvadeProcess);
1341 using DLL_FUNC_TYPE(SymGetOptions) = DWORD(__stdcall*)(VOID);
1342 using DLL_FUNC_TYPE(SymSetOptions) = DWORD(__stdcall*)(IN DWORD SymOptions);
1343 using DLL_FUNC_TYPE(SymGetSearchPath) = BOOL(__stdcall*)(
1344     IN HANDLE hProcess, OUT PSTR SearchPath, IN DWORD SearchPathLength);
1345 using DLL_FUNC_TYPE(SymLoadModule64) = DWORD64(__stdcall*)(
1346     IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName,
1347     IN DWORD64 BaseOfDll, IN DWORD SizeOfDll);
1348 using DLL_FUNC_TYPE(StackWalk64) = BOOL(__stdcall*)(
1349     DWORD MachineType, HANDLE hProcess, HANDLE hThread,
1350     LPSTACKFRAME64 StackFrame, PVOID ContextRecord,
1351     PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1352     PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1353     PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1354     PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1355 using DLL_FUNC_TYPE(SymGetSymFromAddr64) = BOOL(__stdcall*)(
1356     IN HANDLE hProcess, IN DWORD64 qwAddr, OUT PDWORD64 pdwDisplacement,
1357     OUT PIMAGEHLP_SYMBOL64 Symbol);
1358 using DLL_FUNC_TYPE(SymGetLineFromAddr64) =
1359     BOOL(__stdcall*)(IN HANDLE hProcess, IN DWORD64 qwAddr,
1360                      OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line64);
1361 // DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1362 using DLL_FUNC_TYPE(SymFunctionTableAccess64) = PVOID(__stdcall*)(
1363     HANDLE hProcess,
1364     DWORD64 AddrBase);  // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1365 using DLL_FUNC_TYPE(SymGetModuleBase64) = DWORD64(__stdcall*)(
1366     HANDLE hProcess,
1367     DWORD64 AddrBase);  // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1368 
1369 // TlHelp32.h functions.
1370 using DLL_FUNC_TYPE(CreateToolhelp32Snapshot) =
1371     HANDLE(__stdcall*)(DWORD dwFlags, DWORD th32ProcessID);
1372 using DLL_FUNC_TYPE(Module32FirstW) = BOOL(__stdcall*)(HANDLE hSnapshot,
1373                                                        LPMODULEENTRY32W lpme);
1374 using DLL_FUNC_TYPE(Module32NextW) = BOOL(__stdcall*)(HANDLE hSnapshot,
1375                                                       LPMODULEENTRY32W lpme);
1376 
1377 #undef IN
1378 #undef VOID
1379 
1380 // Declare a variable for each dynamically loaded DLL function.
1381 #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = nullptr;
1382 DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)1383 TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1384 #undef DEF_DLL_FUNCTION
1385 
1386 // Load the functions. This function has a lot of "ugly" macros in order to
1387 // keep down code duplication.
1388 
1389 static bool LoadDbgHelpAndTlHelp32() {
1390   static bool dbghelp_loaded = false;
1391 
1392   if (dbghelp_loaded) return true;
1393 
1394   HMODULE module;
1395 
1396   // Load functions from the dbghelp.dll module.
1397   module = LoadLibrary(TEXT("dbghelp.dll"));
1398   if (module == nullptr) {
1399     return false;
1400   }
1401 
1402 #define LOAD_DLL_FUNC(name)                                                 \
1403   DLL_FUNC_VAR(name) =                                                      \
1404       reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1405 
1406 DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1407 
1408 #undef LOAD_DLL_FUNC
1409 
1410   // Load functions from the kernel32.dll module (the TlHelp32.h function used
1411   // to be in tlhelp32.dll but are now moved to kernel32.dll).
1412   module = LoadLibrary(TEXT("kernel32.dll"));
1413   if (module == nullptr) {
1414     return false;
1415   }
1416 
1417 #define LOAD_DLL_FUNC(name)                                                 \
1418   DLL_FUNC_VAR(name) =                                                      \
1419       reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1420 
1421 TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1422 
1423 #undef LOAD_DLL_FUNC
1424 
1425   // Check that all functions where loaded.
1426 bool result =
1427 #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != nullptr)&&
1428 
1429     DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1430         TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1431 
1432 #undef DLL_FUNC_LOADED
1433             true;
1434 
1435   dbghelp_loaded = result;
1436   return result;
1437   // NOTE: The modules are never unloaded and will stay around until the
1438   // application is closed.
1439 }
1440 
1441 #undef DBGHELP_FUNCTION_LIST
1442 #undef TLHELP32_FUNCTION_LIST
1443 #undef DLL_FUNC_VAR
1444 #undef DLL_FUNC_TYPE
1445 
1446 
1447 // Load the symbols for generating stack traces.
LoadSymbols(HANDLE process_handle)1448 static std::vector<OS::SharedLibraryAddress> LoadSymbols(
1449     HANDLE process_handle) {
1450   static std::vector<OS::SharedLibraryAddress> result;
1451 
1452   static bool symbols_loaded = false;
1453 
1454   if (symbols_loaded) return result;
1455 
1456   BOOL ok;
1457 
1458   // Initialize the symbol engine.
1459   ok = _SymInitialize(process_handle,  // hProcess
1460                       nullptr,         // UserSearchPath
1461                       false);          // fInvadeProcess
1462   if (!ok) return result;
1463 
1464   DWORD options = _SymGetOptions();
1465   options |= SYMOPT_LOAD_LINES;
1466   options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1467   options = _SymSetOptions(options);
1468 
1469   char buf[OS::kStackWalkMaxNameLen] = {0};
1470   ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1471   if (!ok) {
1472     int err = GetLastError();
1473     OS::Print("%d\n", err);
1474     return result;
1475   }
1476 
1477   HANDLE snapshot = _CreateToolhelp32Snapshot(
1478       TH32CS_SNAPMODULE,       // dwFlags
1479       GetCurrentProcessId());  // th32ProcessId
1480   if (snapshot == INVALID_HANDLE_VALUE) return result;
1481   MODULEENTRY32W module_entry;
1482   module_entry.dwSize = sizeof(module_entry);  // Set the size of the structure.
1483   BOOL cont = _Module32FirstW(snapshot, &module_entry);
1484   while (cont) {
1485     DWORD64 base;
1486     // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1487     // both unicode and ASCII strings even though the parameter is PSTR.
1488     base = _SymLoadModule64(
1489         process_handle,                                       // hProcess
1490         0,                                                    // hFile
1491         reinterpret_cast<PSTR>(module_entry.szExePath),       // ImageName
1492         reinterpret_cast<PSTR>(module_entry.szModule),        // ModuleName
1493         reinterpret_cast<DWORD64>(module_entry.modBaseAddr),  // BaseOfDll
1494         module_entry.modBaseSize);                            // SizeOfDll
1495     if (base == 0) {
1496       int err = GetLastError();
1497       if (err != ERROR_MOD_NOT_FOUND &&
1498           err != ERROR_INVALID_HANDLE) {
1499         result.clear();
1500         return result;
1501       }
1502     }
1503     int lib_name_length = WideCharToMultiByte(
1504         CP_UTF8, 0, module_entry.szExePath, -1, nullptr, 0, nullptr, nullptr);
1505     std::string lib_name(lib_name_length, 0);
1506     WideCharToMultiByte(CP_UTF8, 0, module_entry.szExePath, -1, &lib_name[0],
1507                         lib_name_length, nullptr, nullptr);
1508     result.push_back(OS::SharedLibraryAddress(
1509         lib_name, reinterpret_cast<uintptr_t>(module_entry.modBaseAddr),
1510         reinterpret_cast<uintptr_t>(module_entry.modBaseAddr +
1511                                     module_entry.modBaseSize)));
1512     cont = _Module32NextW(snapshot, &module_entry);
1513   }
1514   CloseHandle(snapshot);
1515 
1516   symbols_loaded = true;
1517   return result;
1518 }
1519 
1520 
GetSharedLibraryAddresses()1521 std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
1522   // SharedLibraryEvents are logged when loading symbol information.
1523   // Only the shared libraries loaded at the time of the call to
1524   // GetSharedLibraryAddresses are logged.  DLLs loaded after
1525   // initialization are not accounted for.
1526   if (!LoadDbgHelpAndTlHelp32()) return std::vector<OS::SharedLibraryAddress>();
1527   HANDLE process_handle = GetCurrentProcess();
1528   return LoadSymbols(process_handle);
1529 }
1530 
SignalCodeMovingGC()1531 void OS::SignalCodeMovingGC() {}
1532 
1533 #else  // __MINGW32__
GetSharedLibraryAddresses()1534 std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
1535   return std::vector<OS::SharedLibraryAddress>();
1536 }
1537 
SignalCodeMovingGC()1538 void OS::SignalCodeMovingGC() {}
1539 #endif  // __MINGW32__
1540 
1541 
ActivationFrameAlignment()1542 int OS::ActivationFrameAlignment() {
1543 #ifdef _WIN64
1544   return 16;  // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1545 #elif defined(__MINGW32__)
1546   // With gcc 4.4 the tree vectorization optimizer can generate code
1547   // that requires 16 byte alignment such as movdqa on x86.
1548   return 16;
1549 #else
1550   return 8;  // Floating-point math runs faster with 8-byte alignment.
1551 #endif
1552 }
1553 
1554 #if (defined(_WIN32) || defined(_WIN64))
EnsureConsoleOutputWin32()1555 void EnsureConsoleOutputWin32() {
1556   UINT new_flags =
1557       SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
1558   UINT existing_flags = SetErrorMode(new_flags);
1559   SetErrorMode(existing_flags | new_flags);
1560 #if defined(_MSC_VER)
1561   _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1562   _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1563   _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1564   _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1565   _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1566   _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1567   _set_error_mode(_OUT_TO_STDERR);
1568 #endif  // defined(_MSC_VER)
1569 }
1570 #endif  // (defined(_WIN32) || defined(_WIN64))
1571 
1572 // ----------------------------------------------------------------------------
1573 // Win32 thread support.
1574 
1575 // Definition of invalid thread handle and id.
1576 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
1577 
1578 // Entry point for threads. The supplied argument is a pointer to the thread
1579 // object. The entry function dispatches to the run method in the thread
1580 // object. It is important that this function has __stdcall calling
1581 // convention.
ThreadEntry(void * arg)1582 static unsigned int __stdcall ThreadEntry(void* arg) {
1583   Thread* thread = reinterpret_cast<Thread*>(arg);
1584   thread->NotifyStartedAndRun();
1585   return 0;
1586 }
1587 
1588 
1589 class Thread::PlatformData {
1590  public:
PlatformData(HANDLE thread)1591   explicit PlatformData(HANDLE thread) : thread_(thread) {}
1592   HANDLE thread_;
1593   unsigned thread_id_;
1594 };
1595 
1596 
1597 // Initialize a Win32 thread object. The thread has an invalid thread
1598 // handle until it is started.
1599 
Thread(const Options & options)1600 Thread::Thread(const Options& options)
1601     : stack_size_(options.stack_size()), start_semaphore_(nullptr) {
1602   data_ = new PlatformData(kNoThread);
1603   set_name(options.name());
1604 }
1605 
1606 
set_name(const char * name)1607 void Thread::set_name(const char* name) {
1608   OS::StrNCpy(name_, sizeof(name_), name, strlen(name));
1609   name_[sizeof(name_) - 1] = '\0';
1610 }
1611 
1612 
1613 // Close our own handle for the thread.
~Thread()1614 Thread::~Thread() {
1615   if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1616   delete data_;
1617 }
1618 
1619 
1620 // Create a new thread. It is important to use _beginthreadex() instead of
1621 // the Win32 function CreateThread(), because the CreateThread() does not
1622 // initialize thread specific structures in the C runtime library.
Start()1623 bool Thread::Start() {
1624   uintptr_t result = _beginthreadex(nullptr, static_cast<unsigned>(stack_size_),
1625                                     ThreadEntry, this, 0, &data_->thread_id_);
1626   data_->thread_ = reinterpret_cast<HANDLE>(result);
1627   return result != 0;
1628 }
1629 
1630 // Wait for thread to terminate.
Join()1631 void Thread::Join() {
1632   if (data_->thread_id_ != GetCurrentThreadId()) {
1633     WaitForSingleObject(data_->thread_, INFINITE);
1634   }
1635 }
1636 
1637 
CreateThreadLocalKey()1638 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1639   DWORD result = TlsAlloc();
1640   DCHECK(result != TLS_OUT_OF_INDEXES);
1641   return static_cast<LocalStorageKey>(result);
1642 }
1643 
1644 
DeleteThreadLocalKey(LocalStorageKey key)1645 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1646   BOOL result = TlsFree(static_cast<DWORD>(key));
1647   USE(result);
1648   DCHECK(result);
1649 }
1650 
1651 
GetThreadLocal(LocalStorageKey key)1652 void* Thread::GetThreadLocal(LocalStorageKey key) {
1653   return TlsGetValue(static_cast<DWORD>(key));
1654 }
1655 
1656 
SetThreadLocal(LocalStorageKey key,void * value)1657 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1658   BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1659   USE(result);
1660   DCHECK(result);
1661 }
1662 
AdjustSchedulingParams()1663 void OS::AdjustSchedulingParams() {}
1664 
GetFreeMemoryRangesWithin(OS::Address boundary_start,OS::Address boundary_end,size_t minimum_size,size_t alignment)1665 std::vector<OS::MemoryRange> OS::GetFreeMemoryRangesWithin(
1666     OS::Address boundary_start, OS::Address boundary_end, size_t minimum_size,
1667     size_t alignment) {
1668   std::vector<OS::MemoryRange> result = {};
1669 
1670   // Search for the virtual memory (vm) ranges within the boundary.
1671   // If a range is free and larger than {minimum_size}, then push it to the
1672   // returned vector.
1673   uintptr_t vm_start = RoundUp(boundary_start, alignment);
1674   uintptr_t vm_end = 0;
1675   MEMORY_BASIC_INFORMATION mi;
1676   // This loop will terminate once the scanning reaches the higher address
1677   // to the end of boundary or the function VirtualQuery fails.
1678   while (vm_start < boundary_end &&
1679          VirtualQuery(reinterpret_cast<LPCVOID>(vm_start), &mi, sizeof(mi)) !=
1680              0) {
1681     vm_start = reinterpret_cast<uintptr_t>(mi.BaseAddress);
1682     vm_end = vm_start + mi.RegionSize;
1683     if (mi.State == MEM_FREE) {
1684       // The available area is the overlap of the virtual memory range and
1685       // boundary. Push the overlapped memory range to the vector if there is
1686       // enough space.
1687       const uintptr_t overlap_start =
1688           RoundUp(std::max(vm_start, boundary_start), alignment);
1689       const uintptr_t overlap_end =
1690           RoundDown(std::min(vm_end, boundary_end), alignment);
1691       if (overlap_start < overlap_end &&
1692           overlap_end - overlap_start >= minimum_size) {
1693         result.push_back({overlap_start, overlap_end});
1694       }
1695     }
1696     // Continue to visit the next virtual memory range.
1697     vm_start = vm_end;
1698   }
1699 
1700   return result;
1701 }
1702 
1703 // static
GetStackStart()1704 Stack::StackSlot Stack::GetStackStart() {
1705 #if defined(V8_TARGET_ARCH_X64)
1706   return reinterpret_cast<void*>(
1707       reinterpret_cast<NT_TIB64*>(NtCurrentTeb())->StackBase);
1708 #elif defined(V8_TARGET_ARCH_32_BIT)
1709   return reinterpret_cast<void*>(
1710       reinterpret_cast<NT_TIB*>(NtCurrentTeb())->StackBase);
1711 #elif defined(V8_TARGET_ARCH_ARM64)
1712   // Windows 8 and later, see
1713   // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadstacklimits
1714   ULONG_PTR lowLimit, highLimit;
1715   ::GetCurrentThreadStackLimits(&lowLimit, &highLimit);
1716   return reinterpret_cast<void*>(highLimit);
1717 #else
1718 #error Unsupported GetStackStart.
1719 #endif
1720 }
1721 
1722 // static
GetCurrentStackPosition()1723 Stack::StackSlot Stack::GetCurrentStackPosition() {
1724 #if V8_CC_MSVC
1725   return _AddressOfReturnAddress();
1726 #else
1727   return __builtin_frame_address(0);
1728 #endif
1729 }
1730 
1731 }  // namespace base
1732 }  // namespace v8
1733