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 #define V8_WIN32_HEADERS_FULL
     31 #include "win32-headers.h"
     32 
     33 #include "v8.h"
     34 
     35 #include "codegen.h"
     36 #include "platform.h"
     37 #include "vm-state-inl.h"
     38 
     39 #ifdef _MSC_VER
     40 
     41 // Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
     42 // defined in strings.h.
     43 int strncasecmp(const char* s1, const char* s2, int n) {
     44   return _strnicmp(s1, s2, n);
     45 }
     46 
     47 #endif  // _MSC_VER
     48 
     49 
     50 // Extra functions for MinGW. Most of these are the _s functions which are in
     51 // the Microsoft Visual Studio C++ CRT.
     52 #ifdef __MINGW32__
     53 
     54 int localtime_s(tm* out_tm, const time_t* time) {
     55   tm* posix_local_time_struct = localtime(time);
     56   if (posix_local_time_struct == NULL) return 1;
     57   *out_tm = *posix_local_time_struct;
     58   return 0;
     59 }
     60 
     61 
     62 int fopen_s(FILE** pFile, const char* filename, const char* mode) {
     63   *pFile = fopen(filename, mode);
     64   return *pFile != NULL ? 0 : 1;
     65 }
     66 
     67 
     68 #ifndef __MINGW64_VERSION_MAJOR
     69 
     70 // Not sure this the correct interpretation of _mkgmtime
     71 time_t _mkgmtime(tm* timeptr) {
     72   return mktime(timeptr);
     73 }
     74 
     75 
     76 #define _TRUNCATE 0
     77 #define STRUNCATE 80
     78 
     79 #endif  // __MINGW64_VERSION_MAJOR
     80 
     81 
     82 int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
     83                  const char* format, va_list argptr) {
     84   ASSERT(count == _TRUNCATE);
     85   return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
     86 }
     87 
     88 
     89 int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
     90   CHECK(source != NULL);
     91   CHECK(dest != NULL);
     92   CHECK_GT(dest_size, 0);
     93 
     94   if (count == _TRUNCATE) {
     95     while (dest_size > 0 && *source != 0) {
     96       *(dest++) = *(source++);
     97       --dest_size;
     98     }
     99     if (dest_size == 0) {
    100       *(dest - 1) = 0;
    101       return STRUNCATE;
    102     }
    103   } else {
    104     while (dest_size > 0 && count > 0 && *source != 0) {
    105       *(dest++) = *(source++);
    106       --dest_size;
    107       --count;
    108     }
    109   }
    110   CHECK_GT(dest_size, 0);
    111   *dest = 0;
    112   return 0;
    113 }
    114 
    115 
    116 #ifndef __MINGW64_VERSION_MAJOR
    117 
    118 inline void MemoryBarrier() {
    119   int barrier = 0;
    120   __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
    121 }
    122 
    123 #endif  // __MINGW64_VERSION_MAJOR
    124 
    125 
    126 #endif  // __MINGW32__
    127 
    128 // Generate a pseudo-random number in the range 0-2^31-1. Usually
    129 // defined in stdlib.h. Missing in both Microsoft Visual Studio C++ and MinGW.
    130 int random() {
    131   return rand();
    132 }
    133 
    134 
    135 namespace v8 {
    136 namespace internal {
    137 
    138 intptr_t OS::MaxVirtualMemory() {
    139   return 0;
    140 }
    141 
    142 
    143 double ceiling(double x) {
    144   return ceil(x);
    145 }
    146 
    147 
    148 static Mutex* limit_mutex = NULL;
    149 
    150 #if defined(V8_TARGET_ARCH_IA32)
    151 static OS::MemCopyFunction memcopy_function = NULL;
    152 static LazyMutex memcopy_function_mutex = LAZY_MUTEX_INITIALIZER;
    153 // Defined in codegen-ia32.cc.
    154 OS::MemCopyFunction CreateMemCopyFunction();
    155 
    156 // Copy memory area to disjoint memory area.
    157 void OS::MemCopy(void* dest, const void* src, size_t size) {
    158   if (memcopy_function == NULL) {
    159     ScopedLock lock(memcopy_function_mutex.Pointer());
    160     if (memcopy_function == NULL) {
    161       OS::MemCopyFunction temp = CreateMemCopyFunction();
    162       MemoryBarrier();
    163       memcopy_function = temp;
    164     }
    165   }
    166   // Note: here we rely on dependent reads being ordered. This is true
    167   // on all architectures we currently support.
    168   (*memcopy_function)(dest, src, size);
    169 #ifdef DEBUG
    170   CHECK_EQ(0, memcmp(dest, src, size));
    171 #endif
    172 }
    173 #endif  // V8_TARGET_ARCH_IA32
    174 
    175 #ifdef _WIN64
    176 typedef double (*ModuloFunction)(double, double);
    177 static ModuloFunction modulo_function = NULL;
    178 // Defined in codegen-x64.cc.
    179 ModuloFunction CreateModuloFunction();
    180 
    181 void init_modulo_function() {
    182   modulo_function = CreateModuloFunction();
    183 }
    184 
    185 double modulo(double x, double y) {
    186   // Note: here we rely on dependent reads being ordered. This is true
    187   // on all architectures we currently support.
    188   return (*modulo_function)(x, y);
    189 }
    190 #else  // Win32
    191 
    192 double modulo(double x, double y) {
    193   // Workaround MS fmod bugs. ECMA-262 says:
    194   // dividend is finite and divisor is an infinity => result equals dividend
    195   // dividend is a zero and divisor is nonzero finite => result equals dividend
    196   if (!(isfinite(x) && (!isfinite(y) && !isnan(y))) &&
    197       !(x == 0 && (y != 0 && isfinite(y)))) {
    198     x = fmod(x, y);
    199   }
    200   return x;
    201 }
    202 
    203 #endif  // _WIN64
    204 
    205 
    206 #define UNARY_MATH_FUNCTION(name, generator)             \
    207 static UnaryMathFunction fast_##name##_function = NULL;  \
    208 void init_fast_##name##_function() {                     \
    209   fast_##name##_function = generator;                    \
    210 }                                                        \
    211 double fast_##name(double x) {                           \
    212   return (*fast_##name##_function)(x);                   \
    213 }
    214 
    215 UNARY_MATH_FUNCTION(sin, CreateTranscendentalFunction(TranscendentalCache::SIN))
    216 UNARY_MATH_FUNCTION(cos, CreateTranscendentalFunction(TranscendentalCache::COS))
    217 UNARY_MATH_FUNCTION(tan, CreateTranscendentalFunction(TranscendentalCache::TAN))
    218 UNARY_MATH_FUNCTION(log, CreateTranscendentalFunction(TranscendentalCache::LOG))
    219 UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
    220 
    221 #undef MATH_FUNCTION
    222 
    223 
    224 void MathSetup() {
    225 #ifdef _WIN64
    226   init_modulo_function();
    227 #endif
    228   init_fast_sin_function();
    229   init_fast_cos_function();
    230   init_fast_tan_function();
    231   init_fast_log_function();
    232   init_fast_sqrt_function();
    233 }
    234 
    235 
    236 // ----------------------------------------------------------------------------
    237 // The Time class represents time on win32. A timestamp is represented as
    238 // a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
    239 // timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
    240 // January 1, 1970.
    241 
    242 class Time {
    243  public:
    244   // Constructors.
    245   Time();
    246   explicit Time(double jstime);
    247   Time(int year, int mon, int day, int hour, int min, int sec);
    248 
    249   // Convert timestamp to JavaScript representation.
    250   double ToJSTime();
    251 
    252   // Set timestamp to current time.
    253   void SetToCurrentTime();
    254 
    255   // Returns the local timezone offset in milliseconds east of UTC. This is
    256   // the number of milliseconds you must add to UTC to get local time, i.e.
    257   // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
    258   // routine also takes into account whether daylight saving is effect
    259   // at the time.
    260   int64_t LocalOffset();
    261 
    262   // Returns the daylight savings time offset for the time in milliseconds.
    263   int64_t DaylightSavingsOffset();
    264 
    265   // Returns a string identifying the current timezone for the
    266   // timestamp taking into account daylight saving.
    267   char* LocalTimezone();
    268 
    269  private:
    270   // Constants for time conversion.
    271   static const int64_t kTimeEpoc = 116444736000000000LL;
    272   static const int64_t kTimeScaler = 10000;
    273   static const int64_t kMsPerMinute = 60000;
    274 
    275   // Constants for timezone information.
    276   static const int kTzNameSize = 128;
    277   static const bool kShortTzNames = false;
    278 
    279   // Timezone information. We need to have static buffers for the
    280   // timezone names because we return pointers to these in
    281   // LocalTimezone().
    282   static bool tz_initialized_;
    283   static TIME_ZONE_INFORMATION tzinfo_;
    284   static char std_tz_name_[kTzNameSize];
    285   static char dst_tz_name_[kTzNameSize];
    286 
    287   // Initialize the timezone information (if not already done).
    288   static void TzSet();
    289 
    290   // Guess the name of the timezone from the bias.
    291   static const char* GuessTimezoneNameFromBias(int bias);
    292 
    293   // Return whether or not daylight savings time is in effect at this time.
    294   bool InDST();
    295 
    296   // Return the difference (in milliseconds) between this timestamp and
    297   // another timestamp.
    298   int64_t Diff(Time* other);
    299 
    300   // Accessor for FILETIME representation.
    301   FILETIME& ft() { return time_.ft_; }
    302 
    303   // Accessor for integer representation.
    304   int64_t& t() { return time_.t_; }
    305 
    306   // Although win32 uses 64-bit integers for representing timestamps,
    307   // these are packed into a FILETIME structure. The FILETIME structure
    308   // is just a struct representing a 64-bit integer. The TimeStamp union
    309   // allows access to both a FILETIME and an integer representation of
    310   // the timestamp.
    311   union TimeStamp {
    312     FILETIME ft_;
    313     int64_t t_;
    314   };
    315 
    316   TimeStamp time_;
    317 };
    318 
    319 // Static variables.
    320 bool Time::tz_initialized_ = false;
    321 TIME_ZONE_INFORMATION Time::tzinfo_;
    322 char Time::std_tz_name_[kTzNameSize];
    323 char Time::dst_tz_name_[kTzNameSize];
    324 
    325 
    326 // Initialize timestamp to start of epoc.
    327 Time::Time() {
    328   t() = 0;
    329 }
    330 
    331 
    332 // Initialize timestamp from a JavaScript timestamp.
    333 Time::Time(double jstime) {
    334   t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
    335 }
    336 
    337 
    338 // Initialize timestamp from date/time components.
    339 Time::Time(int year, int mon, int day, int hour, int min, int sec) {
    340   SYSTEMTIME st;
    341   st.wYear = year;
    342   st.wMonth = mon;
    343   st.wDay = day;
    344   st.wHour = hour;
    345   st.wMinute = min;
    346   st.wSecond = sec;
    347   st.wMilliseconds = 0;
    348   SystemTimeToFileTime(&st, &ft());
    349 }
    350 
    351 
    352 // Convert timestamp to JavaScript timestamp.
    353 double Time::ToJSTime() {
    354   return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
    355 }
    356 
    357 
    358 // Guess the name of the timezone from the bias.
    359 // The guess is very biased towards the northern hemisphere.
    360 const char* Time::GuessTimezoneNameFromBias(int bias) {
    361   static const int kHour = 60;
    362   switch (-bias) {
    363     case -9*kHour: return "Alaska";
    364     case -8*kHour: return "Pacific";
    365     case -7*kHour: return "Mountain";
    366     case -6*kHour: return "Central";
    367     case -5*kHour: return "Eastern";
    368     case -4*kHour: return "Atlantic";
    369     case  0*kHour: return "GMT";
    370     case +1*kHour: return "Central Europe";
    371     case +2*kHour: return "Eastern Europe";
    372     case +3*kHour: return "Russia";
    373     case +5*kHour + 30: return "India";
    374     case +8*kHour: return "China";
    375     case +9*kHour: return "Japan";
    376     case +12*kHour: return "New Zealand";
    377     default: return "Local";
    378   }
    379 }
    380 
    381 
    382 // Initialize timezone information. The timezone information is obtained from
    383 // windows. If we cannot get the timezone information we fall back to CET.
    384 // Please notice that this code is not thread-safe.
    385 void Time::TzSet() {
    386   // Just return if timezone information has already been initialized.
    387   if (tz_initialized_) return;
    388 
    389   // Initialize POSIX time zone data.
    390   _tzset();
    391   // Obtain timezone information from operating system.
    392   memset(&tzinfo_, 0, sizeof(tzinfo_));
    393   if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
    394     // If we cannot get timezone information we fall back to CET.
    395     tzinfo_.Bias = -60;
    396     tzinfo_.StandardDate.wMonth = 10;
    397     tzinfo_.StandardDate.wDay = 5;
    398     tzinfo_.StandardDate.wHour = 3;
    399     tzinfo_.StandardBias = 0;
    400     tzinfo_.DaylightDate.wMonth = 3;
    401     tzinfo_.DaylightDate.wDay = 5;
    402     tzinfo_.DaylightDate.wHour = 2;
    403     tzinfo_.DaylightBias = -60;
    404   }
    405 
    406   // Make standard and DST timezone names.
    407   WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
    408                       std_tz_name_, kTzNameSize, NULL, NULL);
    409   std_tz_name_[kTzNameSize - 1] = '\0';
    410   WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
    411                       dst_tz_name_, kTzNameSize, NULL, NULL);
    412   dst_tz_name_[kTzNameSize - 1] = '\0';
    413 
    414   // If OS returned empty string or resource id (like "@tzres.dll,-211")
    415   // simply guess the name from the UTC bias of the timezone.
    416   // To properly resolve the resource identifier requires a library load,
    417   // which is not possible in a sandbox.
    418   if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
    419     OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
    420                  "%s Standard Time",
    421                  GuessTimezoneNameFromBias(tzinfo_.Bias));
    422   }
    423   if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
    424     OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
    425                  "%s Daylight Time",
    426                  GuessTimezoneNameFromBias(tzinfo_.Bias));
    427   }
    428 
    429   // Timezone information initialized.
    430   tz_initialized_ = true;
    431 }
    432 
    433 
    434 // Return the difference in milliseconds between this and another timestamp.
    435 int64_t Time::Diff(Time* other) {
    436   return (t() - other->t()) / kTimeScaler;
    437 }
    438 
    439 
    440 // Set timestamp to current time.
    441 void Time::SetToCurrentTime() {
    442   // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
    443   // Because we're fast, we like fast timers which have at least a
    444   // 1ms resolution.
    445   //
    446   // timeGetTime() provides 1ms granularity when combined with
    447   // timeBeginPeriod().  If the host application for v8 wants fast
    448   // timers, it can use timeBeginPeriod to increase the resolution.
    449   //
    450   // Using timeGetTime() has a drawback because it is a 32bit value
    451   // and hence rolls-over every ~49days.
    452   //
    453   // To use the clock, we use GetSystemTimeAsFileTime as our base;
    454   // and then use timeGetTime to extrapolate current time from the
    455   // start time.  To deal with rollovers, we resync the clock
    456   // any time when more than kMaxClockElapsedTime has passed or
    457   // whenever timeGetTime creates a rollover.
    458 
    459   static bool initialized = false;
    460   static TimeStamp init_time;
    461   static DWORD init_ticks;
    462   static const int64_t kHundredNanosecondsPerSecond = 10000000;
    463   static const int64_t kMaxClockElapsedTime =
    464       60*kHundredNanosecondsPerSecond;  // 1 minute
    465 
    466   // If we are uninitialized, we need to resync the clock.
    467   bool needs_resync = !initialized;
    468 
    469   // Get the current time.
    470   TimeStamp time_now;
    471   GetSystemTimeAsFileTime(&time_now.ft_);
    472   DWORD ticks_now = timeGetTime();
    473 
    474   // Check if we need to resync due to clock rollover.
    475   needs_resync |= ticks_now < init_ticks;
    476 
    477   // Check if we need to resync due to elapsed time.
    478   needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
    479 
    480   // Resync the clock if necessary.
    481   if (needs_resync) {
    482     GetSystemTimeAsFileTime(&init_time.ft_);
    483     init_ticks = ticks_now = timeGetTime();
    484     initialized = true;
    485   }
    486 
    487   // Finally, compute the actual time.  Why is this so hard.
    488   DWORD elapsed = ticks_now - init_ticks;
    489   this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
    490 }
    491 
    492 
    493 // Return the local timezone offset in milliseconds east of UTC. This
    494 // takes into account whether daylight saving is in effect at the time.
    495 // Only times in the 32-bit Unix range may be passed to this function.
    496 // Also, adding the time-zone offset to the input must not overflow.
    497 // The function EquivalentTime() in date.js guarantees this.
    498 int64_t Time::LocalOffset() {
    499   // Initialize timezone information, if needed.
    500   TzSet();
    501 
    502   Time rounded_to_second(*this);
    503   rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
    504       1000 * kTimeScaler;
    505   // Convert to local time using POSIX localtime function.
    506   // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
    507   // very slow.  Other browsers use localtime().
    508 
    509   // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
    510   // POSIX seconds past 1/1/1970 0:00:00.
    511   double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
    512   if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
    513     return 0;
    514   }
    515   // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
    516   time_t posix_time = static_cast<time_t>(unchecked_posix_time);
    517 
    518   // Convert to local time, as struct with fields for day, hour, year, etc.
    519   tm posix_local_time_struct;
    520   if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
    521   // Convert local time in struct to POSIX time as if it were a UTC time.
    522   time_t local_posix_time = _mkgmtime(&posix_local_time_struct);
    523   Time localtime(1000.0 * local_posix_time);
    524 
    525   return localtime.Diff(&rounded_to_second);
    526 }
    527 
    528 
    529 // Return whether or not daylight savings time is in effect at this time.
    530 bool Time::InDST() {
    531   // Initialize timezone information, if needed.
    532   TzSet();
    533 
    534   // Determine if DST is in effect at the specified time.
    535   bool in_dst = false;
    536   if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) {
    537     // Get the local timezone offset for the timestamp in milliseconds.
    538     int64_t offset = LocalOffset();
    539 
    540     // Compute the offset for DST. The bias parameters in the timezone info
    541     // are specified in minutes. These must be converted to milliseconds.
    542     int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute;
    543 
    544     // If the local time offset equals the timezone bias plus the daylight
    545     // bias then DST is in effect.
    546     in_dst = offset == dstofs;
    547   }
    548 
    549   return in_dst;
    550 }
    551 
    552 
    553 // Return the daylight savings time offset for this time.
    554 int64_t Time::DaylightSavingsOffset() {
    555   return InDST() ? 60 * kMsPerMinute : 0;
    556 }
    557 
    558 
    559 // Returns a string identifying the current timezone for the
    560 // timestamp taking into account daylight saving.
    561 char* Time::LocalTimezone() {
    562   // Return the standard or DST time zone name based on whether daylight
    563   // saving is in effect at the given time.
    564   return InDST() ? dst_tz_name_ : std_tz_name_;
    565 }
    566 
    567 
    568 void OS::SetUp() {
    569   // Seed the random number generator.
    570   // Convert the current time to a 64-bit integer first, before converting it
    571   // to an unsigned. Going directly can cause an overflow and the seed to be
    572   // set to all ones. The seed will be identical for different instances that
    573   // call this setup code within the same millisecond.
    574   uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
    575   srand(static_cast<unsigned int>(seed));
    576   limit_mutex = CreateMutex();
    577 }
    578 
    579 
    580 void OS::PostSetUp() {
    581   // Math functions depend on CPU features therefore they are initialized after
    582   // CPU.
    583   MathSetup();
    584 }
    585 
    586 
    587 // Returns the accumulated user time for thread.
    588 int OS::GetUserTime(uint32_t* secs,  uint32_t* usecs) {
    589   FILETIME dummy;
    590   uint64_t usertime;
    591 
    592   // Get the amount of time that the thread has executed in user mode.
    593   if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
    594                       reinterpret_cast<FILETIME*>(&usertime))) return -1;
    595 
    596   // Adjust the resolution to micro-seconds.
    597   usertime /= 10;
    598 
    599   // Convert to seconds and microseconds
    600   *secs = static_cast<uint32_t>(usertime / 1000000);
    601   *usecs = static_cast<uint32_t>(usertime % 1000000);
    602   return 0;
    603 }
    604 
    605 
    606 // Returns current time as the number of milliseconds since
    607 // 00:00:00 UTC, January 1, 1970.
    608 double OS::TimeCurrentMillis() {
    609   Time t;
    610   t.SetToCurrentTime();
    611   return t.ToJSTime();
    612 }
    613 
    614 // Returns the tickcounter based on timeGetTime.
    615 int64_t OS::Ticks() {
    616   return timeGetTime() * 1000;  // Convert to microseconds.
    617 }
    618 
    619 
    620 // Returns a string identifying the current timezone taking into
    621 // account daylight saving.
    622 const char* OS::LocalTimezone(double time) {
    623   return Time(time).LocalTimezone();
    624 }
    625 
    626 
    627 // Returns the local time offset in milliseconds east of UTC without
    628 // taking daylight savings time into account.
    629 double OS::LocalTimeOffset() {
    630   // Use current time, rounded to the millisecond.
    631   Time t(TimeCurrentMillis());
    632   // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
    633   return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset());
    634 }
    635 
    636 
    637 // Returns the daylight savings offset in milliseconds for the given
    638 // time.
    639 double OS::DaylightSavingsOffset(double time) {
    640   int64_t offset = Time(time).DaylightSavingsOffset();
    641   return static_cast<double>(offset);
    642 }
    643 
    644 
    645 int OS::GetLastError() {
    646   return ::GetLastError();
    647 }
    648 
    649 
    650 // ----------------------------------------------------------------------------
    651 // Win32 console output.
    652 //
    653 // If a Win32 application is linked as a console application it has a normal
    654 // standard output and standard error. In this case normal printf works fine
    655 // for output. However, if the application is linked as a GUI application,
    656 // the process doesn't have a console, and therefore (debugging) output is lost.
    657 // This is the case if we are embedded in a windows program (like a browser).
    658 // In order to be able to get debug output in this case the the debugging
    659 // facility using OutputDebugString. This output goes to the active debugger
    660 // for the process (if any). Else the output can be monitored using DBMON.EXE.
    661 
    662 enum OutputMode {
    663   UNKNOWN,  // Output method has not yet been determined.
    664   CONSOLE,  // Output is written to stdout.
    665   ODS       // Output is written to debug facility.
    666 };
    667 
    668 static OutputMode output_mode = UNKNOWN;  // Current output mode.
    669 
    670 
    671 // Determine if the process has a console for output.
    672 static bool HasConsole() {
    673   // Only check the first time. Eventual race conditions are not a problem,
    674   // because all threads will eventually determine the same mode.
    675   if (output_mode == UNKNOWN) {
    676     // We cannot just check that the standard output is attached to a console
    677     // because this would fail if output is redirected to a file. Therefore we
    678     // say that a process does not have an output console if either the
    679     // standard output handle is invalid or its file type is unknown.
    680     if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
    681         GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
    682       output_mode = CONSOLE;
    683     else
    684       output_mode = ODS;
    685   }
    686   return output_mode == CONSOLE;
    687 }
    688 
    689 
    690 static void VPrintHelper(FILE* stream, const char* format, va_list args) {
    691   if (HasConsole()) {
    692     vfprintf(stream, format, args);
    693   } else {
    694     // It is important to use safe print here in order to avoid
    695     // overflowing the buffer. We might truncate the output, but this
    696     // does not crash.
    697     EmbeddedVector<char, 4096> buffer;
    698     OS::VSNPrintF(buffer, format, args);
    699     OutputDebugStringA(buffer.start());
    700   }
    701 }
    702 
    703 
    704 FILE* OS::FOpen(const char* path, const char* mode) {
    705   FILE* result;
    706   if (fopen_s(&result, path, mode) == 0) {
    707     return result;
    708   } else {
    709     return NULL;
    710   }
    711 }
    712 
    713 
    714 bool OS::Remove(const char* path) {
    715   return (DeleteFileA(path) != 0);
    716 }
    717 
    718 
    719 FILE* OS::OpenTemporaryFile() {
    720   // tmpfile_s tries to use the root dir, don't use it.
    721   char tempPathBuffer[MAX_PATH];
    722   DWORD path_result = 0;
    723   path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
    724   if (path_result > MAX_PATH || path_result == 0) return NULL;
    725   UINT name_result = 0;
    726   char tempNameBuffer[MAX_PATH];
    727   name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
    728   if (name_result == 0) return NULL;
    729   FILE* result = FOpen(tempNameBuffer, "w+");  // Same mode as tmpfile uses.
    730   if (result != NULL) {
    731     Remove(tempNameBuffer);  // Delete on close.
    732   }
    733   return result;
    734 }
    735 
    736 
    737 // Open log file in binary mode to avoid /n -> /r/n conversion.
    738 const char* const OS::LogFileOpenMode = "wb";
    739 
    740 
    741 // Print (debug) message to console.
    742 void OS::Print(const char* format, ...) {
    743   va_list args;
    744   va_start(args, format);
    745   VPrint(format, args);
    746   va_end(args);
    747 }
    748 
    749 
    750 void OS::VPrint(const char* format, va_list args) {
    751   VPrintHelper(stdout, format, args);
    752 }
    753 
    754 
    755 void OS::FPrint(FILE* out, const char* format, ...) {
    756   va_list args;
    757   va_start(args, format);
    758   VFPrint(out, format, args);
    759   va_end(args);
    760 }
    761 
    762 
    763 void OS::VFPrint(FILE* out, const char* format, va_list args) {
    764   VPrintHelper(out, format, args);
    765 }
    766 
    767 
    768 // Print error message to console.
    769 void OS::PrintError(const char* format, ...) {
    770   va_list args;
    771   va_start(args, format);
    772   VPrintError(format, args);
    773   va_end(args);
    774 }
    775 
    776 
    777 void OS::VPrintError(const char* format, va_list args) {
    778   VPrintHelper(stderr, format, args);
    779 }
    780 
    781 
    782 int OS::SNPrintF(Vector<char> str, const char* format, ...) {
    783   va_list args;
    784   va_start(args, format);
    785   int result = VSNPrintF(str, format, args);
    786   va_end(args);
    787   return result;
    788 }
    789 
    790 
    791 int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
    792   int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
    793   // Make sure to zero-terminate the string if the output was
    794   // truncated or if there was an error.
    795   if (n < 0 || n >= str.length()) {
    796     if (str.length() > 0)
    797       str[str.length() - 1] = '\0';
    798     return -1;
    799   } else {
    800     return n;
    801   }
    802 }
    803 
    804 
    805 char* OS::StrChr(char* str, int c) {
    806   return const_cast<char*>(strchr(str, c));
    807 }
    808 
    809 
    810 void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
    811   // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
    812   size_t buffer_size = static_cast<size_t>(dest.length());
    813   if (n + 1 > buffer_size)  // count for trailing '\0'
    814     n = _TRUNCATE;
    815   int result = strncpy_s(dest.start(), dest.length(), src, n);
    816   USE(result);
    817   ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
    818 }
    819 
    820 
    821 // We keep the lowest and highest addresses mapped as a quick way of
    822 // determining that pointers are outside the heap (used mostly in assertions
    823 // and verification).  The estimate is conservative, i.e., not all addresses in
    824 // 'allocated' space are actually allocated to our heap.  The range is
    825 // [lowest, highest), inclusive on the low and and exclusive on the high end.
    826 static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
    827 static void* highest_ever_allocated = reinterpret_cast<void*>(0);
    828 
    829 
    830 static void UpdateAllocatedSpaceLimits(void* address, int size) {
    831   ASSERT(limit_mutex != NULL);
    832   ScopedLock lock(limit_mutex);
    833 
    834   lowest_ever_allocated = Min(lowest_ever_allocated, address);
    835   highest_ever_allocated =
    836       Max(highest_ever_allocated,
    837           reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
    838 }
    839 
    840 
    841 bool OS::IsOutsideAllocatedSpace(void* pointer) {
    842   if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated)
    843     return true;
    844   // Ask the Windows API
    845   if (IsBadWritePtr(pointer, 1))
    846     return true;
    847   return false;
    848 }
    849 
    850 
    851 // Get the system's page size used by VirtualAlloc() or the next power
    852 // of two. The reason for always returning a power of two is that the
    853 // rounding up in OS::Allocate expects that.
    854 static size_t GetPageSize() {
    855   static size_t page_size = 0;
    856   if (page_size == 0) {
    857     SYSTEM_INFO info;
    858     GetSystemInfo(&info);
    859     page_size = RoundUpToPowerOf2(info.dwPageSize);
    860   }
    861   return page_size;
    862 }
    863 
    864 
    865 // The allocation alignment is the guaranteed alignment for
    866 // VirtualAlloc'ed blocks of memory.
    867 size_t OS::AllocateAlignment() {
    868   static size_t allocate_alignment = 0;
    869   if (allocate_alignment == 0) {
    870     SYSTEM_INFO info;
    871     GetSystemInfo(&info);
    872     allocate_alignment = info.dwAllocationGranularity;
    873   }
    874   return allocate_alignment;
    875 }
    876 
    877 
    878 static void* GetRandomAddr() {
    879   Isolate* isolate = Isolate::UncheckedCurrent();
    880   // Note that the current isolate isn't set up in a call path via
    881   // CpuFeatures::Probe. We don't care about randomization in this case because
    882   // the code page is immediately freed.
    883   if (isolate != NULL) {
    884     // The address range used to randomize RWX allocations in OS::Allocate
    885     // Try not to map pages into the default range that windows loads DLLs
    886     // Use a multiple of 64k to prevent committing unused memory.
    887     // Note: This does not guarantee RWX regions will be within the
    888     // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
    889 #ifdef V8_HOST_ARCH_64_BIT
    890     static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
    891     static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
    892 #else
    893     static const intptr_t kAllocationRandomAddressMin = 0x04000000;
    894     static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
    895 #endif
    896     uintptr_t address = (V8::RandomPrivate(isolate) << kPageSizeBits)
    897         | kAllocationRandomAddressMin;
    898     address &= kAllocationRandomAddressMax;
    899     return reinterpret_cast<void *>(address);
    900   }
    901   return NULL;
    902 }
    903 
    904 
    905 static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
    906   LPVOID base = NULL;
    907 
    908   if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
    909     // For exectutable pages try and randomize the allocation address
    910     for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
    911       base = VirtualAlloc(GetRandomAddr(), size, action, protection);
    912     }
    913   }
    914 
    915   // After three attempts give up and let the OS find an address to use.
    916   if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
    917 
    918   return base;
    919 }
    920 
    921 
    922 void* OS::Allocate(const size_t requested,
    923                    size_t* allocated,
    924                    bool is_executable) {
    925   // VirtualAlloc rounds allocated size to page size automatically.
    926   size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
    927 
    928   // Windows XP SP2 allows Data Excution Prevention (DEP).
    929   int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
    930 
    931   LPVOID mbase = RandomizedVirtualAlloc(msize,
    932                                         MEM_COMMIT | MEM_RESERVE,
    933                                         prot);
    934 
    935   if (mbase == NULL) {
    936     LOG(ISOLATE, StringEvent("OS::Allocate", "VirtualAlloc failed"));
    937     return NULL;
    938   }
    939 
    940   ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
    941 
    942   *allocated = msize;
    943   UpdateAllocatedSpaceLimits(mbase, static_cast<int>(msize));
    944   return mbase;
    945 }
    946 
    947 
    948 void OS::Free(void* address, const size_t size) {
    949   // TODO(1240712): VirtualFree has a return value which is ignored here.
    950   VirtualFree(address, 0, MEM_RELEASE);
    951   USE(size);
    952 }
    953 
    954 
    955 intptr_t OS::CommitPageSize() {
    956   return 4096;
    957 }
    958 
    959 
    960 void OS::ProtectCode(void* address, const size_t size) {
    961   DWORD old_protect;
    962   VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
    963 }
    964 
    965 
    966 void OS::Guard(void* address, const size_t size) {
    967   DWORD oldprotect;
    968   VirtualProtect(address, size, PAGE_READONLY | PAGE_GUARD, &oldprotect);
    969 }
    970 
    971 
    972 void OS::Sleep(int milliseconds) {
    973   ::Sleep(milliseconds);
    974 }
    975 
    976 
    977 void OS::Abort() {
    978   if (IsDebuggerPresent() || FLAG_break_on_abort) {
    979     DebugBreak();
    980   } else {
    981     // Make the MSVCRT do a silent abort.
    982     raise(SIGABRT);
    983   }
    984 }
    985 
    986 
    987 void OS::DebugBreak() {
    988 #ifdef _MSC_VER
    989   __debugbreak();
    990 #else
    991   ::DebugBreak();
    992 #endif
    993 }
    994 
    995 
    996 class Win32MemoryMappedFile : public OS::MemoryMappedFile {
    997  public:
    998   Win32MemoryMappedFile(HANDLE file,
    999                         HANDLE file_mapping,
   1000                         void* memory,
   1001                         int size)
   1002       : file_(file),
   1003         file_mapping_(file_mapping),
   1004         memory_(memory),
   1005         size_(size) { }
   1006   virtual ~Win32MemoryMappedFile();
   1007   virtual void* memory() { return memory_; }
   1008   virtual int size() { return size_; }
   1009  private:
   1010   HANDLE file_;
   1011   HANDLE file_mapping_;
   1012   void* memory_;
   1013   int size_;
   1014 };
   1015 
   1016 
   1017 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
   1018   // Open a physical file
   1019   HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
   1020       FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
   1021   if (file == INVALID_HANDLE_VALUE) return NULL;
   1022 
   1023   int size = static_cast<int>(GetFileSize(file, NULL));
   1024 
   1025   // Create a file mapping for the physical file
   1026   HANDLE file_mapping = CreateFileMapping(file, NULL,
   1027       PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
   1028   if (file_mapping == NULL) return NULL;
   1029 
   1030   // Map a view of the file into memory
   1031   void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
   1032   return new Win32MemoryMappedFile(file, file_mapping, memory, size);
   1033 }
   1034 
   1035 
   1036 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
   1037     void* initial) {
   1038   // Open a physical file
   1039   HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
   1040       FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
   1041   if (file == NULL) return NULL;
   1042   // Create a file mapping for the physical file
   1043   HANDLE file_mapping = CreateFileMapping(file, NULL,
   1044       PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
   1045   if (file_mapping == NULL) return NULL;
   1046   // Map a view of the file into memory
   1047   void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
   1048   if (memory) memmove(memory, initial, size);
   1049   return new Win32MemoryMappedFile(file, file_mapping, memory, size);
   1050 }
   1051 
   1052 
   1053 Win32MemoryMappedFile::~Win32MemoryMappedFile() {
   1054   if (memory_ != NULL)
   1055     UnmapViewOfFile(memory_);
   1056   CloseHandle(file_mapping_);
   1057   CloseHandle(file_);
   1058 }
   1059 
   1060 
   1061 // The following code loads functions defined in DbhHelp.h and TlHelp32.h
   1062 // dynamically. This is to avoid being depending on dbghelp.dll and
   1063 // tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
   1064 // kernel32.dll at some point so loading functions defines in TlHelp32.h
   1065 // dynamically might not be necessary any more - for some versions of Windows?).
   1066 
   1067 // Function pointers to functions dynamically loaded from dbghelp.dll.
   1068 #define DBGHELP_FUNCTION_LIST(V)  \
   1069   V(SymInitialize)                \
   1070   V(SymGetOptions)                \
   1071   V(SymSetOptions)                \
   1072   V(SymGetSearchPath)             \
   1073   V(SymLoadModule64)              \
   1074   V(StackWalk64)                  \
   1075   V(SymGetSymFromAddr64)          \
   1076   V(SymGetLineFromAddr64)         \
   1077   V(SymFunctionTableAccess64)     \
   1078   V(SymGetModuleBase64)
   1079 
   1080 // Function pointers to functions dynamically loaded from dbghelp.dll.
   1081 #define TLHELP32_FUNCTION_LIST(V)  \
   1082   V(CreateToolhelp32Snapshot)      \
   1083   V(Module32FirstW)                \
   1084   V(Module32NextW)
   1085 
   1086 // Define the decoration to use for the type and variable name used for
   1087 // dynamically loaded DLL function..
   1088 #define DLL_FUNC_TYPE(name) _##name##_
   1089 #define DLL_FUNC_VAR(name) _##name
   1090 
   1091 // Define the type for each dynamically loaded DLL function. The function
   1092 // definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
   1093 // from the Windows include files are redefined here to have the function
   1094 // definitions to be as close to the ones in the original .h files as possible.
   1095 #ifndef IN
   1096 #define IN
   1097 #endif
   1098 #ifndef VOID
   1099 #define VOID void
   1100 #endif
   1101 
   1102 // DbgHelp isn't supported on MinGW yet
   1103 #ifndef __MINGW32__
   1104 // DbgHelp.h functions.
   1105 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
   1106                                                        IN PSTR UserSearchPath,
   1107                                                        IN BOOL fInvadeProcess);
   1108 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
   1109 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
   1110 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
   1111     IN HANDLE hProcess,
   1112     OUT PSTR SearchPath,
   1113     IN DWORD SearchPathLength);
   1114 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
   1115     IN HANDLE hProcess,
   1116     IN HANDLE hFile,
   1117     IN PSTR ImageName,
   1118     IN PSTR ModuleName,
   1119     IN DWORD64 BaseOfDll,
   1120     IN DWORD SizeOfDll);
   1121 typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
   1122     DWORD MachineType,
   1123     HANDLE hProcess,
   1124     HANDLE hThread,
   1125     LPSTACKFRAME64 StackFrame,
   1126     PVOID ContextRecord,
   1127     PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
   1128     PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
   1129     PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
   1130     PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
   1131 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
   1132     IN HANDLE hProcess,
   1133     IN DWORD64 qwAddr,
   1134     OUT PDWORD64 pdwDisplacement,
   1135     OUT PIMAGEHLP_SYMBOL64 Symbol);
   1136 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
   1137     IN HANDLE hProcess,
   1138     IN DWORD64 qwAddr,
   1139     OUT PDWORD pdwDisplacement,
   1140     OUT PIMAGEHLP_LINE64 Line64);
   1141 // DbgHelp.h typedefs. Implementation found in dbghelp.dll.
   1142 typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
   1143     HANDLE hProcess,
   1144     DWORD64 AddrBase);  // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
   1145 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
   1146     HANDLE hProcess,
   1147     DWORD64 AddrBase);  // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
   1148 
   1149 // TlHelp32.h functions.
   1150 typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
   1151     DWORD dwFlags,
   1152     DWORD th32ProcessID);
   1153 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
   1154                                                         LPMODULEENTRY32W lpme);
   1155 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
   1156                                                        LPMODULEENTRY32W lpme);
   1157 
   1158 #undef IN
   1159 #undef VOID
   1160 
   1161 // Declare a variable for each dynamically loaded DLL function.
   1162 #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
   1163 DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
   1164 TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
   1165 #undef DEF_DLL_FUNCTION
   1166 
   1167 // Load the functions. This function has a lot of "ugly" macros in order to
   1168 // keep down code duplication.
   1169 
   1170 static bool LoadDbgHelpAndTlHelp32() {
   1171   static bool dbghelp_loaded = false;
   1172 
   1173   if (dbghelp_loaded) return true;
   1174 
   1175   HMODULE module;
   1176 
   1177   // Load functions from the dbghelp.dll module.
   1178   module = LoadLibrary(TEXT("dbghelp.dll"));
   1179   if (module == NULL) {
   1180     return false;
   1181   }
   1182 
   1183 #define LOAD_DLL_FUNC(name)                                                 \
   1184   DLL_FUNC_VAR(name) =                                                      \
   1185       reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
   1186 
   1187 DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
   1188 
   1189 #undef LOAD_DLL_FUNC
   1190 
   1191   // Load functions from the kernel32.dll module (the TlHelp32.h function used
   1192   // to be in tlhelp32.dll but are now moved to kernel32.dll).
   1193   module = LoadLibrary(TEXT("kernel32.dll"));
   1194   if (module == NULL) {
   1195     return false;
   1196   }
   1197 
   1198 #define LOAD_DLL_FUNC(name)                                                 \
   1199   DLL_FUNC_VAR(name) =                                                      \
   1200       reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
   1201 
   1202 TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
   1203 
   1204 #undef LOAD_DLL_FUNC
   1205 
   1206   // Check that all functions where loaded.
   1207   bool result =
   1208 #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
   1209 
   1210 DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
   1211 TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
   1212 
   1213 #undef DLL_FUNC_LOADED
   1214   true;
   1215 
   1216   dbghelp_loaded = result;
   1217   return result;
   1218   // NOTE: The modules are never unloaded and will stay around until the
   1219   // application is closed.
   1220 }
   1221 
   1222 
   1223 // Load the symbols for generating stack traces.
   1224 static bool LoadSymbols(HANDLE process_handle) {
   1225   static bool symbols_loaded = false;
   1226 
   1227   if (symbols_loaded) return true;
   1228 
   1229   BOOL ok;
   1230 
   1231   // Initialize the symbol engine.
   1232   ok = _SymInitialize(process_handle,  // hProcess
   1233                       NULL,            // UserSearchPath
   1234                       false);          // fInvadeProcess
   1235   if (!ok) return false;
   1236 
   1237   DWORD options = _SymGetOptions();
   1238   options |= SYMOPT_LOAD_LINES;
   1239   options |= SYMOPT_FAIL_CRITICAL_ERRORS;
   1240   options = _SymSetOptions(options);
   1241 
   1242   char buf[OS::kStackWalkMaxNameLen] = {0};
   1243   ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
   1244   if (!ok) {
   1245     int err = GetLastError();
   1246     PrintF("%d\n", err);
   1247     return false;
   1248   }
   1249 
   1250   HANDLE snapshot = _CreateToolhelp32Snapshot(
   1251       TH32CS_SNAPMODULE,       // dwFlags
   1252       GetCurrentProcessId());  // th32ProcessId
   1253   if (snapshot == INVALID_HANDLE_VALUE) return false;
   1254   MODULEENTRY32W module_entry;
   1255   module_entry.dwSize = sizeof(module_entry);  // Set the size of the structure.
   1256   BOOL cont = _Module32FirstW(snapshot, &module_entry);
   1257   while (cont) {
   1258     DWORD64 base;
   1259     // NOTE the SymLoadModule64 function has the peculiarity of accepting a
   1260     // both unicode and ASCII strings even though the parameter is PSTR.
   1261     base = _SymLoadModule64(
   1262         process_handle,                                       // hProcess
   1263         0,                                                    // hFile
   1264         reinterpret_cast<PSTR>(module_entry.szExePath),       // ImageName
   1265         reinterpret_cast<PSTR>(module_entry.szModule),        // ModuleName
   1266         reinterpret_cast<DWORD64>(module_entry.modBaseAddr),  // BaseOfDll
   1267         module_entry.modBaseSize);                            // SizeOfDll
   1268     if (base == 0) {
   1269       int err = GetLastError();
   1270       if (err != ERROR_MOD_NOT_FOUND &&
   1271           err != ERROR_INVALID_HANDLE) return false;
   1272     }
   1273     LOG(i::Isolate::Current(),
   1274         SharedLibraryEvent(
   1275             module_entry.szExePath,
   1276             reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
   1277             reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
   1278                                            module_entry.modBaseSize)));
   1279     cont = _Module32NextW(snapshot, &module_entry);
   1280   }
   1281   CloseHandle(snapshot);
   1282 
   1283   symbols_loaded = true;
   1284   return true;
   1285 }
   1286 
   1287 
   1288 void OS::LogSharedLibraryAddresses() {
   1289   // SharedLibraryEvents are logged when loading symbol information.
   1290   // Only the shared libraries loaded at the time of the call to
   1291   // LogSharedLibraryAddresses are logged.  DLLs loaded after
   1292   // initialization are not accounted for.
   1293   if (!LoadDbgHelpAndTlHelp32()) return;
   1294   HANDLE process_handle = GetCurrentProcess();
   1295   LoadSymbols(process_handle);
   1296 }
   1297 
   1298 
   1299 void OS::SignalCodeMovingGC() {
   1300 }
   1301 
   1302 
   1303 // Walk the stack using the facilities in dbghelp.dll and tlhelp32.dll
   1304 
   1305 // Switch off warning 4748 (/GS can not protect parameters and local variables
   1306 // from local buffer overrun because optimizations are disabled in function) as
   1307 // it is triggered by the use of inline assembler.
   1308 #pragma warning(push)
   1309 #pragma warning(disable : 4748)
   1310 int OS::StackWalk(Vector<OS::StackFrame> frames) {
   1311   BOOL ok;
   1312 
   1313   // Load the required functions from DLL's.
   1314   if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError;
   1315 
   1316   // Get the process and thread handles.
   1317   HANDLE process_handle = GetCurrentProcess();
   1318   HANDLE thread_handle = GetCurrentThread();
   1319 
   1320   // Read the symbols.
   1321   if (!LoadSymbols(process_handle)) return kStackWalkError;
   1322 
   1323   // Capture current context.
   1324   CONTEXT context;
   1325   RtlCaptureContext(&context);
   1326 
   1327   // Initialize the stack walking
   1328   STACKFRAME64 stack_frame;
   1329   memset(&stack_frame, 0, sizeof(stack_frame));
   1330 #ifdef  _WIN64
   1331   stack_frame.AddrPC.Offset = context.Rip;
   1332   stack_frame.AddrFrame.Offset = context.Rbp;
   1333   stack_frame.AddrStack.Offset = context.Rsp;
   1334 #else
   1335   stack_frame.AddrPC.Offset = context.Eip;
   1336   stack_frame.AddrFrame.Offset = context.Ebp;
   1337   stack_frame.AddrStack.Offset = context.Esp;
   1338 #endif
   1339   stack_frame.AddrPC.Mode = AddrModeFlat;
   1340   stack_frame.AddrFrame.Mode = AddrModeFlat;
   1341   stack_frame.AddrStack.Mode = AddrModeFlat;
   1342   int frames_count = 0;
   1343 
   1344   // Collect stack frames.
   1345   int frames_size = frames.length();
   1346   while (frames_count < frames_size) {
   1347     ok = _StackWalk64(
   1348         IMAGE_FILE_MACHINE_I386,    // MachineType
   1349         process_handle,             // hProcess
   1350         thread_handle,              // hThread
   1351         &stack_frame,               // StackFrame
   1352         &context,                   // ContextRecord
   1353         NULL,                       // ReadMemoryRoutine
   1354         _SymFunctionTableAccess64,  // FunctionTableAccessRoutine
   1355         _SymGetModuleBase64,        // GetModuleBaseRoutine
   1356         NULL);                      // TranslateAddress
   1357     if (!ok) break;
   1358 
   1359     // Store the address.
   1360     ASSERT((stack_frame.AddrPC.Offset >> 32) == 0);  // 32-bit address.
   1361     frames[frames_count].address =
   1362         reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
   1363 
   1364     // Try to locate a symbol for this frame.
   1365     DWORD64 symbol_displacement;
   1366     SmartArrayPointer<IMAGEHLP_SYMBOL64> symbol(
   1367         NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen));
   1368     if (symbol.is_empty()) return kStackWalkError;  // Out of memory.
   1369     memset(*symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
   1370     (*symbol)->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
   1371     (*symbol)->MaxNameLength = kStackWalkMaxNameLen;
   1372     ok = _SymGetSymFromAddr64(process_handle,             // hProcess
   1373                               stack_frame.AddrPC.Offset,  // Address
   1374                               &symbol_displacement,       // Displacement
   1375                               *symbol);                   // Symbol
   1376     if (ok) {
   1377       // Try to locate more source information for the symbol.
   1378       IMAGEHLP_LINE64 Line;
   1379       memset(&Line, 0, sizeof(Line));
   1380       Line.SizeOfStruct = sizeof(Line);
   1381       DWORD line_displacement;
   1382       ok = _SymGetLineFromAddr64(
   1383           process_handle,             // hProcess
   1384           stack_frame.AddrPC.Offset,  // dwAddr
   1385           &line_displacement,         // pdwDisplacement
   1386           &Line);                     // Line
   1387       // Format a text representation of the frame based on the information
   1388       // available.
   1389       if (ok) {
   1390         SNPrintF(MutableCStrVector(frames[frames_count].text,
   1391                                    kStackWalkMaxTextLen),
   1392                  "%s %s:%d:%d",
   1393                  (*symbol)->Name, Line.FileName, Line.LineNumber,
   1394                  line_displacement);
   1395       } else {
   1396         SNPrintF(MutableCStrVector(frames[frames_count].text,
   1397                                    kStackWalkMaxTextLen),
   1398                  "%s",
   1399                  (*symbol)->Name);
   1400       }
   1401       // Make sure line termination is in place.
   1402       frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
   1403     } else {
   1404       // No text representation of this frame
   1405       frames[frames_count].text[0] = '\0';
   1406 
   1407       // Continue if we are just missing a module (for non C/C++ frames a
   1408       // module will never be found).
   1409       int err = GetLastError();
   1410       if (err != ERROR_MOD_NOT_FOUND) {
   1411         break;
   1412       }
   1413     }
   1414 
   1415     frames_count++;
   1416   }
   1417 
   1418   // Return the number of frames filled in.
   1419   return frames_count;
   1420 }
   1421 
   1422 // Restore warnings to previous settings.
   1423 #pragma warning(pop)
   1424 
   1425 #else  // __MINGW32__
   1426 void OS::LogSharedLibraryAddresses() { }
   1427 void OS::SignalCodeMovingGC() { }
   1428 int OS::StackWalk(Vector<OS::StackFrame> frames) { return 0; }
   1429 #endif  // __MINGW32__
   1430 
   1431 
   1432 uint64_t OS::CpuFeaturesImpliedByPlatform() {
   1433   return 0;  // Windows runs on anything.
   1434 }
   1435 
   1436 
   1437 double OS::nan_value() {
   1438 #ifdef _MSC_VER
   1439   // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
   1440   // in mask set, so value equals mask.
   1441   static const __int64 nanval = kQuietNaNMask;
   1442   return *reinterpret_cast<const double*>(&nanval);
   1443 #else  // _MSC_VER
   1444   return NAN;
   1445 #endif  // _MSC_VER
   1446 }
   1447 
   1448 
   1449 int OS::ActivationFrameAlignment() {
   1450 #ifdef _WIN64
   1451   return 16;  // Windows 64-bit ABI requires the stack to be 16-byte aligned.
   1452 #else
   1453   return 8;  // Floating-point math runs faster with 8-byte alignment.
   1454 #endif
   1455 }
   1456 
   1457 
   1458 void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
   1459   MemoryBarrier();
   1460   *ptr = value;
   1461 }
   1462 
   1463 
   1464 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
   1465 
   1466 
   1467 VirtualMemory::VirtualMemory(size_t size)
   1468     : address_(ReserveRegion(size)), size_(size) { }
   1469 
   1470 
   1471 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
   1472     : address_(NULL), size_(0) {
   1473   ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
   1474   size_t request_size = RoundUp(size + alignment,
   1475                                 static_cast<intptr_t>(OS::AllocateAlignment()));
   1476   void* address = ReserveRegion(request_size);
   1477   if (address == NULL) return;
   1478   Address base = RoundUp(static_cast<Address>(address), alignment);
   1479   // Try reducing the size by freeing and then reallocating a specific area.
   1480   bool result = ReleaseRegion(address, request_size);
   1481   USE(result);
   1482   ASSERT(result);
   1483   address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
   1484   if (address != NULL) {
   1485     request_size = size;
   1486     ASSERT(base == static_cast<Address>(address));
   1487   } else {
   1488     // Resizing failed, just go with a bigger area.
   1489     address = ReserveRegion(request_size);
   1490     if (address == NULL) return;
   1491   }
   1492   address_ = address;
   1493   size_ = request_size;
   1494 }
   1495 
   1496 
   1497 VirtualMemory::~VirtualMemory() {
   1498   if (IsReserved()) {
   1499     bool result = ReleaseRegion(address_, size_);
   1500     ASSERT(result);
   1501     USE(result);
   1502   }
   1503 }
   1504 
   1505 
   1506 bool VirtualMemory::IsReserved() {
   1507   return address_ != NULL;
   1508 }
   1509 
   1510 
   1511 void VirtualMemory::Reset() {
   1512   address_ = NULL;
   1513   size_ = 0;
   1514 }
   1515 
   1516 
   1517 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
   1518   if (CommitRegion(address, size, is_executable)) {
   1519     UpdateAllocatedSpaceLimits(address, static_cast<int>(size));
   1520     return true;
   1521   }
   1522   return false;
   1523 }
   1524 
   1525 
   1526 bool VirtualMemory::Uncommit(void* address, size_t size) {
   1527   ASSERT(IsReserved());
   1528   return UncommitRegion(address, size);
   1529 }
   1530 
   1531 
   1532 void* VirtualMemory::ReserveRegion(size_t size) {
   1533   return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
   1534 }
   1535 
   1536 
   1537 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
   1538   int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
   1539   if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
   1540     return false;
   1541   }
   1542 
   1543   UpdateAllocatedSpaceLimits(base, static_cast<int>(size));
   1544   return true;
   1545 }
   1546 
   1547 
   1548 bool VirtualMemory::Guard(void* address) {
   1549   if (NULL == VirtualAlloc(address,
   1550                            OS::CommitPageSize(),
   1551                            MEM_COMMIT,
   1552                            PAGE_READONLY | PAGE_GUARD)) {
   1553     return false;
   1554   }
   1555   return true;
   1556 }
   1557 
   1558 
   1559 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
   1560   return VirtualFree(base, size, MEM_DECOMMIT) != 0;
   1561 }
   1562 
   1563 
   1564 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
   1565   return VirtualFree(base, 0, MEM_RELEASE) != 0;
   1566 }
   1567 
   1568 
   1569 // ----------------------------------------------------------------------------
   1570 // Win32 thread support.
   1571 
   1572 // Definition of invalid thread handle and id.
   1573 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
   1574 
   1575 // Entry point for threads. The supplied argument is a pointer to the thread
   1576 // object. The entry function dispatches to the run method in the thread
   1577 // object. It is important that this function has __stdcall calling
   1578 // convention.
   1579 static unsigned int __stdcall ThreadEntry(void* arg) {
   1580   Thread* thread = reinterpret_cast<Thread*>(arg);
   1581   thread->Run();
   1582   return 0;
   1583 }
   1584 
   1585 
   1586 class Thread::PlatformData : public Malloced {
   1587  public:
   1588   explicit PlatformData(HANDLE thread) : thread_(thread) {}
   1589   HANDLE thread_;
   1590   unsigned thread_id_;
   1591 };
   1592 
   1593 
   1594 // Initialize a Win32 thread object. The thread has an invalid thread
   1595 // handle until it is started.
   1596 
   1597 Thread::Thread(const Options& options)
   1598     : stack_size_(options.stack_size()) {
   1599   data_ = new PlatformData(kNoThread);
   1600   set_name(options.name());
   1601 }
   1602 
   1603 
   1604 void Thread::set_name(const char* name) {
   1605   OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
   1606   name_[sizeof(name_) - 1] = '\0';
   1607 }
   1608 
   1609 
   1610 // Close our own handle for the thread.
   1611 Thread::~Thread() {
   1612   if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
   1613   delete data_;
   1614 }
   1615 
   1616 
   1617 // Create a new thread. It is important to use _beginthreadex() instead of
   1618 // the Win32 function CreateThread(), because the CreateThread() does not
   1619 // initialize thread specific structures in the C runtime library.
   1620 void Thread::Start() {
   1621   data_->thread_ = reinterpret_cast<HANDLE>(
   1622       _beginthreadex(NULL,
   1623                      static_cast<unsigned>(stack_size_),
   1624                      ThreadEntry,
   1625                      this,
   1626                      0,
   1627                      &data_->thread_id_));
   1628 }
   1629 
   1630 
   1631 // Wait for thread to terminate.
   1632 void Thread::Join() {
   1633   if (data_->thread_id_ != GetCurrentThreadId()) {
   1634     WaitForSingleObject(data_->thread_, INFINITE);
   1635   }
   1636 }
   1637 
   1638 
   1639 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
   1640   DWORD result = TlsAlloc();
   1641   ASSERT(result != TLS_OUT_OF_INDEXES);
   1642   return static_cast<LocalStorageKey>(result);
   1643 }
   1644 
   1645 
   1646 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
   1647   BOOL result = TlsFree(static_cast<DWORD>(key));
   1648   USE(result);
   1649   ASSERT(result);
   1650 }
   1651 
   1652 
   1653 void* Thread::GetThreadLocal(LocalStorageKey key) {
   1654   return TlsGetValue(static_cast<DWORD>(key));
   1655 }
   1656 
   1657 
   1658 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
   1659   BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
   1660   USE(result);
   1661   ASSERT(result);
   1662 }
   1663 
   1664 
   1665 
   1666 void Thread::YieldCPU() {
   1667   Sleep(0);
   1668 }
   1669 
   1670 
   1671 // ----------------------------------------------------------------------------
   1672 // Win32 mutex support.
   1673 //
   1674 // On Win32 mutexes are implemented using CRITICAL_SECTION objects. These are
   1675 // faster than Win32 Mutex objects because they are implemented using user mode
   1676 // atomic instructions. Therefore we only do ring transitions if there is lock
   1677 // contention.
   1678 
   1679 class Win32Mutex : public Mutex {
   1680  public:
   1681   Win32Mutex() { InitializeCriticalSection(&cs_); }
   1682 
   1683   virtual ~Win32Mutex() { DeleteCriticalSection(&cs_); }
   1684 
   1685   virtual int Lock() {
   1686     EnterCriticalSection(&cs_);
   1687     return 0;
   1688   }
   1689 
   1690   virtual int Unlock() {
   1691     LeaveCriticalSection(&cs_);
   1692     return 0;
   1693   }
   1694 
   1695 
   1696   virtual bool TryLock() {
   1697     // Returns non-zero if critical section is entered successfully entered.
   1698     return TryEnterCriticalSection(&cs_);
   1699   }
   1700 
   1701  private:
   1702   CRITICAL_SECTION cs_;  // Critical section used for mutex
   1703 };
   1704 
   1705 
   1706 Mutex* OS::CreateMutex() {
   1707   return new Win32Mutex();
   1708 }
   1709 
   1710 
   1711 // ----------------------------------------------------------------------------
   1712 // Win32 semaphore support.
   1713 //
   1714 // On Win32 semaphores are implemented using Win32 Semaphore objects. The
   1715 // semaphores are anonymous. Also, the semaphores are initialized to have
   1716 // no upper limit on count.
   1717 
   1718 
   1719 class Win32Semaphore : public Semaphore {
   1720  public:
   1721   explicit Win32Semaphore(int count) {
   1722     sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
   1723   }
   1724 
   1725   ~Win32Semaphore() {
   1726     CloseHandle(sem);
   1727   }
   1728 
   1729   void Wait() {
   1730     WaitForSingleObject(sem, INFINITE);
   1731   }
   1732 
   1733   bool Wait(int timeout) {
   1734     // Timeout in Windows API is in milliseconds.
   1735     DWORD millis_timeout = timeout / 1000;
   1736     return WaitForSingleObject(sem, millis_timeout) != WAIT_TIMEOUT;
   1737   }
   1738 
   1739   void Signal() {
   1740     LONG dummy;
   1741     ReleaseSemaphore(sem, 1, &dummy);
   1742   }
   1743 
   1744  private:
   1745   HANDLE sem;
   1746 };
   1747 
   1748 
   1749 Semaphore* OS::CreateSemaphore(int count) {
   1750   return new Win32Semaphore(count);
   1751 }
   1752 
   1753 
   1754 // ----------------------------------------------------------------------------
   1755 // Win32 socket support.
   1756 //
   1757 
   1758 class Win32Socket : public Socket {
   1759  public:
   1760   explicit Win32Socket() {
   1761     // Create the socket.
   1762     socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
   1763   }
   1764   explicit Win32Socket(SOCKET socket): socket_(socket) { }
   1765   virtual ~Win32Socket() { Shutdown(); }
   1766 
   1767   // Server initialization.
   1768   bool Bind(const int port);
   1769   bool Listen(int backlog) const;
   1770   Socket* Accept() const;
   1771 
   1772   // Client initialization.
   1773   bool Connect(const char* host, const char* port);
   1774 
   1775   // Shutdown socket for both read and write.
   1776   bool Shutdown();
   1777 
   1778   // Data Transimission
   1779   int Send(const char* data, int len) const;
   1780   int Receive(char* data, int len) const;
   1781 
   1782   bool SetReuseAddress(bool reuse_address);
   1783 
   1784   bool IsValid() const { return socket_ != INVALID_SOCKET; }
   1785 
   1786  private:
   1787   SOCKET socket_;
   1788 };
   1789 
   1790 
   1791 bool Win32Socket::Bind(const int port) {
   1792   if (!IsValid())  {
   1793     return false;
   1794   }
   1795 
   1796   sockaddr_in addr;
   1797   memset(&addr, 0, sizeof(addr));
   1798   addr.sin_family = AF_INET;
   1799   addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   1800   addr.sin_port = htons(port);
   1801   int status = bind(socket_,
   1802                     reinterpret_cast<struct sockaddr *>(&addr),
   1803                     sizeof(addr));
   1804   return status == 0;
   1805 }
   1806 
   1807 
   1808 bool Win32Socket::Listen(int backlog) const {
   1809   if (!IsValid()) {
   1810     return false;
   1811   }
   1812 
   1813   int status = listen(socket_, backlog);
   1814   return status == 0;
   1815 }
   1816 
   1817 
   1818 Socket* Win32Socket::Accept() const {
   1819   if (!IsValid()) {
   1820     return NULL;
   1821   }
   1822 
   1823   SOCKET socket = accept(socket_, NULL, NULL);
   1824   if (socket == INVALID_SOCKET) {
   1825     return NULL;
   1826   } else {
   1827     return new Win32Socket(socket);
   1828   }
   1829 }
   1830 
   1831 
   1832 bool Win32Socket::Connect(const char* host, const char* port) {
   1833   if (!IsValid()) {
   1834     return false;
   1835   }
   1836 
   1837   // Lookup host and port.
   1838   struct addrinfo *result = NULL;
   1839   struct addrinfo hints;
   1840   memset(&hints, 0, sizeof(addrinfo));
   1841   hints.ai_family = AF_INET;
   1842   hints.ai_socktype = SOCK_STREAM;
   1843   hints.ai_protocol = IPPROTO_TCP;
   1844   int status = getaddrinfo(host, port, &hints, &result);
   1845   if (status != 0) {
   1846     return false;
   1847   }
   1848 
   1849   // Connect.
   1850   status = connect(socket_,
   1851                    result->ai_addr,
   1852                    static_cast<int>(result->ai_addrlen));
   1853   freeaddrinfo(result);
   1854   return status == 0;
   1855 }
   1856 
   1857 
   1858 bool Win32Socket::Shutdown() {
   1859   if (IsValid()) {
   1860     // Shutdown socket for both read and write.
   1861     int status = shutdown(socket_, SD_BOTH);
   1862     closesocket(socket_);
   1863     socket_ = INVALID_SOCKET;
   1864     return status == SOCKET_ERROR;
   1865   }
   1866   return true;
   1867 }
   1868 
   1869 
   1870 int Win32Socket::Send(const char* data, int len) const {
   1871   int status = send(socket_, data, len, 0);
   1872   return status;
   1873 }
   1874 
   1875 
   1876 int Win32Socket::Receive(char* data, int len) const {
   1877   int status = recv(socket_, data, len, 0);
   1878   return status;
   1879 }
   1880 
   1881 
   1882 bool Win32Socket::SetReuseAddress(bool reuse_address) {
   1883   BOOL on = reuse_address ? true : false;
   1884   int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
   1885                           reinterpret_cast<char*>(&on), sizeof(on));
   1886   return status == SOCKET_ERROR;
   1887 }
   1888 
   1889 
   1890 bool Socket::SetUp() {
   1891   // Initialize Winsock32
   1892   int err;
   1893   WSADATA winsock_data;
   1894   WORD version_requested = MAKEWORD(1, 0);
   1895   err = WSAStartup(version_requested, &winsock_data);
   1896   if (err != 0) {
   1897     PrintF("Unable to initialize Winsock, err = %d\n", Socket::LastError());
   1898   }
   1899 
   1900   return err == 0;
   1901 }
   1902 
   1903 
   1904 int Socket::LastError() {
   1905   return WSAGetLastError();
   1906 }
   1907 
   1908 
   1909 uint16_t Socket::HToN(uint16_t value) {
   1910   return htons(value);
   1911 }
   1912 
   1913 
   1914 uint16_t Socket::NToH(uint16_t value) {
   1915   return ntohs(value);
   1916 }
   1917 
   1918 
   1919 uint32_t Socket::HToN(uint32_t value) {
   1920   return htonl(value);
   1921 }
   1922 
   1923 
   1924 uint32_t Socket::NToH(uint32_t value) {
   1925   return ntohl(value);
   1926 }
   1927 
   1928 
   1929 Socket* OS::CreateSocket() {
   1930   return new Win32Socket();
   1931 }
   1932 
   1933 
   1934 // ----------------------------------------------------------------------------
   1935 // Win32 profiler support.
   1936 
   1937 class Sampler::PlatformData : public Malloced {
   1938  public:
   1939   // Get a handle to the calling thread. This is the thread that we are
   1940   // going to profile. We need to make a copy of the handle because we are
   1941   // going to use it in the sampler thread. Using GetThreadHandle() will
   1942   // not work in this case. We're using OpenThread because DuplicateHandle
   1943   // for some reason doesn't work in Chrome's sandbox.
   1944   PlatformData() : profiled_thread_(OpenThread(THREAD_GET_CONTEXT |
   1945                                                THREAD_SUSPEND_RESUME |
   1946                                                THREAD_QUERY_INFORMATION,
   1947                                                false,
   1948                                                GetCurrentThreadId())) {}
   1949 
   1950   ~PlatformData() {
   1951     if (profiled_thread_ != NULL) {
   1952       CloseHandle(profiled_thread_);
   1953       profiled_thread_ = NULL;
   1954     }
   1955   }
   1956 
   1957   HANDLE profiled_thread() { return profiled_thread_; }
   1958 
   1959  private:
   1960   HANDLE profiled_thread_;
   1961 };
   1962 
   1963 
   1964 class SamplerThread : public Thread {
   1965  public:
   1966   static const int kSamplerThreadStackSize = 64 * KB;
   1967 
   1968   explicit SamplerThread(int interval)
   1969       : Thread(Thread::Options("SamplerThread", kSamplerThreadStackSize)),
   1970         interval_(interval) {}
   1971 
   1972   static void AddActiveSampler(Sampler* sampler) {
   1973     ScopedLock lock(mutex_.Pointer());
   1974     SamplerRegistry::AddActiveSampler(sampler);
   1975     if (instance_ == NULL) {
   1976       instance_ = new SamplerThread(sampler->interval());
   1977       instance_->Start();
   1978     } else {
   1979       ASSERT(instance_->interval_ == sampler->interval());
   1980     }
   1981   }
   1982 
   1983   static void RemoveActiveSampler(Sampler* sampler) {
   1984     ScopedLock lock(mutex_.Pointer());
   1985     SamplerRegistry::RemoveActiveSampler(sampler);
   1986     if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
   1987       RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
   1988       delete instance_;
   1989       instance_ = NULL;
   1990     }
   1991   }
   1992 
   1993   // Implement Thread::Run().
   1994   virtual void Run() {
   1995     SamplerRegistry::State state;
   1996     while ((state = SamplerRegistry::GetState()) !=
   1997            SamplerRegistry::HAS_NO_SAMPLERS) {
   1998       bool cpu_profiling_enabled =
   1999           (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
   2000       bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
   2001       // When CPU profiling is enabled both JavaScript and C++ code is
   2002       // profiled. We must not suspend.
   2003       if (!cpu_profiling_enabled) {
   2004         if (rate_limiter_.SuspendIfNecessary()) continue;
   2005       }
   2006       if (cpu_profiling_enabled) {
   2007         if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
   2008           return;
   2009         }
   2010       }
   2011       if (runtime_profiler_enabled) {
   2012         if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
   2013           return;
   2014         }
   2015       }
   2016       OS::Sleep(interval_);
   2017     }
   2018   }
   2019 
   2020   static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
   2021     if (!sampler->isolate()->IsInitialized()) return;
   2022     if (!sampler->IsProfiling()) return;
   2023     SamplerThread* sampler_thread =
   2024         reinterpret_cast<SamplerThread*>(raw_sampler_thread);
   2025     sampler_thread->SampleContext(sampler);
   2026   }
   2027 
   2028   static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
   2029     if (!sampler->isolate()->IsInitialized()) return;
   2030     sampler->isolate()->runtime_profiler()->NotifyTick();
   2031   }
   2032 
   2033   void SampleContext(Sampler* sampler) {
   2034     HANDLE profiled_thread = sampler->platform_data()->profiled_thread();
   2035     if (profiled_thread == NULL) return;
   2036 
   2037     // Context used for sampling the register state of the profiled thread.
   2038     CONTEXT context;
   2039     memset(&context, 0, sizeof(context));
   2040 
   2041     TickSample sample_obj;
   2042     TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
   2043     if (sample == NULL) sample = &sample_obj;
   2044 
   2045     static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
   2046     if (SuspendThread(profiled_thread) == kSuspendFailed) return;
   2047     sample->state = sampler->isolate()->current_vm_state();
   2048 
   2049     context.ContextFlags = CONTEXT_FULL;
   2050     if (GetThreadContext(profiled_thread, &context) != 0) {
   2051 #if V8_HOST_ARCH_X64
   2052       sample->pc = reinterpret_cast<Address>(context.Rip);
   2053       sample->sp = reinterpret_cast<Address>(context.Rsp);
   2054       sample->fp = reinterpret_cast<Address>(context.Rbp);
   2055 #else
   2056       sample->pc = reinterpret_cast<Address>(context.Eip);
   2057       sample->sp = reinterpret_cast<Address>(context.Esp);
   2058       sample->fp = reinterpret_cast<Address>(context.Ebp);
   2059 #endif
   2060       sampler->SampleStack(sample);
   2061       sampler->Tick(sample);
   2062     }
   2063     ResumeThread(profiled_thread);
   2064   }
   2065 
   2066   const int interval_;
   2067   RuntimeProfilerRateLimiter rate_limiter_;
   2068 
   2069   // Protects the process wide state below.
   2070   static LazyMutex mutex_;
   2071   static SamplerThread* instance_;
   2072 
   2073  private:
   2074   DISALLOW_COPY_AND_ASSIGN(SamplerThread);
   2075 };
   2076 
   2077 
   2078 LazyMutex SamplerThread::mutex_ = LAZY_MUTEX_INITIALIZER;
   2079 SamplerThread* SamplerThread::instance_ = NULL;
   2080 
   2081 
   2082 Sampler::Sampler(Isolate* isolate, int interval)
   2083     : isolate_(isolate),
   2084       interval_(interval),
   2085       profiling_(false),
   2086       active_(false),
   2087       samples_taken_(0) {
   2088   data_ = new PlatformData;
   2089 }
   2090 
   2091 
   2092 Sampler::~Sampler() {
   2093   ASSERT(!IsActive());
   2094   delete data_;
   2095 }
   2096 
   2097 
   2098 void Sampler::Start() {
   2099   ASSERT(!IsActive());
   2100   SetActive(true);
   2101   SamplerThread::AddActiveSampler(this);
   2102 }
   2103 
   2104 
   2105 void Sampler::Stop() {
   2106   ASSERT(IsActive());
   2107   SamplerThread::RemoveActiveSampler(this);
   2108   SetActive(false);
   2109 }
   2110 
   2111 
   2112 } }  // namespace v8::internal
   2113