ager@chromium.org | 9258b6b | 2008-09-11 09:11:10 +0000 | [diff] [blame] | 1 | // Copyright 2006-2008 the V8 project authors. All rights reserved. |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +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. |
| 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 |
| 51 | |
| 52 | #include <windows.h> |
| 53 | |
| 54 | #include <mmsystem.h> // For timeGetTime(). |
| 55 | #include <dbghelp.h> // For SymLoadModule64 and al. |
| 56 | #include <tlhelp32.h> // For Module32First and al. |
| 57 | |
| 58 | // These aditional WIN32 includes have to be right here as the #undef's below |
| 59 | // makes it impossible to have them elsewhere. |
| 60 | #include <winsock2.h> |
| 61 | #include <process.h> // for _beginthreadex() |
| 62 | #include <stdlib.h> |
| 63 | |
| 64 | #pragma comment(lib, "winmm.lib") // force linkage with winmm. |
| 65 | |
| 66 | #undef VOID |
| 67 | #undef DELETE |
| 68 | #undef IN |
| 69 | #undef THIS |
| 70 | #undef CONST |
| 71 | #undef NAN |
| 72 | #undef GetObject |
| 73 | #undef CreateMutex |
| 74 | #undef CreateSemaphore |
| 75 | |
| 76 | #include "v8.h" |
| 77 | |
| 78 | #include "platform.h" |
| 79 | |
| 80 | // Extra POSIX/ANSI routines for Win32. Please refer to The Open Group Base |
| 81 | // Specification for specification of the correct semantics for these |
| 82 | // functions. |
| 83 | // (http://www.opengroup.org/onlinepubs/000095399/) |
| 84 | |
| 85 | // Test for finite value - usually defined in math.h |
| 86 | namespace v8 { |
| 87 | namespace internal { |
| 88 | |
| 89 | int isfinite(double x) { |
| 90 | return _finite(x); |
| 91 | } |
| 92 | |
| 93 | } // namespace v8 |
| 94 | } // namespace internal |
| 95 | |
| 96 | // Test for a NaN (not a number) value - usually defined in math.h |
| 97 | int isnan(double x) { |
| 98 | return _isnan(x); |
| 99 | } |
| 100 | |
| 101 | |
| 102 | // Test for infinity - usually defined in math.h |
| 103 | int isinf(double x) { |
| 104 | return (_fpclass(x) & (_FPCLASS_PINF | _FPCLASS_NINF)) != 0; |
| 105 | } |
| 106 | |
| 107 | |
| 108 | // Test if x is less than y and both nominal - usually defined in math.h |
| 109 | int isless(double x, double y) { |
| 110 | return isnan(x) || isnan(y) ? 0 : x < y; |
| 111 | } |
| 112 | |
| 113 | |
| 114 | // Test if x is greater than y and both nominal - usually defined in math.h |
| 115 | int isgreater(double x, double y) { |
| 116 | return isnan(x) || isnan(y) ? 0 : x > y; |
| 117 | } |
| 118 | |
| 119 | |
| 120 | // Classify floating point number - usually defined in math.h |
| 121 | int fpclassify(double x) { |
| 122 | // Use the MS-specific _fpclass() for classification. |
| 123 | int flags = _fpclass(x); |
| 124 | |
| 125 | // Determine class. We cannot use a switch statement because |
| 126 | // the _FPCLASS_ constants are defined as flags. |
| 127 | if (flags & (_FPCLASS_PN | _FPCLASS_NN)) return FP_NORMAL; |
| 128 | if (flags & (_FPCLASS_PZ | _FPCLASS_NZ)) return FP_ZERO; |
| 129 | if (flags & (_FPCLASS_PD | _FPCLASS_ND)) return FP_SUBNORMAL; |
| 130 | if (flags & (_FPCLASS_PINF | _FPCLASS_NINF)) return FP_INFINITE; |
| 131 | |
| 132 | // All cases should be covered by the code above. |
| 133 | ASSERT(flags & (_FPCLASS_SNAN | _FPCLASS_QNAN)); |
| 134 | return FP_NAN; |
| 135 | } |
| 136 | |
| 137 | |
| 138 | // Test sign - usually defined in math.h |
| 139 | int signbit(double x) { |
| 140 | // We need to take care of the special case of both positive |
| 141 | // and negative versions of zero. |
| 142 | if (x == 0) |
| 143 | return _fpclass(x) & _FPCLASS_NZ; |
| 144 | else |
| 145 | return x < 0; |
| 146 | } |
| 147 | |
| 148 | |
| 149 | // Generate a pseudo-random number in the range 0-2^31-1. Usually |
| 150 | // defined in stdlib.h |
| 151 | int random() { |
| 152 | return rand(); |
| 153 | } |
| 154 | |
| 155 | |
| 156 | // Case-insensitive string comparisons. Use stricmp() on Win32. Usually defined |
| 157 | // in strings.h. |
| 158 | int strcasecmp(const char* s1, const char* s2) { |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 159 | return _stricmp(s1, s2); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 160 | } |
| 161 | |
| 162 | |
| 163 | // Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually |
| 164 | // defined in strings.h. |
| 165 | int strncasecmp(const char* s1, const char* s2, int n) { |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 166 | return _strnicmp(s1, s2, n); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 167 | } |
| 168 | |
| 169 | namespace v8 { namespace internal { |
| 170 | |
| 171 | double ceiling(double x) { |
| 172 | return ceil(x); |
| 173 | } |
| 174 | |
| 175 | // ---------------------------------------------------------------------------- |
| 176 | // The Time class represents time on win32. A timestamp is represented as |
| 177 | // a 64-bit integer in 100 nano-seconds since January 1, 1601 (UTC). JavaScript |
| 178 | // timestamps are represented as a doubles in milliseconds since 00:00:00 UTC, |
| 179 | // January 1, 1970. |
| 180 | |
| 181 | class Time { |
| 182 | public: |
| 183 | // Constructors. |
| 184 | Time(); |
| 185 | explicit Time(double jstime); |
| 186 | Time(int year, int mon, int day, int hour, int min, int sec); |
| 187 | |
| 188 | // Convert timestamp to JavaScript representation. |
| 189 | double ToJSTime(); |
| 190 | |
| 191 | // Set timestamp to current time. |
| 192 | void SetToCurrentTime(); |
| 193 | |
| 194 | // Returns the local timezone offset in milliseconds east of UTC. This is |
| 195 | // the number of milliseconds you must add to UTC to get local time, i.e. |
| 196 | // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This |
| 197 | // routine also takes into account whether daylight saving is effect |
| 198 | // at the time. |
| 199 | int64_t LocalOffset(); |
| 200 | |
| 201 | // Returns the daylight savings time offset for the time in milliseconds. |
| 202 | int64_t DaylightSavingsOffset(); |
| 203 | |
| 204 | // Returns a string identifying the current timezone for the |
| 205 | // timestamp taking into account daylight saving. |
| 206 | char* LocalTimezone(); |
| 207 | |
| 208 | private: |
| 209 | // Constants for time conversion. |
| 210 | static const int64_t kTimeEpoc = 116444736000000000; |
| 211 | static const int64_t kTimeScaler = 10000; |
| 212 | static const int64_t kMsPerMinute = 60000; |
| 213 | |
| 214 | // Constants for timezone information. |
| 215 | static const int kTzNameSize = 128; |
| 216 | static const bool kShortTzNames = false; |
| 217 | |
| 218 | // Timezone information. We need to have static buffers for the |
| 219 | // timezone names because we return pointers to these in |
| 220 | // LocalTimezone(). |
| 221 | static bool tz_initialized_; |
| 222 | static TIME_ZONE_INFORMATION tzinfo_; |
| 223 | static char std_tz_name_[kTzNameSize]; |
| 224 | static char dst_tz_name_[kTzNameSize]; |
| 225 | |
| 226 | // Initialize the timezone information (if not already done). |
| 227 | static void TzSet(); |
| 228 | |
| 229 | // Guess the name of the timezone from the bias. |
| 230 | static const char* GuessTimezoneNameFromBias(int bias); |
| 231 | |
| 232 | // Return whether or not daylight savings time is in effect at this time. |
| 233 | bool InDST(); |
| 234 | |
| 235 | // Return the difference (in milliseconds) between this timestamp and |
| 236 | // another timestamp. |
| 237 | int64_t Diff(Time* other); |
| 238 | |
| 239 | // Accessor for FILETIME representation. |
| 240 | FILETIME& ft() { return time_.ft_; } |
| 241 | |
| 242 | // Accessor for integer representation. |
| 243 | int64_t& t() { return time_.t_; } |
| 244 | |
| 245 | // Although win32 uses 64-bit integers for representing timestamps, |
| 246 | // these are packed into a FILETIME structure. The FILETIME structure |
| 247 | // is just a struct representing a 64-bit integer. The TimeStamp union |
| 248 | // allows access to both a FILETIME and an integer representation of |
| 249 | // the timestamp. |
| 250 | union TimeStamp { |
| 251 | FILETIME ft_; |
| 252 | int64_t t_; |
| 253 | }; |
| 254 | |
| 255 | TimeStamp time_; |
| 256 | }; |
| 257 | |
| 258 | // Static variables. |
| 259 | bool Time::tz_initialized_ = false; |
| 260 | TIME_ZONE_INFORMATION Time::tzinfo_; |
| 261 | char Time::std_tz_name_[kTzNameSize]; |
| 262 | char Time::dst_tz_name_[kTzNameSize]; |
| 263 | |
| 264 | |
| 265 | // Initialize timestamp to start of epoc. |
| 266 | Time::Time() { |
| 267 | t() = 0; |
| 268 | } |
| 269 | |
| 270 | |
| 271 | // Initialize timestamp from a JavaScript timestamp. |
| 272 | Time::Time(double jstime) { |
| 273 | t() = static_cast<uint64_t>(jstime) * kTimeScaler + kTimeEpoc; |
| 274 | } |
| 275 | |
| 276 | |
| 277 | // Initialize timestamp from date/time components. |
| 278 | Time::Time(int year, int mon, int day, int hour, int min, int sec) { |
| 279 | SYSTEMTIME st; |
| 280 | st.wYear = year; |
| 281 | st.wMonth = mon; |
| 282 | st.wDay = day; |
| 283 | st.wHour = hour; |
| 284 | st.wMinute = min; |
| 285 | st.wSecond = sec; |
| 286 | st.wMilliseconds = 0; |
| 287 | SystemTimeToFileTime(&st, &ft()); |
| 288 | } |
| 289 | |
| 290 | |
| 291 | // Convert timestamp to JavaScript timestamp. |
| 292 | double Time::ToJSTime() { |
| 293 | return static_cast<double>((t() - kTimeEpoc) / kTimeScaler); |
| 294 | } |
| 295 | |
| 296 | |
| 297 | // Guess the name of the timezone from the bias. |
| 298 | // The guess is very biased towards the northern hemisphere. |
| 299 | const char* Time::GuessTimezoneNameFromBias(int bias) { |
| 300 | static const int kHour = 60; |
| 301 | switch (-bias) { |
| 302 | case -9*kHour: return "Alaska"; |
| 303 | case -8*kHour: return "Pacific"; |
| 304 | case -7*kHour: return "Mountain"; |
| 305 | case -6*kHour: return "Central"; |
| 306 | case -5*kHour: return "Eastern"; |
| 307 | case -4*kHour: return "Atlantic"; |
| 308 | case 0*kHour: return "GMT"; |
| 309 | case +1*kHour: return "Central Europe"; |
| 310 | case +2*kHour: return "Eastern Europe"; |
| 311 | case +3*kHour: return "Russia"; |
| 312 | case +5*kHour + 30: return "India"; |
| 313 | case +8*kHour: return "China"; |
| 314 | case +9*kHour: return "Japan"; |
| 315 | case +12*kHour: return "New Zealand"; |
| 316 | default: return "Local"; |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | |
| 321 | // Initialize timezone information. The timezone information is obtained from |
| 322 | // windows. If we cannot get the timezone information we fall back to CET. |
| 323 | // Please notice that this code is not thread-safe. |
| 324 | void Time::TzSet() { |
| 325 | // Just return if timezone information has already been initialized. |
| 326 | if (tz_initialized_) return; |
| 327 | |
| 328 | // Obtain timezone information from operating system. |
| 329 | memset(&tzinfo_, 0, sizeof(tzinfo_)); |
| 330 | if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) { |
| 331 | // If we cannot get timezone information we fall back to CET. |
| 332 | tzinfo_.Bias = -60; |
| 333 | tzinfo_.StandardDate.wMonth = 10; |
| 334 | tzinfo_.StandardDate.wDay = 5; |
| 335 | tzinfo_.StandardDate.wHour = 3; |
| 336 | tzinfo_.StandardBias = 0; |
| 337 | tzinfo_.DaylightDate.wMonth = 3; |
| 338 | tzinfo_.DaylightDate.wDay = 5; |
| 339 | tzinfo_.DaylightDate.wHour = 2; |
| 340 | tzinfo_.DaylightBias = -60; |
| 341 | } |
| 342 | |
| 343 | // Make standard and DST timezone names. |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 344 | OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize), |
| 345 | "%S", |
| 346 | tzinfo_.StandardName); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 347 | std_tz_name_[kTzNameSize - 1] = '\0'; |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 348 | OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize), |
| 349 | "%S", |
| 350 | tzinfo_.DaylightName); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 351 | dst_tz_name_[kTzNameSize - 1] = '\0'; |
| 352 | |
| 353 | // If OS returned empty string or resource id (like "@tzres.dll,-211") |
| 354 | // simply guess the name from the UTC bias of the timezone. |
| 355 | // To properly resolve the resource identifier requires a library load, |
| 356 | // which is not possible in a sandbox. |
| 357 | if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') { |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 358 | OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1), |
| 359 | "%s Standard Time", |
| 360 | GuessTimezoneNameFromBias(tzinfo_.Bias)); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 361 | } |
| 362 | if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') { |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 363 | OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1), |
| 364 | "%s Daylight Time", |
| 365 | GuessTimezoneNameFromBias(tzinfo_.Bias)); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 366 | } |
| 367 | |
| 368 | // Timezone information initialized. |
| 369 | tz_initialized_ = true; |
| 370 | } |
| 371 | |
| 372 | |
| 373 | // Return the difference in milliseconds between this and another timestamp. |
| 374 | int64_t Time::Diff(Time* other) { |
| 375 | return (t() - other->t()) / kTimeScaler; |
| 376 | } |
| 377 | |
| 378 | |
| 379 | // Set timestamp to current time. |
| 380 | void Time::SetToCurrentTime() { |
| 381 | // The default GetSystemTimeAsFileTime has a ~15.5ms resolution. |
| 382 | // Because we're fast, we like fast timers which have at least a |
| 383 | // 1ms resolution. |
| 384 | // |
| 385 | // timeGetTime() provides 1ms granularity when combined with |
| 386 | // timeBeginPeriod(). If the host application for v8 wants fast |
| 387 | // timers, it can use timeBeginPeriod to increase the resolution. |
| 388 | // |
| 389 | // Using timeGetTime() has a drawback because it is a 32bit value |
| 390 | // and hence rolls-over every ~49days. |
| 391 | // |
| 392 | // To use the clock, we use GetSystemTimeAsFileTime as our base; |
| 393 | // and then use timeGetTime to extrapolate current time from the |
| 394 | // start time. To deal with rollovers, we resync the clock |
| 395 | // any time when more than kMaxClockElapsedTime has passed or |
| 396 | // whenever timeGetTime creates a rollover. |
| 397 | |
| 398 | static bool initialized = false; |
| 399 | static TimeStamp init_time; |
| 400 | static DWORD init_ticks; |
| 401 | static const int kHundredNanosecondsPerSecond = 10000; |
| 402 | static const int kMaxClockElapsedTime = |
| 403 | 60*60*24*kHundredNanosecondsPerSecond; // 1 day |
| 404 | |
| 405 | // If we are uninitialized, we need to resync the clock. |
| 406 | bool needs_resync = !initialized; |
| 407 | |
| 408 | // Get the current time. |
| 409 | TimeStamp time_now; |
| 410 | GetSystemTimeAsFileTime(&time_now.ft_); |
| 411 | DWORD ticks_now = timeGetTime(); |
| 412 | |
| 413 | // Check if we need to resync due to clock rollover. |
| 414 | needs_resync |= ticks_now < init_ticks; |
| 415 | |
| 416 | // Check if we need to resync due to elapsed time. |
| 417 | needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime; |
| 418 | |
| 419 | // Resync the clock if necessary. |
| 420 | if (needs_resync) { |
| 421 | GetSystemTimeAsFileTime(&init_time.ft_); |
| 422 | init_ticks = ticks_now = timeGetTime(); |
| 423 | initialized = true; |
| 424 | } |
| 425 | |
| 426 | // Finally, compute the actual time. Why is this so hard. |
| 427 | DWORD elapsed = ticks_now - init_ticks; |
| 428 | this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000); |
| 429 | } |
| 430 | |
| 431 | |
| 432 | // Return the local timezone offset in milliseconds east of UTC. This |
| 433 | // takes into account whether daylight saving is in effect at the time. |
| 434 | int64_t Time::LocalOffset() { |
| 435 | // Initialize timezone information, if needed. |
| 436 | TzSet(); |
| 437 | |
| 438 | // Convert timestamp to date/time components. These are now in UTC |
| 439 | // format. NB: Please do not replace the following three calls with one |
| 440 | // call to FileTimeToLocalFileTime(), because it does not handle |
| 441 | // daylight saving correctly. |
| 442 | SYSTEMTIME utc; |
| 443 | FileTimeToSystemTime(&ft(), &utc); |
| 444 | |
| 445 | // Convert to local time, using timezone information. |
| 446 | SYSTEMTIME local; |
| 447 | SystemTimeToTzSpecificLocalTime(&tzinfo_, &utc, &local); |
| 448 | |
| 449 | // Convert local time back to a timestamp. This timestamp now |
| 450 | // has a bias similar to the local timezone bias in effect |
| 451 | // at the time of the original timestamp. |
| 452 | Time localtime; |
| 453 | SystemTimeToFileTime(&local, &localtime.ft()); |
| 454 | |
| 455 | // The difference between the new local timestamp and the original |
| 456 | // timestamp and is the local timezone offset. |
| 457 | return localtime.Diff(this); |
| 458 | } |
| 459 | |
| 460 | |
| 461 | // Return whether or not daylight savings time is in effect at this time. |
| 462 | bool Time::InDST() { |
| 463 | // Initialize timezone information, if needed. |
| 464 | TzSet(); |
| 465 | |
| 466 | // Determine if DST is in effect at the specified time. |
| 467 | bool in_dst = false; |
| 468 | if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) { |
| 469 | // Get the local timezone offset for the timestamp in milliseconds. |
| 470 | int64_t offset = LocalOffset(); |
| 471 | |
| 472 | // Compute the offset for DST. The bias parameters in the timezone info |
| 473 | // are specified in minutes. These must be converted to milliseconds. |
| 474 | int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute; |
| 475 | |
| 476 | // If the local time offset equals the timezone bias plus the daylight |
| 477 | // bias then DST is in effect. |
| 478 | in_dst = offset == dstofs; |
| 479 | } |
| 480 | |
| 481 | return in_dst; |
| 482 | } |
| 483 | |
| 484 | |
| 485 | // Return the dalight savings time offset for this time. |
| 486 | int64_t Time::DaylightSavingsOffset() { |
| 487 | return InDST() ? 60 * kMsPerMinute : 0; |
| 488 | } |
| 489 | |
| 490 | |
| 491 | // Returns a string identifying the current timezone for the |
| 492 | // timestamp taking into account daylight saving. |
| 493 | char* Time::LocalTimezone() { |
| 494 | // Return the standard or DST time zone name based on whether daylight |
| 495 | // saving is in effect at the given time. |
| 496 | return InDST() ? dst_tz_name_ : std_tz_name_; |
| 497 | } |
| 498 | |
| 499 | |
| 500 | void OS::Setup() { |
| 501 | // Seed the random number generator. |
ager@chromium.org | 9258b6b | 2008-09-11 09:11:10 +0000 | [diff] [blame] | 502 | // Convert the current time to a 64-bit integer first, before converting it |
| 503 | // to an unsigned. Going directly can cause an overflow and the seed to be |
| 504 | // set to all ones. The seed will be identical for different instances that |
| 505 | // call this setup code within the same millisecond. |
| 506 | uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis()); |
| 507 | srand(static_cast<unsigned int>(seed)); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 508 | } |
| 509 | |
| 510 | |
| 511 | // Returns the accumulated user time for thread. |
| 512 | int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) { |
| 513 | FILETIME dummy; |
| 514 | uint64_t usertime; |
| 515 | |
| 516 | // Get the amount of time that the thread has executed in user mode. |
| 517 | if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy, |
| 518 | reinterpret_cast<FILETIME*>(&usertime))) return -1; |
| 519 | |
| 520 | // Adjust the resolution to micro-seconds. |
| 521 | usertime /= 10; |
| 522 | |
| 523 | // Convert to seconds and microseconds |
| 524 | *secs = static_cast<uint32_t>(usertime / 1000000); |
| 525 | *usecs = static_cast<uint32_t>(usertime % 1000000); |
| 526 | return 0; |
| 527 | } |
| 528 | |
| 529 | |
| 530 | // Returns current time as the number of milliseconds since |
| 531 | // 00:00:00 UTC, January 1, 1970. |
| 532 | double OS::TimeCurrentMillis() { |
| 533 | Time t; |
| 534 | t.SetToCurrentTime(); |
| 535 | return t.ToJSTime(); |
| 536 | } |
| 537 | |
| 538 | // Returns the tickcounter based on timeGetTime. |
| 539 | int64_t OS::Ticks() { |
| 540 | return timeGetTime() * 1000; // Convert to microseconds. |
| 541 | } |
| 542 | |
| 543 | |
| 544 | // Returns a string identifying the current timezone taking into |
| 545 | // account daylight saving. |
| 546 | char* OS::LocalTimezone(double time) { |
| 547 | return Time(time).LocalTimezone(); |
| 548 | } |
| 549 | |
| 550 | |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 551 | // Returns the local time offset in milliseconds east of UTC without |
| 552 | // taking daylight savings time into account. |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 553 | double OS::LocalTimeOffset() { |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 554 | // Use current time, rounded to the millisecond. |
| 555 | Time t(TimeCurrentMillis()); |
| 556 | // Time::LocalOffset inlcudes any daylight savings offset, so subtract it. |
| 557 | return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset()); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 558 | } |
| 559 | |
| 560 | |
| 561 | // Returns the daylight savings offset in milliseconds for the given |
| 562 | // time. |
| 563 | double OS::DaylightSavingsOffset(double time) { |
| 564 | int64_t offset = Time(time).DaylightSavingsOffset(); |
| 565 | return static_cast<double>(offset); |
| 566 | } |
| 567 | |
| 568 | |
| 569 | // ---------------------------------------------------------------------------- |
| 570 | // Win32 console output. |
| 571 | // |
| 572 | // If a Win32 application is linked as a console application it has a normal |
| 573 | // standard output and standard error. In this case normal printf works fine |
| 574 | // for output. However, if the application is linked as a GUI application, |
| 575 | // the process doesn't have a console, and therefore (debugging) output is lost. |
| 576 | // This is the case if we are embedded in a windows program (like a browser). |
| 577 | // In order to be able to get debug output in this case the the debugging |
| 578 | // facility using OutputDebugString. This output goes to the active debugger |
| 579 | // for the process (if any). Else the output can be monitored using DBMON.EXE. |
| 580 | |
| 581 | enum OutputMode { |
| 582 | UNKNOWN, // Output method has not yet been determined. |
| 583 | CONSOLE, // Output is written to stdout. |
| 584 | ODS // Output is written to debug facility. |
| 585 | }; |
| 586 | |
| 587 | static OutputMode output_mode = UNKNOWN; // Current output mode. |
| 588 | |
| 589 | |
| 590 | // Determine if the process has a console for output. |
| 591 | static bool HasConsole() { |
| 592 | // Only check the first time. Eventual race conditions are not a problem, |
| 593 | // because all threads will eventually determine the same mode. |
| 594 | if (output_mode == UNKNOWN) { |
| 595 | // We cannot just check that the standard output is attached to a console |
| 596 | // because this would fail if output is redirected to a file. Therefore we |
| 597 | // say that a process does not have an output console if either the |
| 598 | // standard output handle is invalid or its file type is unknown. |
| 599 | if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE && |
| 600 | GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN) |
| 601 | output_mode = CONSOLE; |
| 602 | else |
| 603 | output_mode = ODS; |
| 604 | } |
| 605 | return output_mode == CONSOLE; |
| 606 | } |
| 607 | |
| 608 | |
| 609 | static void VPrintHelper(FILE* stream, const char* format, va_list args) { |
| 610 | if (HasConsole()) { |
| 611 | vfprintf(stream, format, args); |
| 612 | } else { |
| 613 | // It is important to use safe print here in order to avoid |
| 614 | // overflowing the buffer. We might truncate the output, but this |
| 615 | // does not crash. |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 616 | EmbeddedVector<char, 4096> buffer; |
| 617 | OS::VSNPrintF(buffer, format, args); |
| 618 | OutputDebugStringA(buffer.start()); |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | |
| 623 | FILE* OS::FOpen(const char* path, const char* mode) { |
| 624 | FILE* result; |
| 625 | if (fopen_s(&result, path, mode) == 0) { |
| 626 | return result; |
| 627 | } else { |
| 628 | return NULL; |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 629 | } |
| 630 | } |
| 631 | |
| 632 | |
| 633 | // Print (debug) message to console. |
| 634 | void OS::Print(const char* format, ...) { |
| 635 | va_list args; |
| 636 | va_start(args, format); |
| 637 | VPrint(format, args); |
| 638 | va_end(args); |
| 639 | } |
| 640 | |
| 641 | |
| 642 | void OS::VPrint(const char* format, va_list args) { |
| 643 | VPrintHelper(stdout, format, args); |
| 644 | } |
| 645 | |
| 646 | |
| 647 | // Print error message to console. |
| 648 | void OS::PrintError(const char* format, ...) { |
| 649 | va_list args; |
| 650 | va_start(args, format); |
| 651 | VPrintError(format, args); |
| 652 | va_end(args); |
| 653 | } |
| 654 | |
| 655 | |
| 656 | void OS::VPrintError(const char* format, va_list args) { |
| 657 | VPrintHelper(stderr, format, args); |
| 658 | } |
| 659 | |
| 660 | |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 661 | int OS::SNPrintF(Vector<char> str, const char* format, ...) { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 662 | va_list args; |
| 663 | va_start(args, format); |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 664 | int result = VSNPrintF(str, format, args); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 665 | va_end(args); |
| 666 | return result; |
| 667 | } |
| 668 | |
| 669 | |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 670 | int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) { |
| 671 | int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 672 | // Make sure to zero-terminate the string if the output was |
| 673 | // truncated or if there was an error. |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 674 | if (n < 0 || n >= str.length()) { |
| 675 | str[str.length() - 1] = '\0'; |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 676 | return -1; |
| 677 | } else { |
| 678 | return n; |
| 679 | } |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 680 | } |
| 681 | |
| 682 | |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 683 | void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) { |
| 684 | int result = strncpy_s(dest.start(), dest.length(), src, n); |
| 685 | USE(result); |
| 686 | ASSERT(result == 0); |
| 687 | } |
| 688 | |
| 689 | |
| 690 | void OS::WcsCpy(Vector<wchar_t> dest, const wchar_t* src) { |
| 691 | int result = wcscpy_s(dest.start(), dest.length(), src); |
| 692 | USE(result); |
| 693 | ASSERT(result == 0); |
| 694 | } |
| 695 | |
| 696 | |
| 697 | char *OS::StrDup(const char* str) { |
| 698 | return _strdup(str); |
| 699 | } |
| 700 | |
| 701 | |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 702 | // We keep the lowest and highest addresses mapped as a quick way of |
| 703 | // determining that pointers are outside the heap (used mostly in assertions |
| 704 | // and verification). The estimate is conservative, ie, not all addresses in |
| 705 | // 'allocated' space are actually allocated to our heap. The range is |
| 706 | // [lowest, highest), inclusive on the low and and exclusive on the high end. |
| 707 | static void* lowest_ever_allocated = reinterpret_cast<void*>(-1); |
| 708 | static void* highest_ever_allocated = reinterpret_cast<void*>(0); |
| 709 | |
| 710 | |
| 711 | static void UpdateAllocatedSpaceLimits(void* address, int size) { |
| 712 | lowest_ever_allocated = Min(lowest_ever_allocated, address); |
| 713 | highest_ever_allocated = |
| 714 | Max(highest_ever_allocated, |
| 715 | reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size)); |
| 716 | } |
| 717 | |
| 718 | |
| 719 | bool OS::IsOutsideAllocatedSpace(void* pointer) { |
| 720 | if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated) |
| 721 | return true; |
| 722 | // Ask the Windows API |
| 723 | if (IsBadWritePtr(pointer, 1)) |
| 724 | return true; |
| 725 | return false; |
| 726 | } |
| 727 | |
| 728 | |
mads.s.ager@gmail.com | 769cc96 | 2008-08-06 10:02:49 +0000 | [diff] [blame] | 729 | // Get the system's page size used by VirtualAlloc() or the next power |
| 730 | // of two. The reason for always returning a power of two is that the |
| 731 | // rounding up in OS::Allocate expects that. |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 732 | static size_t GetPageSize() { |
| 733 | static size_t page_size = 0; |
| 734 | if (page_size == 0) { |
| 735 | SYSTEM_INFO info; |
| 736 | GetSystemInfo(&info); |
mads.s.ager@gmail.com | 769cc96 | 2008-08-06 10:02:49 +0000 | [diff] [blame] | 737 | page_size = RoundUpToPowerOf2(info.dwPageSize); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 738 | } |
| 739 | return page_size; |
| 740 | } |
| 741 | |
| 742 | |
mads.s.ager@gmail.com | 769cc96 | 2008-08-06 10:02:49 +0000 | [diff] [blame] | 743 | // The allocation alignment is the guaranteed alignment for |
| 744 | // VirtualAlloc'ed blocks of memory. |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 745 | size_t OS::AllocateAlignment() { |
mads.s.ager@gmail.com | 769cc96 | 2008-08-06 10:02:49 +0000 | [diff] [blame] | 746 | static size_t allocate_alignment = 0; |
| 747 | if (allocate_alignment == 0) { |
| 748 | SYSTEM_INFO info; |
| 749 | GetSystemInfo(&info); |
| 750 | allocate_alignment = info.dwAllocationGranularity; |
| 751 | } |
| 752 | return allocate_alignment; |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 753 | } |
| 754 | |
| 755 | |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 756 | void* OS::Allocate(const size_t requested, |
| 757 | size_t* allocated, |
| 758 | bool executable) { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 759 | // VirtualAlloc rounds allocated size to page size automatically. |
| 760 | size_t msize = RoundUp(requested, GetPageSize()); |
| 761 | |
| 762 | // Windows XP SP2 allows Data Excution Prevention (DEP). |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 763 | int prot = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; |
mads.s.ager@gmail.com | 769cc96 | 2008-08-06 10:02:49 +0000 | [diff] [blame] | 764 | LPVOID mbase = VirtualAlloc(NULL, msize, MEM_COMMIT | MEM_RESERVE, prot); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 765 | if (mbase == NULL) { |
| 766 | LOG(StringEvent("OS::Allocate", "VirtualAlloc failed")); |
| 767 | return NULL; |
| 768 | } |
| 769 | |
| 770 | ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment())); |
| 771 | |
| 772 | *allocated = msize; |
| 773 | UpdateAllocatedSpaceLimits(mbase, msize); |
| 774 | return mbase; |
| 775 | } |
| 776 | |
| 777 | |
| 778 | void OS::Free(void* buf, const size_t length) { |
| 779 | // TODO(1240712): VirtualFree has a return value which is ignored here. |
| 780 | VirtualFree(buf, 0, MEM_RELEASE); |
| 781 | USE(length); |
| 782 | } |
| 783 | |
| 784 | |
| 785 | void OS::Sleep(int milliseconds) { |
| 786 | ::Sleep(milliseconds); |
| 787 | } |
| 788 | |
| 789 | |
| 790 | void OS::Abort() { |
| 791 | // Redirect to windows specific abort to ensure |
| 792 | // collaboration with sandboxing. |
| 793 | __debugbreak(); |
| 794 | } |
| 795 | |
| 796 | |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 797 | void OS::DebugBreak() { |
| 798 | __debugbreak(); |
| 799 | } |
| 800 | |
| 801 | |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 802 | class Win32MemoryMappedFile : public OS::MemoryMappedFile { |
| 803 | public: |
| 804 | Win32MemoryMappedFile(HANDLE file, HANDLE file_mapping, void* memory) |
| 805 | : file_(file), file_mapping_(file_mapping), memory_(memory) { } |
| 806 | virtual ~Win32MemoryMappedFile(); |
| 807 | virtual void* memory() { return memory_; } |
| 808 | private: |
| 809 | HANDLE file_; |
| 810 | HANDLE file_mapping_; |
| 811 | void* memory_; |
| 812 | }; |
| 813 | |
| 814 | |
| 815 | OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size, |
| 816 | void* initial) { |
| 817 | // Open a physical file |
| 818 | HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, |
| 819 | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL); |
| 820 | if (file == NULL) return NULL; |
| 821 | // Create a file mapping for the physical file |
| 822 | HANDLE file_mapping = CreateFileMapping(file, NULL, |
| 823 | PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL); |
| 824 | if (file_mapping == NULL) return NULL; |
| 825 | // Map a view of the file into memory |
| 826 | void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size); |
| 827 | if (memory) memmove(memory, initial, size); |
| 828 | return new Win32MemoryMappedFile(file, file_mapping, memory); |
| 829 | } |
| 830 | |
| 831 | |
| 832 | Win32MemoryMappedFile::~Win32MemoryMappedFile() { |
| 833 | if (memory_ != NULL) |
| 834 | UnmapViewOfFile(memory_); |
| 835 | CloseHandle(file_mapping_); |
| 836 | CloseHandle(file_); |
| 837 | } |
| 838 | |
| 839 | |
| 840 | // The following code loads functions defined in DbhHelp.h and TlHelp32.h |
| 841 | // dynamically. This is to avoid beeing depending on dbghelp.dll and |
| 842 | // tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to |
| 843 | // kernel32.dll at some point so loading functions defines in TlHelp32.h |
| 844 | // dynamically might not be necessary any more - for some versions of Windows?). |
| 845 | |
| 846 | // Function pointers to functions dynamically loaded from dbghelp.dll. |
| 847 | #define DBGHELP_FUNCTION_LIST(V) \ |
| 848 | V(SymInitialize) \ |
| 849 | V(SymGetOptions) \ |
| 850 | V(SymSetOptions) \ |
| 851 | V(SymGetSearchPath) \ |
| 852 | V(SymLoadModule64) \ |
| 853 | V(StackWalk64) \ |
| 854 | V(SymGetSymFromAddr64) \ |
| 855 | V(SymGetLineFromAddr64) \ |
| 856 | V(SymFunctionTableAccess64) \ |
| 857 | V(SymGetModuleBase64) |
| 858 | |
| 859 | // Function pointers to functions dynamically loaded from dbghelp.dll. |
| 860 | #define TLHELP32_FUNCTION_LIST(V) \ |
| 861 | V(CreateToolhelp32Snapshot) \ |
| 862 | V(Module32FirstW) \ |
| 863 | V(Module32NextW) |
| 864 | |
| 865 | // Define the decoration to use for the type and variable name used for |
| 866 | // dynamically loaded DLL function.. |
| 867 | #define DLL_FUNC_TYPE(name) _##name##_ |
| 868 | #define DLL_FUNC_VAR(name) _##name |
| 869 | |
| 870 | // Define the type for each dynamically loaded DLL function. The function |
| 871 | // definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros |
| 872 | // from the Windows include files are redefined here to have the function |
| 873 | // definitions to be as close to the ones in the original .h files as possible. |
| 874 | #ifndef IN |
| 875 | #define IN |
| 876 | #endif |
| 877 | #ifndef VOID |
| 878 | #define VOID void |
| 879 | #endif |
| 880 | |
| 881 | // DbgHelp.h functions. |
| 882 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess, |
| 883 | IN PSTR UserSearchPath, |
| 884 | IN BOOL fInvadeProcess); |
| 885 | typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID); |
| 886 | typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions); |
| 887 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))( |
| 888 | IN HANDLE hProcess, |
| 889 | OUT PSTR SearchPath, |
| 890 | IN DWORD SearchPathLength); |
| 891 | typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))( |
| 892 | IN HANDLE hProcess, |
| 893 | IN HANDLE hFile, |
| 894 | IN PSTR ImageName, |
| 895 | IN PSTR ModuleName, |
| 896 | IN DWORD64 BaseOfDll, |
| 897 | IN DWORD SizeOfDll); |
| 898 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))( |
| 899 | DWORD MachineType, |
| 900 | HANDLE hProcess, |
| 901 | HANDLE hThread, |
| 902 | LPSTACKFRAME64 StackFrame, |
| 903 | PVOID ContextRecord, |
| 904 | PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, |
| 905 | PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, |
| 906 | PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, |
| 907 | PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); |
| 908 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))( |
| 909 | IN HANDLE hProcess, |
| 910 | IN DWORD64 qwAddr, |
| 911 | OUT PDWORD64 pdwDisplacement, |
| 912 | OUT PIMAGEHLP_SYMBOL64 Symbol); |
| 913 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))( |
| 914 | IN HANDLE hProcess, |
| 915 | IN DWORD64 qwAddr, |
| 916 | OUT PDWORD pdwDisplacement, |
| 917 | OUT PIMAGEHLP_LINE64 Line64); |
| 918 | // DbgHelp.h typedefs. Implementation found in dbghelp.dll. |
| 919 | typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))( |
| 920 | HANDLE hProcess, |
| 921 | DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64 |
| 922 | typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))( |
| 923 | HANDLE hProcess, |
| 924 | DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64 |
| 925 | |
| 926 | // TlHelp32.h functions. |
| 927 | typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))( |
| 928 | DWORD dwFlags, |
| 929 | DWORD th32ProcessID); |
| 930 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot, |
| 931 | LPMODULEENTRY32W lpme); |
| 932 | typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot, |
| 933 | LPMODULEENTRY32W lpme); |
| 934 | |
| 935 | #undef IN |
| 936 | #undef VOID |
| 937 | |
| 938 | // Declare a variable for each dynamically loaded DLL function. |
| 939 | #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL; |
| 940 | DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION) |
| 941 | TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION) |
| 942 | #undef DEF_DLL_FUNCTION |
| 943 | |
| 944 | // Load the functions. This function has a lot of "ugly" macros in order to |
| 945 | // keep down code duplication. |
| 946 | |
| 947 | static bool LoadDbgHelpAndTlHelp32() { |
| 948 | static bool dbghelp_loaded = false; |
| 949 | |
| 950 | if (dbghelp_loaded) return true; |
| 951 | |
| 952 | HMODULE module; |
| 953 | |
| 954 | // Load functions from the dbghelp.dll module. |
| 955 | module = LoadLibrary(TEXT("dbghelp.dll")); |
| 956 | if (module == NULL) { |
| 957 | return false; |
| 958 | } |
| 959 | |
| 960 | #define LOAD_DLL_FUNC(name) \ |
| 961 | DLL_FUNC_VAR(name) = \ |
| 962 | reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name)); |
| 963 | |
| 964 | DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC) |
| 965 | |
| 966 | #undef LOAD_DLL_FUNC |
| 967 | |
| 968 | // Load functions from the kernel32.dll module (the TlHelp32.h function used |
| 969 | // to be in tlhelp32.dll but are now moved to kernel32.dll). |
| 970 | module = LoadLibrary(TEXT("kernel32.dll")); |
| 971 | if (module == NULL) { |
| 972 | return false; |
| 973 | } |
| 974 | |
| 975 | #define LOAD_DLL_FUNC(name) \ |
| 976 | DLL_FUNC_VAR(name) = \ |
| 977 | reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name)); |
| 978 | |
| 979 | TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC) |
| 980 | |
| 981 | #undef LOAD_DLL_FUNC |
| 982 | |
| 983 | // Check that all functions where loaded. |
| 984 | bool result = |
| 985 | #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) && |
| 986 | |
| 987 | DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED) |
| 988 | TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED) |
| 989 | |
| 990 | #undef DLL_FUNC_LOADED |
| 991 | true; |
| 992 | |
| 993 | dbghelp_loaded = result; |
| 994 | return result; |
| 995 | // NOTE: The modules are never unloaded and will stay arround until the |
| 996 | // application is closed. |
| 997 | } |
| 998 | |
| 999 | |
| 1000 | // Load the symbols for generating stack traces. |
| 1001 | static bool LoadSymbols(HANDLE process_handle) { |
| 1002 | static bool symbols_loaded = false; |
| 1003 | |
| 1004 | if (symbols_loaded) return true; |
| 1005 | |
| 1006 | BOOL ok; |
| 1007 | |
| 1008 | // Initialize the symbol engine. |
| 1009 | ok = _SymInitialize(process_handle, // hProcess |
| 1010 | NULL, // UserSearchPath |
| 1011 | FALSE); // fInvadeProcess |
| 1012 | if (!ok) return false; |
| 1013 | |
| 1014 | DWORD options = _SymGetOptions(); |
| 1015 | options |= SYMOPT_LOAD_LINES; |
| 1016 | options |= SYMOPT_FAIL_CRITICAL_ERRORS; |
| 1017 | options = _SymSetOptions(options); |
| 1018 | |
| 1019 | char buf[OS::kStackWalkMaxNameLen] = {0}; |
| 1020 | ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen); |
| 1021 | if (!ok) { |
| 1022 | int err = GetLastError(); |
| 1023 | PrintF("%d\n", err); |
| 1024 | return false; |
| 1025 | } |
| 1026 | |
| 1027 | HANDLE snapshot = _CreateToolhelp32Snapshot( |
| 1028 | TH32CS_SNAPMODULE, // dwFlags |
| 1029 | GetCurrentProcessId()); // th32ProcessId |
| 1030 | if (snapshot == INVALID_HANDLE_VALUE) return false; |
| 1031 | MODULEENTRY32W module_entry; |
| 1032 | module_entry.dwSize = sizeof(module_entry); // Set the size of the structure. |
| 1033 | BOOL cont = _Module32FirstW(snapshot, &module_entry); |
| 1034 | while (cont) { |
| 1035 | DWORD64 base; |
| 1036 | // NOTE the SymLoadModule64 function has the peculiarity of accepting a |
| 1037 | // both unicode and ASCII strings even though the parameter is PSTR. |
| 1038 | base = _SymLoadModule64( |
| 1039 | process_handle, // hProcess |
| 1040 | 0, // hFile |
| 1041 | reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName |
| 1042 | reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName |
| 1043 | reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll |
| 1044 | module_entry.modBaseSize); // SizeOfDll |
| 1045 | if (base == 0) { |
| 1046 | int err = GetLastError(); |
| 1047 | if (err != ERROR_MOD_NOT_FOUND && |
| 1048 | err != ERROR_INVALID_HANDLE) return false; |
| 1049 | } |
| 1050 | LOG(SharedLibraryEvent( |
| 1051 | module_entry.szExePath, |
| 1052 | reinterpret_cast<unsigned int>(module_entry.modBaseAddr), |
| 1053 | reinterpret_cast<unsigned int>(module_entry.modBaseAddr + |
| 1054 | module_entry.modBaseSize))); |
| 1055 | cont = _Module32NextW(snapshot, &module_entry); |
| 1056 | } |
| 1057 | CloseHandle(snapshot); |
| 1058 | |
| 1059 | symbols_loaded = true; |
| 1060 | return true; |
| 1061 | } |
| 1062 | |
| 1063 | |
| 1064 | void OS::LogSharedLibraryAddresses() { |
| 1065 | // SharedLibraryEvents are logged when loading symbol information. |
| 1066 | // Only the shared libraries loaded at the time of the call to |
| 1067 | // LogSharedLibraryAddresses are logged. DLLs loaded after |
| 1068 | // initialization are not accounted for. |
| 1069 | if (!LoadDbgHelpAndTlHelp32()) return; |
| 1070 | HANDLE process_handle = GetCurrentProcess(); |
| 1071 | LoadSymbols(process_handle); |
| 1072 | } |
| 1073 | |
| 1074 | |
| 1075 | // Walk the stack using the facilities in dbghelp.dll and tlhelp32.dll |
| 1076 | |
| 1077 | // Switch off warning 4748 (/GS can not protect parameters and local variables |
| 1078 | // from local buffer overrun because optimizations are disabled in function) as |
| 1079 | // it is triggered by the use of inline assembler. |
| 1080 | #pragma warning(push) |
| 1081 | #pragma warning(disable : 4748) |
| 1082 | int OS::StackWalk(OS::StackFrame* frames, int frames_size) { |
| 1083 | BOOL ok; |
| 1084 | |
| 1085 | // Load the required functions from DLL's. |
| 1086 | if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError; |
| 1087 | |
| 1088 | // Get the process and thread handles. |
| 1089 | HANDLE process_handle = GetCurrentProcess(); |
| 1090 | HANDLE thread_handle = GetCurrentThread(); |
| 1091 | |
| 1092 | // Read the symbols. |
| 1093 | if (!LoadSymbols(process_handle)) return kStackWalkError; |
| 1094 | |
| 1095 | // Capture current context. |
| 1096 | CONTEXT context; |
| 1097 | memset(&context, 0, sizeof(context)); |
| 1098 | context.ContextFlags = CONTEXT_CONTROL; |
| 1099 | context.ContextFlags = CONTEXT_CONTROL; |
| 1100 | __asm call x |
| 1101 | __asm x: pop eax |
| 1102 | __asm mov context.Eip, eax |
| 1103 | __asm mov context.Ebp, ebp |
| 1104 | __asm mov context.Esp, esp |
| 1105 | // NOTE: At some point, we could use RtlCaptureContext(&context) to |
| 1106 | // capture the context instead of inline assembler. However it is |
| 1107 | // only available on XP, Vista, Server 2003 and Server 2008 which |
| 1108 | // might not be sufficient. |
| 1109 | |
| 1110 | // Initialize the stack walking |
| 1111 | STACKFRAME64 stack_frame; |
| 1112 | memset(&stack_frame, 0, sizeof(stack_frame)); |
| 1113 | stack_frame.AddrPC.Offset = context.Eip; |
| 1114 | stack_frame.AddrPC.Mode = AddrModeFlat; |
| 1115 | stack_frame.AddrFrame.Offset = context.Ebp; |
| 1116 | stack_frame.AddrFrame.Mode = AddrModeFlat; |
| 1117 | stack_frame.AddrStack.Offset = context.Esp; |
| 1118 | stack_frame.AddrStack.Mode = AddrModeFlat; |
| 1119 | int frames_count = 0; |
| 1120 | |
| 1121 | // Collect stack frames. |
| 1122 | while (frames_count < frames_size) { |
| 1123 | ok = _StackWalk64( |
| 1124 | IMAGE_FILE_MACHINE_I386, // MachineType |
| 1125 | process_handle, // hProcess |
| 1126 | thread_handle, // hThread |
| 1127 | &stack_frame, // StackFrame |
| 1128 | &context, // ContextRecord |
| 1129 | NULL, // ReadMemoryRoutine |
| 1130 | _SymFunctionTableAccess64, // FunctionTableAccessRoutine |
| 1131 | _SymGetModuleBase64, // GetModuleBaseRoutine |
| 1132 | NULL); // TranslateAddress |
| 1133 | if (!ok) break; |
| 1134 | |
| 1135 | // Store the address. |
| 1136 | ASSERT((stack_frame.AddrPC.Offset >> 32) == 0); // 32-bit address. |
| 1137 | frames[frames_count].address = |
| 1138 | reinterpret_cast<void*>(stack_frame.AddrPC.Offset); |
| 1139 | |
| 1140 | // Try to locate a symbol for this frame. |
| 1141 | DWORD64 symbol_displacement; |
| 1142 | IMAGEHLP_SYMBOL64* symbol = NULL; |
| 1143 | symbol = NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen); |
| 1144 | if (!symbol) return kStackWalkError; // Out of memory. |
| 1145 | memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen); |
| 1146 | symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); |
| 1147 | symbol->MaxNameLength = kStackWalkMaxNameLen; |
| 1148 | ok = _SymGetSymFromAddr64(process_handle, // hProcess |
| 1149 | stack_frame.AddrPC.Offset, // Address |
| 1150 | &symbol_displacement, // Displacement |
| 1151 | symbol); // Symbol |
| 1152 | if (ok) { |
| 1153 | // Try to locate more source information for the symbol. |
| 1154 | IMAGEHLP_LINE64 Line; |
| 1155 | memset(&Line, 0, sizeof(Line)); |
| 1156 | Line.SizeOfStruct = sizeof(Line); |
| 1157 | DWORD line_displacement; |
| 1158 | ok = _SymGetLineFromAddr64( |
| 1159 | process_handle, // hProcess |
| 1160 | stack_frame.AddrPC.Offset, // dwAddr |
| 1161 | &line_displacement, // pdwDisplacement |
| 1162 | &Line); // Line |
| 1163 | // Format a text representation of the frame based on the information |
| 1164 | // available. |
| 1165 | if (ok) { |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 1166 | SNPrintF(MutableCStrVector(frames[frames_count].text, |
| 1167 | kStackWalkMaxTextLen), |
| 1168 | "%s %s:%d:%d", |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1169 | symbol->Name, Line.FileName, Line.LineNumber, |
| 1170 | line_displacement); |
| 1171 | } else { |
kasperl@chromium.org | b912362 | 2008-09-17 14:05:56 +0000 | [diff] [blame^] | 1172 | SNPrintF(MutableCStrVector(frames[frames_count].text, |
| 1173 | kStackWalkMaxTextLen), |
| 1174 | "%s", |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1175 | symbol->Name); |
| 1176 | } |
| 1177 | // Make sure line termination is in place. |
| 1178 | frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0'; |
| 1179 | } else { |
| 1180 | // No text representation of this frame |
| 1181 | frames[frames_count].text[0] = '\0'; |
| 1182 | |
| 1183 | // Continue if we are just missing a module (for non C/C++ frames a |
| 1184 | // module will never be found). |
| 1185 | int err = GetLastError(); |
| 1186 | if (err != ERROR_MOD_NOT_FOUND) { |
| 1187 | DeleteArray(symbol); |
| 1188 | break; |
| 1189 | } |
| 1190 | } |
| 1191 | DeleteArray(symbol); |
| 1192 | |
| 1193 | frames_count++; |
| 1194 | } |
| 1195 | |
| 1196 | // Return the number of frames filled in. |
| 1197 | return frames_count; |
| 1198 | } |
| 1199 | |
| 1200 | // Restore warnings to previous settings. |
| 1201 | #pragma warning(pop) |
| 1202 | |
| 1203 | |
| 1204 | double OS::nan_value() { |
| 1205 | static const __int64 nanval = 0xfff8000000000000; |
| 1206 | return *reinterpret_cast<const double*>(&nanval); |
| 1207 | } |
| 1208 | |
| 1209 | bool VirtualMemory::IsReserved() { |
| 1210 | return address_ != NULL; |
| 1211 | } |
| 1212 | |
| 1213 | |
ager@chromium.org | 9258b6b | 2008-09-11 09:11:10 +0000 | [diff] [blame] | 1214 | VirtualMemory::VirtualMemory(size_t size) { |
| 1215 | address_ = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1216 | size_ = size; |
| 1217 | } |
| 1218 | |
| 1219 | |
| 1220 | VirtualMemory::~VirtualMemory() { |
| 1221 | if (IsReserved()) { |
| 1222 | if (0 == VirtualFree(address(), 0, MEM_RELEASE)) address_ = NULL; |
| 1223 | } |
| 1224 | } |
| 1225 | |
| 1226 | |
kasper.lund | 7276f14 | 2008-07-30 08:49:36 +0000 | [diff] [blame] | 1227 | bool VirtualMemory::Commit(void* address, size_t size, bool executable) { |
| 1228 | int prot = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; |
| 1229 | if (NULL == VirtualAlloc(address, size, MEM_COMMIT, prot)) { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1230 | return false; |
| 1231 | } |
| 1232 | |
| 1233 | UpdateAllocatedSpaceLimits(address, size); |
| 1234 | return true; |
| 1235 | } |
| 1236 | |
| 1237 | |
| 1238 | bool VirtualMemory::Uncommit(void* address, size_t size) { |
| 1239 | ASSERT(IsReserved()); |
| 1240 | return VirtualFree(address, size, MEM_DECOMMIT) != NULL; |
| 1241 | } |
| 1242 | |
| 1243 | |
| 1244 | // ---------------------------------------------------------------------------- |
| 1245 | // Win32 thread support. |
| 1246 | |
| 1247 | // Definition of invalid thread handle and id. |
| 1248 | static const HANDLE kNoThread = INVALID_HANDLE_VALUE; |
| 1249 | static const DWORD kNoThreadId = 0; |
| 1250 | |
| 1251 | |
| 1252 | class ThreadHandle::PlatformData : public Malloced { |
| 1253 | public: |
| 1254 | explicit PlatformData(ThreadHandle::Kind kind) { |
| 1255 | Initialize(kind); |
| 1256 | } |
| 1257 | |
| 1258 | void Initialize(ThreadHandle::Kind kind) { |
| 1259 | switch (kind) { |
| 1260 | case ThreadHandle::SELF: tid_ = GetCurrentThreadId(); break; |
| 1261 | case ThreadHandle::INVALID: tid_ = kNoThreadId; break; |
| 1262 | } |
| 1263 | } |
| 1264 | DWORD tid_; // Win32 thread identifier. |
| 1265 | }; |
| 1266 | |
| 1267 | |
| 1268 | // Entry point for threads. The supplied argument is a pointer to the thread |
| 1269 | // object. The entry function dispatches to the run method in the thread |
| 1270 | // object. It is important that this function has __stdcall calling |
| 1271 | // convention. |
| 1272 | static unsigned int __stdcall ThreadEntry(void* arg) { |
| 1273 | Thread* thread = reinterpret_cast<Thread*>(arg); |
| 1274 | // This is also initialized by the last parameter to _beginthreadex() but we |
| 1275 | // don't know which thread will run first (the original thread or the new |
| 1276 | // one) so we initialize it here too. |
| 1277 | thread->thread_handle_data()->tid_ = GetCurrentThreadId(); |
| 1278 | thread->Run(); |
| 1279 | return 0; |
| 1280 | } |
| 1281 | |
| 1282 | |
| 1283 | // Initialize thread handle to invalid handle. |
| 1284 | ThreadHandle::ThreadHandle(ThreadHandle::Kind kind) { |
| 1285 | data_ = new PlatformData(kind); |
| 1286 | } |
| 1287 | |
| 1288 | |
| 1289 | ThreadHandle::~ThreadHandle() { |
| 1290 | delete data_; |
| 1291 | } |
| 1292 | |
| 1293 | |
| 1294 | // The thread is running if it has the same id as the current thread. |
| 1295 | bool ThreadHandle::IsSelf() const { |
| 1296 | return GetCurrentThreadId() == data_->tid_; |
| 1297 | } |
| 1298 | |
| 1299 | |
| 1300 | // Test for invalid thread handle. |
| 1301 | bool ThreadHandle::IsValid() const { |
| 1302 | return data_->tid_ != kNoThreadId; |
| 1303 | } |
| 1304 | |
| 1305 | |
| 1306 | void ThreadHandle::Initialize(ThreadHandle::Kind kind) { |
| 1307 | data_->Initialize(kind); |
| 1308 | } |
| 1309 | |
| 1310 | |
| 1311 | class Thread::PlatformData : public Malloced { |
| 1312 | public: |
| 1313 | explicit PlatformData(HANDLE thread) : thread_(thread) {} |
| 1314 | HANDLE thread_; |
| 1315 | }; |
| 1316 | |
| 1317 | |
| 1318 | // Initialize a Win32 thread object. The thread has an invalid thread |
| 1319 | // handle until it is started. |
| 1320 | |
| 1321 | Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) { |
| 1322 | data_ = new PlatformData(kNoThread); |
| 1323 | } |
| 1324 | |
| 1325 | |
| 1326 | // Close our own handle for the thread. |
| 1327 | Thread::~Thread() { |
| 1328 | if (data_->thread_ != kNoThread) CloseHandle(data_->thread_); |
| 1329 | delete data_; |
| 1330 | } |
| 1331 | |
| 1332 | |
| 1333 | // Create a new thread. It is important to use _beginthreadex() instead of |
| 1334 | // the Win32 function CreateThread(), because the CreateThread() does not |
| 1335 | // initialize thread specific structures in the C runtime library. |
| 1336 | void Thread::Start() { |
| 1337 | data_->thread_ = reinterpret_cast<HANDLE>( |
| 1338 | _beginthreadex(NULL, |
| 1339 | 0, |
| 1340 | ThreadEntry, |
| 1341 | this, |
| 1342 | 0, |
| 1343 | reinterpret_cast<unsigned int*>( |
| 1344 | &thread_handle_data()->tid_))); |
| 1345 | ASSERT(IsValid()); |
| 1346 | } |
| 1347 | |
| 1348 | |
| 1349 | // Wait for thread to terminate. |
| 1350 | void Thread::Join() { |
| 1351 | WaitForSingleObject(data_->thread_, INFINITE); |
| 1352 | } |
| 1353 | |
| 1354 | |
| 1355 | Thread::LocalStorageKey Thread::CreateThreadLocalKey() { |
| 1356 | DWORD result = TlsAlloc(); |
| 1357 | ASSERT(result != TLS_OUT_OF_INDEXES); |
| 1358 | return static_cast<LocalStorageKey>(result); |
| 1359 | } |
| 1360 | |
| 1361 | |
| 1362 | void Thread::DeleteThreadLocalKey(LocalStorageKey key) { |
| 1363 | BOOL result = TlsFree(static_cast<DWORD>(key)); |
| 1364 | USE(result); |
| 1365 | ASSERT(result); |
| 1366 | } |
| 1367 | |
| 1368 | |
| 1369 | void* Thread::GetThreadLocal(LocalStorageKey key) { |
| 1370 | return TlsGetValue(static_cast<DWORD>(key)); |
| 1371 | } |
| 1372 | |
| 1373 | |
| 1374 | void Thread::SetThreadLocal(LocalStorageKey key, void* value) { |
| 1375 | BOOL result = TlsSetValue(static_cast<DWORD>(key), value); |
| 1376 | USE(result); |
| 1377 | ASSERT(result); |
| 1378 | } |
| 1379 | |
| 1380 | |
| 1381 | |
| 1382 | void Thread::YieldCPU() { |
| 1383 | Sleep(0); |
| 1384 | } |
| 1385 | |
| 1386 | |
| 1387 | // ---------------------------------------------------------------------------- |
| 1388 | // Win32 mutex support. |
| 1389 | // |
| 1390 | // On Win32 mutexes are implemented using CRITICAL_SECTION objects. These are |
| 1391 | // faster than Win32 Mutex objects because they are implemented using user mode |
| 1392 | // atomic instructions. Therefore we only do ring transitions if there is lock |
| 1393 | // contention. |
| 1394 | |
| 1395 | class Win32Mutex : public Mutex { |
| 1396 | public: |
| 1397 | |
| 1398 | Win32Mutex() { InitializeCriticalSection(&cs_); } |
| 1399 | |
| 1400 | ~Win32Mutex() { DeleteCriticalSection(&cs_); } |
| 1401 | |
| 1402 | int Lock() { |
| 1403 | EnterCriticalSection(&cs_); |
| 1404 | return 0; |
| 1405 | } |
| 1406 | |
| 1407 | int Unlock() { |
| 1408 | LeaveCriticalSection(&cs_); |
| 1409 | return 0; |
| 1410 | } |
| 1411 | |
| 1412 | private: |
| 1413 | CRITICAL_SECTION cs_; // Critical section used for mutex |
| 1414 | }; |
| 1415 | |
| 1416 | |
| 1417 | Mutex* OS::CreateMutex() { |
| 1418 | return new Win32Mutex(); |
| 1419 | } |
| 1420 | |
| 1421 | |
| 1422 | // ---------------------------------------------------------------------------- |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1423 | // Win32 semaphore support. |
| 1424 | // |
| 1425 | // On Win32 semaphores are implemented using Win32 Semaphore objects. The |
| 1426 | // semaphores are anonymous. Also, the semaphores are initialized to have |
| 1427 | // no upper limit on count. |
| 1428 | |
| 1429 | |
| 1430 | class Win32Semaphore : public Semaphore { |
| 1431 | public: |
| 1432 | explicit Win32Semaphore(int count) { |
| 1433 | sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL); |
| 1434 | } |
| 1435 | |
| 1436 | ~Win32Semaphore() { |
| 1437 | CloseHandle(sem); |
| 1438 | } |
| 1439 | |
| 1440 | void Wait() { |
| 1441 | WaitForSingleObject(sem, INFINITE); |
| 1442 | } |
| 1443 | |
| 1444 | void Signal() { |
| 1445 | LONG dummy; |
| 1446 | ReleaseSemaphore(sem, 1, &dummy); |
| 1447 | } |
| 1448 | |
| 1449 | private: |
| 1450 | HANDLE sem; |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1451 | }; |
| 1452 | |
| 1453 | |
| 1454 | Semaphore* OS::CreateSemaphore(int count) { |
| 1455 | return new Win32Semaphore(count); |
| 1456 | } |
| 1457 | |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1458 | #ifdef ENABLE_LOGGING_AND_PROFILING |
| 1459 | |
| 1460 | // ---------------------------------------------------------------------------- |
| 1461 | // Win32 profiler support. |
| 1462 | // |
| 1463 | // On win32 we use a sampler thread with high priority to sample the program |
| 1464 | // counter for the profiled thread. |
| 1465 | |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1466 | class Sampler::PlatformData : public Malloced { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1467 | public: |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1468 | explicit PlatformData(Sampler* sampler) { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1469 | sampler_ = sampler; |
| 1470 | sampler_thread_ = INVALID_HANDLE_VALUE; |
| 1471 | profiled_thread_ = INVALID_HANDLE_VALUE; |
| 1472 | } |
| 1473 | |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1474 | Sampler* sampler_; |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1475 | HANDLE sampler_thread_; |
| 1476 | HANDLE profiled_thread_; |
| 1477 | |
| 1478 | // Sampler thread handler. |
| 1479 | void Runner() { |
| 1480 | // Context used for sampling the register state of the profiled thread. |
| 1481 | CONTEXT context; |
| 1482 | memset(&context, 0, sizeof(context)); |
| 1483 | // Loop until the sampler is disengaged. |
| 1484 | while (sampler_->IsActive()) { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1485 | TickSample sample; |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1486 | |
| 1487 | // If profiling, we record the pc and sp of the profiled thread. |
| 1488 | if (sampler_->IsProfiling()) { |
| 1489 | // Pause the profiled thread and get its context. |
| 1490 | SuspendThread(profiled_thread_); |
| 1491 | context.ContextFlags = CONTEXT_FULL; |
| 1492 | GetThreadContext(profiled_thread_, &context); |
| 1493 | ResumeThread(profiled_thread_); |
| 1494 | // Invoke tick handler with program counter and stack pointer. |
| 1495 | sample.pc = context.Eip; |
| 1496 | sample.sp = context.Esp; |
| 1497 | } |
| 1498 | |
| 1499 | // We always sample the VM state. |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1500 | sample.state = Logger::state(); |
| 1501 | sampler_->Tick(&sample); |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1502 | |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1503 | // Wait until next sampling. |
| 1504 | Sleep(sampler_->interval_); |
| 1505 | } |
| 1506 | } |
| 1507 | }; |
| 1508 | |
| 1509 | |
| 1510 | // Entry point for sampler thread. |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1511 | static unsigned int __stdcall SamplerEntry(void* arg) { |
| 1512 | Sampler::PlatformData* data = |
| 1513 | reinterpret_cast<Sampler::PlatformData*>(arg); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1514 | data->Runner(); |
| 1515 | return 0; |
| 1516 | } |
| 1517 | |
| 1518 | |
| 1519 | // Initialize a profile sampler. |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1520 | Sampler::Sampler(int interval, bool profiling) |
| 1521 | : interval_(interval), profiling_(profiling), active_(false) { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1522 | data_ = new PlatformData(this); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1523 | } |
| 1524 | |
| 1525 | |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1526 | Sampler::~Sampler() { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1527 | delete data_; |
| 1528 | } |
| 1529 | |
| 1530 | |
| 1531 | // Start profiling. |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1532 | void Sampler::Start() { |
| 1533 | // If we are profiling, we need to be able to access the calling |
| 1534 | // thread. |
| 1535 | if (IsProfiling()) { |
| 1536 | // Get a handle to the calling thread. This is the thread that we are |
| 1537 | // going to profile. We need to duplicate the handle because we are |
| 1538 | // going to use it in the sampler thread. using GetThreadHandle() will |
| 1539 | // not work in this case. |
| 1540 | BOOL ok = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), |
| 1541 | GetCurrentProcess(), &data_->profiled_thread_, |
| 1542 | THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME | |
| 1543 | THREAD_QUERY_INFORMATION, FALSE, 0); |
| 1544 | if (!ok) return; |
| 1545 | } |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1546 | |
| 1547 | // Start sampler thread. |
| 1548 | unsigned int tid; |
| 1549 | active_ = true; |
| 1550 | data_->sampler_thread_ = reinterpret_cast<HANDLE>( |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1551 | _beginthreadex(NULL, 0, SamplerEntry, data_, 0, &tid)); |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1552 | // Set thread to high priority to increase sampling accuracy. |
| 1553 | SetThreadPriority(data_->sampler_thread_, THREAD_PRIORITY_TIME_CRITICAL); |
| 1554 | } |
| 1555 | |
| 1556 | |
| 1557 | // Stop profiling. |
mads.s.ager@gmail.com | 9a4089a | 2008-09-01 08:55:01 +0000 | [diff] [blame] | 1558 | void Sampler::Stop() { |
christian.plesner.hansen | 43d26ec | 2008-07-03 15:10:15 +0000 | [diff] [blame] | 1559 | // Seting active to false triggers termination of the sampler |
| 1560 | // thread. |
| 1561 | active_ = false; |
| 1562 | |
| 1563 | // Wait for sampler thread to terminate. |
| 1564 | WaitForSingleObject(data_->sampler_thread_, INFINITE); |
| 1565 | |
| 1566 | // Release the thread handles |
| 1567 | CloseHandle(data_->sampler_thread_); |
| 1568 | CloseHandle(data_->profiled_thread_); |
| 1569 | } |
| 1570 | |
| 1571 | |
| 1572 | #endif // ENABLE_LOGGING_AND_PROFILING |
| 1573 | |
| 1574 | } } // namespace v8::internal |