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