00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #ifndef WIN32_LEAN_AND_MEAN
00030
00031 #define WIN32_LEAN_AND_MEAN
00032 #endif
00033 #ifndef NOMINMAX
00034 #define NOMINMAX
00035 #endif
00036 #ifndef NOKERNEL
00037 #define NOKERNEL
00038 #endif
00039 #ifndef NOUSER
00040 #define NOUSER
00041 #endif
00042 #ifndef NOSERVICE
00043 #define NOSERVICE
00044 #endif
00045 #ifndef NOSOUND
00046 #define NOSOUND
00047 #endif
00048 #ifndef NOMCX
00049 #define NOMCX
00050 #endif
00051
00052 #include <windows.h>
00053
00054 #include <mmsystem.h>
00055 #include <dbghelp.h>
00056 #include <tlhelp32.h>
00057
00058
00059
00060 #include <winsock2.h>
00061 #include <process.h>
00062 #include <stdlib.h>
00063
00064 #pragma comment(lib, "winmm.lib") // force linkage with winmm.
00065
00066 #undef VOID
00067 #undef DELETE
00068 #undef IN
00069 #undef THIS
00070 #undef CONST
00071 #undef NAN
00072 #undef GetObject
00073 #undef CreateMutex
00074 #undef CreateSemaphore
00075
00076 #include "v8.h"
00077
00078 #include "platform.h"
00079
00080
00081
00082
00083
00084
00085
00086 namespace v8 {
00087 namespace internal {
00088
00089 int isfinite(double x) {
00090 return _finite(x);
00091 }
00092
00093 }
00094 }
00095
00096
00097 int isnan(double x) {
00098 return _isnan(x);
00099 }
00100
00101
00102
00103 int isinf(double x) {
00104 return (_fpclass(x) & (_FPCLASS_PINF | _FPCLASS_NINF)) != 0;
00105 }
00106
00107
00108
00109 int isless(double x, double y) {
00110 return isnan(x) || isnan(y) ? 0 : x < y;
00111 }
00112
00113
00114
00115 int isgreater(double x, double y) {
00116 return isnan(x) || isnan(y) ? 0 : x > y;
00117 }
00118
00119
00120
00121 int fpclassify(double x) {
00122
00123 int flags = _fpclass(x);
00124
00125
00126
00127 if (flags & (_FPCLASS_PN | _FPCLASS_NN)) return FP_NORMAL;
00128 if (flags & (_FPCLASS_PZ | _FPCLASS_NZ)) return FP_ZERO;
00129 if (flags & (_FPCLASS_PD | _FPCLASS_ND)) return FP_SUBNORMAL;
00130 if (flags & (_FPCLASS_PINF | _FPCLASS_NINF)) return FP_INFINITE;
00131
00132
00133 ASSERT(flags & (_FPCLASS_SNAN | _FPCLASS_QNAN));
00134 return FP_NAN;
00135 }
00136
00137
00138
00139 int signbit(double x) {
00140
00141
00142 if (x == 0)
00143 return _fpclass(x) & _FPCLASS_NZ;
00144 else
00145 return x < 0;
00146 }
00147
00148
00149
00150
00151 int random() {
00152 return rand();
00153 }
00154
00155
00156
00157
00158 int strncasecmp(const char* s1, const char* s2, int n) {
00159 return _strnicmp(s1, s2, n);
00160 }
00161
00162 namespace v8 { namespace internal {
00163
00164 double ceiling(double x) {
00165 return ceil(x);
00166 }
00167
00168
00169
00170
00171
00172
00173
00174 class Time {
00175 public:
00176
00177 Time();
00178 explicit Time(double jstime);
00179 Time(int year, int mon, int day, int hour, int min, int sec);
00180
00181
00182 double ToJSTime();
00183
00184
00185 void SetToCurrentTime();
00186
00187
00188
00189
00190
00191
00192 int64_t LocalOffset();
00193
00194
00195 int64_t DaylightSavingsOffset();
00196
00197
00198
00199 char* LocalTimezone();
00200
00201 private:
00202
00203 static const int64_t kTimeEpoc = 116444736000000000;
00204 static const int64_t kTimeScaler = 10000;
00205 static const int64_t kMsPerMinute = 60000;
00206
00207
00208 static const int kTzNameSize = 128;
00209 static const bool kShortTzNames = false;
00210
00211
00212
00213
00214 static bool tz_initialized_;
00215 static TIME_ZONE_INFORMATION tzinfo_;
00216 static char std_tz_name_[kTzNameSize];
00217 static char dst_tz_name_[kTzNameSize];
00218
00219
00220 static void TzSet();
00221
00222
00223 static const char* GuessTimezoneNameFromBias(int bias);
00224
00225
00226 bool InDST();
00227
00228
00229
00230 int64_t Diff(Time* other);
00231
00232
00233 FILETIME& ft() { return time_.ft_; }
00234
00235
00236 int64_t& t() { return time_.t_; }
00237
00238
00239
00240
00241
00242
00243 union TimeStamp {
00244 FILETIME ft_;
00245 int64_t t_;
00246 };
00247
00248 TimeStamp time_;
00249 };
00250
00251
00252 bool Time::tz_initialized_ = false;
00253 TIME_ZONE_INFORMATION Time::tzinfo_;
00254 char Time::std_tz_name_[kTzNameSize];
00255 char Time::dst_tz_name_[kTzNameSize];
00256
00257
00258
00259 Time::Time() {
00260 t() = 0;
00261 }
00262
00263
00264
00265 Time::Time(double jstime) {
00266 t() = static_cast<uint64_t>(jstime) * kTimeScaler + kTimeEpoc;
00267 }
00268
00269
00270
00271 Time::Time(int year, int mon, int day, int hour, int min, int sec) {
00272 SYSTEMTIME st;
00273 st.wYear = year;
00274 st.wMonth = mon;
00275 st.wDay = day;
00276 st.wHour = hour;
00277 st.wMinute = min;
00278 st.wSecond = sec;
00279 st.wMilliseconds = 0;
00280 SystemTimeToFileTime(&st, &ft());
00281 }
00282
00283
00284
00285 double Time::ToJSTime() {
00286 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
00287 }
00288
00289
00290
00291
00292 const char* Time::GuessTimezoneNameFromBias(int bias) {
00293 static const int kHour = 60;
00294 switch (-bias) {
00295 case -9*kHour: return "Alaska";
00296 case -8*kHour: return "Pacific";
00297 case -7*kHour: return "Mountain";
00298 case -6*kHour: return "Central";
00299 case -5*kHour: return "Eastern";
00300 case -4*kHour: return "Atlantic";
00301 case 0*kHour: return "GMT";
00302 case +1*kHour: return "Central Europe";
00303 case +2*kHour: return "Eastern Europe";
00304 case +3*kHour: return "Russia";
00305 case +5*kHour + 30: return "India";
00306 case +8*kHour: return "China";
00307 case +9*kHour: return "Japan";
00308 case +12*kHour: return "New Zealand";
00309 default: return "Local";
00310 }
00311 }
00312
00313
00314
00315
00316
00317 void Time::TzSet() {
00318
00319 if (tz_initialized_) return;
00320
00321
00322 memset(&tzinfo_, 0, sizeof(tzinfo_));
00323 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
00324
00325 tzinfo_.Bias = -60;
00326 tzinfo_.StandardDate.wMonth = 10;
00327 tzinfo_.StandardDate.wDay = 5;
00328 tzinfo_.StandardDate.wHour = 3;
00329 tzinfo_.StandardBias = 0;
00330 tzinfo_.DaylightDate.wMonth = 3;
00331 tzinfo_.DaylightDate.wDay = 5;
00332 tzinfo_.DaylightDate.wHour = 2;
00333 tzinfo_.DaylightBias = -60;
00334 }
00335
00336
00337 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize),
00338 "%S",
00339 tzinfo_.StandardName);
00340 std_tz_name_[kTzNameSize - 1] = '\0';
00341 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize),
00342 "%S",
00343 tzinfo_.DaylightName);
00344 dst_tz_name_[kTzNameSize - 1] = '\0';
00345
00346
00347
00348
00349
00350 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
00351 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
00352 "%s Standard Time",
00353 GuessTimezoneNameFromBias(tzinfo_.Bias));
00354 }
00355 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
00356 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
00357 "%s Daylight Time",
00358 GuessTimezoneNameFromBias(tzinfo_.Bias));
00359 }
00360
00361
00362 tz_initialized_ = true;
00363 }
00364
00365
00366
00367 int64_t Time::Diff(Time* other) {
00368 return (t() - other->t()) / kTimeScaler;
00369 }
00370
00371
00372
00373 void Time::SetToCurrentTime() {
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391 static bool initialized = false;
00392 static TimeStamp init_time;
00393 static DWORD init_ticks;
00394 static const int kHundredNanosecondsPerSecond = 10000;
00395 static const int kMaxClockElapsedTime =
00396 60*60*24*kHundredNanosecondsPerSecond;
00397
00398
00399 bool needs_resync = !initialized;
00400
00401
00402 TimeStamp time_now;
00403 GetSystemTimeAsFileTime(&time_now.ft_);
00404 DWORD ticks_now = timeGetTime();
00405
00406
00407 needs_resync |= ticks_now < init_ticks;
00408
00409
00410 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
00411
00412
00413 if (needs_resync) {
00414 GetSystemTimeAsFileTime(&init_time.ft_);
00415 init_ticks = ticks_now = timeGetTime();
00416 initialized = true;
00417 }
00418
00419
00420 DWORD elapsed = ticks_now - init_ticks;
00421 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
00422 }
00423
00424
00425
00426
00427 int64_t Time::LocalOffset() {
00428
00429 TzSet();
00430
00431
00432
00433
00434
00435 SYSTEMTIME utc;
00436 FileTimeToSystemTime(&ft(), &utc);
00437
00438
00439 SYSTEMTIME local;
00440 SystemTimeToTzSpecificLocalTime(&tzinfo_, &utc, &local);
00441
00442
00443
00444
00445 Time localtime;
00446 SystemTimeToFileTime(&local, &localtime.ft());
00447
00448
00449
00450 return localtime.Diff(this);
00451 }
00452
00453
00454
00455 bool Time::InDST() {
00456
00457 TzSet();
00458
00459
00460 bool in_dst = false;
00461 if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) {
00462
00463 int64_t offset = LocalOffset();
00464
00465
00466
00467 int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute;
00468
00469
00470
00471 in_dst = offset == dstofs;
00472 }
00473
00474 return in_dst;
00475 }
00476
00477
00478
00479 int64_t Time::DaylightSavingsOffset() {
00480 return InDST() ? 60 * kMsPerMinute : 0;
00481 }
00482
00483
00484
00485
00486 char* Time::LocalTimezone() {
00487
00488
00489 return InDST() ? dst_tz_name_ : std_tz_name_;
00490 }
00491
00492
00493 void OS::Setup() {
00494
00495
00496
00497
00498
00499 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
00500 srand(static_cast<unsigned int>(seed));
00501 }
00502
00503
00504
00505 int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
00506 FILETIME dummy;
00507 uint64_t usertime;
00508
00509
00510 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
00511 reinterpret_cast<FILETIME*>(&usertime))) return -1;
00512
00513
00514 usertime /= 10;
00515
00516
00517 *secs = static_cast<uint32_t>(usertime / 1000000);
00518 *usecs = static_cast<uint32_t>(usertime % 1000000);
00519 return 0;
00520 }
00521
00522
00523
00524
00525 double OS::TimeCurrentMillis() {
00526 Time t;
00527 t.SetToCurrentTime();
00528 return t.ToJSTime();
00529 }
00530
00531
00532 int64_t OS::Ticks() {
00533 return timeGetTime() * 1000;
00534 }
00535
00536
00537
00538
00539 char* OS::LocalTimezone(double time) {
00540 return Time(time).LocalTimezone();
00541 }
00542
00543
00544
00545
00546 double OS::LocalTimeOffset() {
00547
00548 Time t(TimeCurrentMillis());
00549
00550 return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset());
00551 }
00552
00553
00554
00555
00556 double OS::DaylightSavingsOffset(double time) {
00557 int64_t offset = Time(time).DaylightSavingsOffset();
00558 return static_cast<double>(offset);
00559 }
00560
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572
00573
00574 enum OutputMode {
00575 UNKNOWN,
00576 CONSOLE,
00577 ODS
00578 };
00579
00580 static OutputMode output_mode = UNKNOWN;
00581
00582
00583
00584 static bool HasConsole() {
00585
00586
00587 if (output_mode == UNKNOWN) {
00588
00589
00590
00591
00592 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
00593 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
00594 output_mode = CONSOLE;
00595 else
00596 output_mode = ODS;
00597 }
00598 return output_mode == CONSOLE;
00599 }
00600
00601
00602 static void VPrintHelper(FILE* stream, const char* format, va_list args) {
00603 if (HasConsole()) {
00604 vfprintf(stream, format, args);
00605 } else {
00606
00607
00608
00609 EmbeddedVector<char, 4096> buffer;
00610 OS::VSNPrintF(buffer, format, args);
00611 OutputDebugStringA(buffer.start());
00612 }
00613 }
00614
00615
00616 FILE* OS::FOpen(const char* path, const char* mode) {
00617 FILE* result;
00618 if (fopen_s(&result, path, mode) == 0) {
00619 return result;
00620 } else {
00621 return NULL;
00622 }
00623 }
00624
00625
00626
00627 void OS::Print(const char* format, ...) {
00628 va_list args;
00629 va_start(args, format);
00630 VPrint(format, args);
00631 va_end(args);
00632 }
00633
00634
00635 void OS::VPrint(const char* format, va_list args) {
00636 VPrintHelper(stdout, format, args);
00637 }
00638
00639
00640
00641 void OS::PrintError(const char* format, ...) {
00642 va_list args;
00643 va_start(args, format);
00644 VPrintError(format, args);
00645 va_end(args);
00646 }
00647
00648
00649 void OS::VPrintError(const char* format, va_list args) {
00650 VPrintHelper(stderr, format, args);
00651 }
00652
00653
00654 int OS::SNPrintF(Vector<char> str, const char* format, ...) {
00655 va_list args;
00656 va_start(args, format);
00657 int result = VSNPrintF(str, format, args);
00658 va_end(args);
00659 return result;
00660 }
00661
00662
00663 int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
00664 int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
00665
00666
00667 if (n < 0 || n >= str.length()) {
00668 str[str.length() - 1] = '\0';
00669 return -1;
00670 } else {
00671 return n;
00672 }
00673 }
00674
00675
00676 void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
00677 int result = strncpy_s(dest.start(), dest.length(), src, n);
00678 USE(result);
00679 ASSERT(result == 0);
00680 }
00681
00682
00683 void OS::WcsCpy(Vector<wchar_t> dest, const wchar_t* src) {
00684 int result = wcscpy_s(dest.start(), dest.length(), src);
00685 USE(result);
00686 ASSERT(result == 0);
00687 }
00688
00689
00690 char *OS::StrDup(const char* str) {
00691 return _strdup(str);
00692 }
00693
00694
00695
00696
00697
00698
00699
00700 static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
00701 static void* highest_ever_allocated = reinterpret_cast<void*>(0);
00702
00703
00704 static void UpdateAllocatedSpaceLimits(void* address, int size) {
00705 lowest_ever_allocated = Min(lowest_ever_allocated, address);
00706 highest_ever_allocated =
00707 Max(highest_ever_allocated,
00708 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
00709 }
00710
00711
00712 bool OS::IsOutsideAllocatedSpace(void* pointer) {
00713 if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated)
00714 return true;
00715
00716 if (IsBadWritePtr(pointer, 1))
00717 return true;
00718 return false;
00719 }
00720
00721
00722
00723
00724
00725 static size_t GetPageSize() {
00726 static size_t page_size = 0;
00727 if (page_size == 0) {
00728 SYSTEM_INFO info;
00729 GetSystemInfo(&info);
00730 page_size = RoundUpToPowerOf2(info.dwPageSize);
00731 }
00732 return page_size;
00733 }
00734
00735
00736
00737
00738 size_t OS::AllocateAlignment() {
00739 static size_t allocate_alignment = 0;
00740 if (allocate_alignment == 0) {
00741 SYSTEM_INFO info;
00742 GetSystemInfo(&info);
00743 allocate_alignment = info.dwAllocationGranularity;
00744 }
00745 return allocate_alignment;
00746 }
00747
00748
00749 void* OS::Allocate(const size_t requested,
00750 size_t* allocated,
00751 bool executable) {
00752
00753 size_t msize = RoundUp(requested, GetPageSize());
00754
00755
00756 int prot = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
00757 LPVOID mbase = VirtualAlloc(NULL, msize, MEM_COMMIT | MEM_RESERVE, prot);
00758 if (mbase == NULL) {
00759 LOG(StringEvent("OS::Allocate", "VirtualAlloc failed"));
00760 return NULL;
00761 }
00762
00763 ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
00764
00765 *allocated = msize;
00766 UpdateAllocatedSpaceLimits(mbase, msize);
00767 return mbase;
00768 }
00769
00770
00771 void OS::Free(void* buf, const size_t length) {
00772
00773 VirtualFree(buf, 0, MEM_RELEASE);
00774 USE(length);
00775 }
00776
00777
00778 void OS::Sleep(int milliseconds) {
00779 ::Sleep(milliseconds);
00780 }
00781
00782
00783 void OS::Abort() {
00784
00785 _set_abort_behavior(0, _WRITE_ABORT_MSG);
00786 _set_abort_behavior(0, _CALL_REPORTFAULT);
00787 abort();
00788 }
00789
00790
00791 void OS::DebugBreak() {
00792 __debugbreak();
00793 }
00794
00795
00796 class Win32MemoryMappedFile : public OS::MemoryMappedFile {
00797 public:
00798 Win32MemoryMappedFile(HANDLE file, HANDLE file_mapping, void* memory)
00799 : file_(file), file_mapping_(file_mapping), memory_(memory) { }
00800 virtual ~Win32MemoryMappedFile();
00801 virtual void* memory() { return memory_; }
00802 private:
00803 HANDLE file_;
00804 HANDLE file_mapping_;
00805 void* memory_;
00806 };
00807
00808
00809 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
00810 void* initial) {
00811
00812 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
00813 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
00814 if (file == NULL) return NULL;
00815
00816 HANDLE file_mapping = CreateFileMapping(file, NULL,
00817 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
00818 if (file_mapping == NULL) return NULL;
00819
00820 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
00821 if (memory) memmove(memory, initial, size);
00822 return new Win32MemoryMappedFile(file, file_mapping, memory);
00823 }
00824
00825
00826 Win32MemoryMappedFile::~Win32MemoryMappedFile() {
00827 if (memory_ != NULL)
00828 UnmapViewOfFile(memory_);
00829 CloseHandle(file_mapping_);
00830 CloseHandle(file_);
00831 }
00832
00833
00834
00835
00836
00837
00838
00839
00840
00841 #define DBGHELP_FUNCTION_LIST(V) \
00842 V(SymInitialize) \
00843 V(SymGetOptions) \
00844 V(SymSetOptions) \
00845 V(SymGetSearchPath) \
00846 V(SymLoadModule64) \
00847 V(StackWalk64) \
00848 V(SymGetSymFromAddr64) \
00849 V(SymGetLineFromAddr64) \
00850 V(SymFunctionTableAccess64) \
00851 V(SymGetModuleBase64)
00852
00853
00854 #define TLHELP32_FUNCTION_LIST(V) \
00855 V(CreateToolhelp32Snapshot) \
00856 V(Module32FirstW) \
00857 V(Module32NextW)
00858
00859
00860
00861 #define DLL_FUNC_TYPE(name) _##name##_
00862 #define DLL_FUNC_VAR(name) _##name
00863
00864
00865
00866
00867
00868 #ifndef IN
00869 #define IN
00870 #endif
00871 #ifndef VOID
00872 #define VOID void
00873 #endif
00874
00875
00876 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
00877 IN PSTR UserSearchPath,
00878 IN BOOL fInvadeProcess);
00879 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
00880 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
00881 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
00882 IN HANDLE hProcess,
00883 OUT PSTR SearchPath,
00884 IN DWORD SearchPathLength);
00885 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
00886 IN HANDLE hProcess,
00887 IN HANDLE hFile,
00888 IN PSTR ImageName,
00889 IN PSTR ModuleName,
00890 IN DWORD64 BaseOfDll,
00891 IN DWORD SizeOfDll);
00892 typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
00893 DWORD MachineType,
00894 HANDLE hProcess,
00895 HANDLE hThread,
00896 LPSTACKFRAME64 StackFrame,
00897 PVOID ContextRecord,
00898 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
00899 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
00900 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
00901 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
00902 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
00903 IN HANDLE hProcess,
00904 IN DWORD64 qwAddr,
00905 OUT PDWORD64 pdwDisplacement,
00906 OUT PIMAGEHLP_SYMBOL64 Symbol);
00907 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
00908 IN HANDLE hProcess,
00909 IN DWORD64 qwAddr,
00910 OUT PDWORD pdwDisplacement,
00911 OUT PIMAGEHLP_LINE64 Line64);
00912
00913 typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
00914 HANDLE hProcess,
00915 DWORD64 AddrBase);
00916 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
00917 HANDLE hProcess,
00918 DWORD64 AddrBase);
00919
00920
00921 typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
00922 DWORD dwFlags,
00923 DWORD th32ProcessID);
00924 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
00925 LPMODULEENTRY32W lpme);
00926 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
00927 LPMODULEENTRY32W lpme);
00928
00929 #undef IN
00930 #undef VOID
00931
00932
00933 #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
00934 DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
00935 TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
00936 #undef DEF_DLL_FUNCTION
00937
00938
00939
00940
00941 static bool LoadDbgHelpAndTlHelp32() {
00942 static bool dbghelp_loaded = false;
00943
00944 if (dbghelp_loaded) return true;
00945
00946 HMODULE module;
00947
00948
00949 module = LoadLibrary(TEXT("dbghelp.dll"));
00950 if (module == NULL) {
00951 return false;
00952 }
00953
00954 #define LOAD_DLL_FUNC(name) \
00955 DLL_FUNC_VAR(name) = \
00956 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
00957
00958 DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
00959
00960 #undef LOAD_DLL_FUNC
00961
00962
00963
00964 module = LoadLibrary(TEXT("kernel32.dll"));
00965 if (module == NULL) {
00966 return false;
00967 }
00968
00969 #define LOAD_DLL_FUNC(name) \
00970 DLL_FUNC_VAR(name) = \
00971 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
00972
00973 TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
00974
00975 #undef LOAD_DLL_FUNC
00976
00977
00978 bool result =
00979 #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
00980
00981 DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
00982 TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
00983
00984 #undef DLL_FUNC_LOADED
00985 true;
00986
00987 dbghelp_loaded = result;
00988 return result;
00989
00990
00991 }
00992
00993
00994
00995 static bool LoadSymbols(HANDLE process_handle) {
00996 static bool symbols_loaded = false;
00997
00998 if (symbols_loaded) return true;
00999
01000 BOOL ok;
01001
01002
01003 ok = _SymInitialize(process_handle,
01004 NULL,
01005 FALSE);
01006 if (!ok) return false;
01007
01008 DWORD options = _SymGetOptions();
01009 options |= SYMOPT_LOAD_LINES;
01010 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
01011 options = _SymSetOptions(options);
01012
01013 char buf[OS::kStackWalkMaxNameLen] = {0};
01014 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
01015 if (!ok) {
01016 int err = GetLastError();
01017 PrintF("%d\n", err);
01018 return false;
01019 }
01020
01021 HANDLE snapshot = _CreateToolhelp32Snapshot(
01022 TH32CS_SNAPMODULE,
01023 GetCurrentProcessId());
01024 if (snapshot == INVALID_HANDLE_VALUE) return false;
01025 MODULEENTRY32W module_entry;
01026 module_entry.dwSize = sizeof(module_entry);
01027 BOOL cont = _Module32FirstW(snapshot, &module_entry);
01028 while (cont) {
01029 DWORD64 base;
01030
01031
01032 base = _SymLoadModule64(
01033 process_handle,
01034 0,
01035 reinterpret_cast<PSTR>(module_entry.szExePath),
01036 reinterpret_cast<PSTR>(module_entry.szModule),
01037 reinterpret_cast<DWORD64>(module_entry.modBaseAddr),
01038 module_entry.modBaseSize);
01039 if (base == 0) {
01040 int err = GetLastError();
01041 if (err != ERROR_MOD_NOT_FOUND &&
01042 err != ERROR_INVALID_HANDLE) return false;
01043 }
01044 LOG(SharedLibraryEvent(
01045 module_entry.szExePath,
01046 reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
01047 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
01048 module_entry.modBaseSize)));
01049 cont = _Module32NextW(snapshot, &module_entry);
01050 }
01051 CloseHandle(snapshot);
01052
01053 symbols_loaded = true;
01054 return true;
01055 }
01056
01057
01058 void OS::LogSharedLibraryAddresses() {
01059
01060
01061
01062
01063 if (!LoadDbgHelpAndTlHelp32()) return;
01064 HANDLE process_handle = GetCurrentProcess();
01065 LoadSymbols(process_handle);
01066 }
01067
01068
01069
01070
01071
01072
01073
01074 #pragma warning(push)
01075 #pragma warning(disable : 4748)
01076 int OS::StackWalk(OS::StackFrame* frames, int frames_size) {
01077 BOOL ok;
01078
01079
01080 if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError;
01081
01082
01083 HANDLE process_handle = GetCurrentProcess();
01084 HANDLE thread_handle = GetCurrentThread();
01085
01086
01087 if (!LoadSymbols(process_handle)) return kStackWalkError;
01088
01089
01090 CONTEXT context;
01091 memset(&context, 0, sizeof(context));
01092 context.ContextFlags = CONTEXT_CONTROL;
01093 context.ContextFlags = CONTEXT_CONTROL;
01094 __asm call x
01095 __asm x: pop eax
01096 __asm mov context.Eip, eax
01097 __asm mov context.Ebp, ebp
01098 __asm mov context.Esp, esp
01099
01100
01101
01102
01103
01104
01105 STACKFRAME64 stack_frame;
01106 memset(&stack_frame, 0, sizeof(stack_frame));
01107 stack_frame.AddrPC.Offset = context.Eip;
01108 stack_frame.AddrPC.Mode = AddrModeFlat;
01109 stack_frame.AddrFrame.Offset = context.Ebp;
01110 stack_frame.AddrFrame.Mode = AddrModeFlat;
01111 stack_frame.AddrStack.Offset = context.Esp;
01112 stack_frame.AddrStack.Mode = AddrModeFlat;
01113 int frames_count = 0;
01114
01115
01116 while (frames_count < frames_size) {
01117 ok = _StackWalk64(
01118 IMAGE_FILE_MACHINE_I386,
01119 process_handle,
01120 thread_handle,
01121 &stack_frame,
01122 &context,
01123 NULL,
01124 _SymFunctionTableAccess64,
01125 _SymGetModuleBase64,
01126 NULL);
01127 if (!ok) break;
01128
01129
01130 ASSERT((stack_frame.AddrPC.Offset >> 32) == 0);
01131 frames[frames_count].address =
01132 reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
01133
01134
01135 DWORD64 symbol_displacement;
01136 IMAGEHLP_SYMBOL64* symbol = NULL;
01137 symbol = NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen);
01138 if (!symbol) return kStackWalkError;
01139 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
01140 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
01141 symbol->MaxNameLength = kStackWalkMaxNameLen;
01142 ok = _SymGetSymFromAddr64(process_handle,
01143 stack_frame.AddrPC.Offset,
01144 &symbol_displacement,
01145 symbol);
01146 if (ok) {
01147
01148 IMAGEHLP_LINE64 Line;
01149 memset(&Line, 0, sizeof(Line));
01150 Line.SizeOfStruct = sizeof(Line);
01151 DWORD line_displacement;
01152 ok = _SymGetLineFromAddr64(
01153 process_handle,
01154 stack_frame.AddrPC.Offset,
01155 &line_displacement,
01156 &Line);
01157
01158
01159 if (ok) {
01160 SNPrintF(MutableCStrVector(frames[frames_count].text,
01161 kStackWalkMaxTextLen),
01162 "%s %s:%d:%d",
01163 symbol->Name, Line.FileName, Line.LineNumber,
01164 line_displacement);
01165 } else {
01166 SNPrintF(MutableCStrVector(frames[frames_count].text,
01167 kStackWalkMaxTextLen),
01168 "%s",
01169 symbol->Name);
01170 }
01171
01172 frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
01173 } else {
01174
01175 frames[frames_count].text[0] = '\0';
01176
01177
01178
01179 int err = GetLastError();
01180 if (err != ERROR_MOD_NOT_FOUND) {
01181 DeleteArray(symbol);
01182 break;
01183 }
01184 }
01185 DeleteArray(symbol);
01186
01187 frames_count++;
01188 }
01189
01190
01191 return frames_count;
01192 }
01193
01194
01195 #pragma warning(pop)
01196
01197
01198 double OS::nan_value() {
01199 static const __int64 nanval = 0xfff8000000000000;
01200 return *reinterpret_cast<const double*>(&nanval);
01201 }
01202
01203
01204 int OS::ActivationFrameAlignment() {
01205
01206 return 0;
01207 }
01208
01209
01210 bool VirtualMemory::IsReserved() {
01211 return address_ != NULL;
01212 }
01213
01214
01215 VirtualMemory::VirtualMemory(size_t size) {
01216 address_ = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
01217 size_ = size;
01218 }
01219
01220
01221 VirtualMemory::~VirtualMemory() {
01222 if (IsReserved()) {
01223 if (0 == VirtualFree(address(), 0, MEM_RELEASE)) address_ = NULL;
01224 }
01225 }
01226
01227
01228 bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
01229 int prot = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
01230 if (NULL == VirtualAlloc(address, size, MEM_COMMIT, prot)) {
01231 return false;
01232 }
01233
01234 UpdateAllocatedSpaceLimits(address, size);
01235 return true;
01236 }
01237
01238
01239 bool VirtualMemory::Uncommit(void* address, size_t size) {
01240 ASSERT(IsReserved());
01241 return VirtualFree(address, size, MEM_DECOMMIT) != NULL;
01242 }
01243
01244
01245
01246
01247
01248
01249 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
01250 static const DWORD kNoThreadId = 0;
01251
01252
01253 class ThreadHandle::PlatformData : public Malloced {
01254 public:
01255 explicit PlatformData(ThreadHandle::Kind kind) {
01256 Initialize(kind);
01257 }
01258
01259 void Initialize(ThreadHandle::Kind kind) {
01260 switch (kind) {
01261 case ThreadHandle::SELF: tid_ = GetCurrentThreadId(); break;
01262 case ThreadHandle::INVALID: tid_ = kNoThreadId; break;
01263 }
01264 }
01265 DWORD tid_;
01266 };
01267
01268
01269
01270
01271
01272
01273 static unsigned int __stdcall ThreadEntry(void* arg) {
01274 Thread* thread = reinterpret_cast<Thread*>(arg);
01275
01276
01277
01278 thread->thread_handle_data()->tid_ = GetCurrentThreadId();
01279 thread->Run();
01280 return 0;
01281 }
01282
01283
01284
01285 ThreadHandle::ThreadHandle(ThreadHandle::Kind kind) {
01286 data_ = new PlatformData(kind);
01287 }
01288
01289
01290 ThreadHandle::~ThreadHandle() {
01291 delete data_;
01292 }
01293
01294
01295
01296 bool ThreadHandle::IsSelf() const {
01297 return GetCurrentThreadId() == data_->tid_;
01298 }
01299
01300
01301
01302 bool ThreadHandle::IsValid() const {
01303 return data_->tid_ != kNoThreadId;
01304 }
01305
01306
01307 void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
01308 data_->Initialize(kind);
01309 }
01310
01311
01312 class Thread::PlatformData : public Malloced {
01313 public:
01314 explicit PlatformData(HANDLE thread) : thread_(thread) {}
01315 HANDLE thread_;
01316 };
01317
01318
01319
01320
01321
01322 Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
01323 data_ = new PlatformData(kNoThread);
01324 }
01325
01326
01327
01328 Thread::~Thread() {
01329 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
01330 delete data_;
01331 }
01332
01333
01334
01335
01336
01337 void Thread::Start() {
01338 data_->thread_ = reinterpret_cast<HANDLE>(
01339 _beginthreadex(NULL,
01340 0,
01341 ThreadEntry,
01342 this,
01343 0,
01344 reinterpret_cast<unsigned int*>(
01345 &thread_handle_data()->tid_)));
01346 ASSERT(IsValid());
01347 }
01348
01349
01350
01351 void Thread::Join() {
01352 WaitForSingleObject(data_->thread_, INFINITE);
01353 }
01354
01355
01356 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
01357 DWORD result = TlsAlloc();
01358 ASSERT(result != TLS_OUT_OF_INDEXES);
01359 return static_cast<LocalStorageKey>(result);
01360 }
01361
01362
01363 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
01364 BOOL result = TlsFree(static_cast<DWORD>(key));
01365 USE(result);
01366 ASSERT(result);
01367 }
01368
01369
01370 void* Thread::GetThreadLocal(LocalStorageKey key) {
01371 return TlsGetValue(static_cast<DWORD>(key));
01372 }
01373
01374
01375 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
01376 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
01377 USE(result);
01378 ASSERT(result);
01379 }
01380
01381
01382
01383 void Thread::YieldCPU() {
01384 Sleep(0);
01385 }
01386
01387
01388
01389
01390
01391
01392
01393
01394
01395
01396 class Win32Mutex : public Mutex {
01397 public:
01398
01399 Win32Mutex() { InitializeCriticalSection(&cs_); }
01400
01401 ~Win32Mutex() { DeleteCriticalSection(&cs_); }
01402
01403 int Lock() {
01404 EnterCriticalSection(&cs_);
01405 return 0;
01406 }
01407
01408 int Unlock() {
01409 LeaveCriticalSection(&cs_);
01410 return 0;
01411 }
01412
01413 private:
01414 CRITICAL_SECTION cs_;
01415 };
01416
01417
01418 Mutex* OS::CreateMutex() {
01419 return new Win32Mutex();
01420 }
01421
01422
01423
01424
01425
01426
01427
01428
01429
01430
01431 class Win32Semaphore : public Semaphore {
01432 public:
01433 explicit Win32Semaphore(int count) {
01434 sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
01435 }
01436
01437 ~Win32Semaphore() {
01438 CloseHandle(sem);
01439 }
01440
01441 void Wait() {
01442 WaitForSingleObject(sem, INFINITE);
01443 }
01444
01445 void Signal() {
01446 LONG dummy;
01447 ReleaseSemaphore(sem, 1, &dummy);
01448 }
01449
01450 private:
01451 HANDLE sem;
01452 };
01453
01454
01455 Semaphore* OS::CreateSemaphore(int count) {
01456 return new Win32Semaphore(count);
01457 }
01458
01459 #ifdef ENABLE_LOGGING_AND_PROFILING
01460
01461
01462
01463
01464
01465
01466
01467 class Sampler::PlatformData : public Malloced {
01468 public:
01469 explicit PlatformData(Sampler* sampler) {
01470 sampler_ = sampler;
01471 sampler_thread_ = INVALID_HANDLE_VALUE;
01472 profiled_thread_ = INVALID_HANDLE_VALUE;
01473 }
01474
01475 Sampler* sampler_;
01476 HANDLE sampler_thread_;
01477 HANDLE profiled_thread_;
01478
01479
01480 void Runner() {
01481
01482 CONTEXT context;
01483 memset(&context, 0, sizeof(context));
01484
01485 while (sampler_->IsActive()) {
01486 TickSample sample;
01487
01488
01489 if (sampler_->IsProfiling()) {
01490
01491 SuspendThread(profiled_thread_);
01492 context.ContextFlags = CONTEXT_FULL;
01493 GetThreadContext(profiled_thread_, &context);
01494 ResumeThread(profiled_thread_);
01495
01496 sample.pc = context.Eip;
01497 sample.sp = context.Esp;
01498 }
01499
01500
01501 sample.state = Logger::state();
01502 sampler_->Tick(&sample);
01503
01504
01505 Sleep(sampler_->interval_);
01506 }
01507 }
01508 };
01509
01510
01511
01512 static unsigned int __stdcall SamplerEntry(void* arg) {
01513 Sampler::PlatformData* data =
01514 reinterpret_cast<Sampler::PlatformData*>(arg);
01515 data->Runner();
01516 return 0;
01517 }
01518
01519
01520
01521 Sampler::Sampler(int interval, bool profiling)
01522 : interval_(interval), profiling_(profiling), active_(false) {
01523 data_ = new PlatformData(this);
01524 }
01525
01526
01527 Sampler::~Sampler() {
01528 delete data_;
01529 }
01530
01531
01532
01533 void Sampler::Start() {
01534
01535
01536 if (IsProfiling()) {
01537
01538
01539
01540
01541 BOOL ok = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
01542 GetCurrentProcess(), &data_->profiled_thread_,
01543 THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME |
01544 THREAD_QUERY_INFORMATION, FALSE, 0);
01545 if (!ok) return;
01546 }
01547
01548
01549 unsigned int tid;
01550 active_ = true;
01551 data_->sampler_thread_ = reinterpret_cast<HANDLE>(
01552 _beginthreadex(NULL, 0, SamplerEntry, data_, 0, &tid));
01553
01554 SetThreadPriority(data_->sampler_thread_, THREAD_PRIORITY_TIME_CRITICAL);
01555 }
01556
01557
01558
01559 void Sampler::Stop() {
01560
01561
01562 active_ = false;
01563
01564
01565 WaitForSingleObject(data_->sampler_thread_, INFINITE);
01566
01567
01568 CloseHandle(data_->sampler_thread_);
01569 CloseHandle(data_->profiled_thread_);
01570 }
01571
01572
01573 #endif // ENABLE_LOGGING_AND_PROFILING
01574
01575 } }