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