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