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