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