1 // Copyright 2006-2008 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 // Platform specific code for Win32.
29 #ifndef WIN32_LEAN_AND_MEAN
30 // WIN32_LEAN_AND_MEAN implies NOCRYPT and NOGDI.
31 #define WIN32_LEAN_AND_MEAN
32 #endif
33 #ifndef NOMINMAX
34 #define NOMINMAX
35 #endif
36 #ifndef NOKERNEL
37 #define NOKERNEL
38 #endif
39 #ifndef NOUSER
40 #define NOUSER
41 #endif
42 #ifndef NOSERVICE
43 #define NOSERVICE
44 #endif
45 #ifndef NOSOUND
46 #define NOSOUND
47 #endif
48 #ifndef NOMCX
49 #define NOMCX
50 #endif
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
56
57 #include <windows.h>
58
59 #include <time.h> // For LocalOffset() implementation.
60 #include <mmsystem.h> // For timeGetTime().
61 #ifdef __MINGW32__
62 // Require Windows XP or higher when compiling with MinGW. This is for MinGW
63 // header files to expose getaddrinfo.
64 #undef _WIN32_WINNT
65 #define _WIN32_WINNT 0x501
66 #endif // __MINGW32__
67 #ifndef __MINGW32__
68 #include <dbghelp.h> // For SymLoadModule64 and al.
69 #endif // __MINGW32__
70 #include <limits.h> // For INT_MAX and al.
71 #include <tlhelp32.h> // For Module32First and al.
72
73 // These additional WIN32 includes have to be right here as the #undef's below
74 // makes it impossible to have them elsewhere.
75 #include <winsock2.h>
76 #include <ws2tcpip.h>
77 #include <process.h> // for _beginthreadex()
78 #include <stdlib.h>
79
80 #undef VOID
81 #undef DELETE
82 #undef IN
83 #undef THIS
84 #undef CONST
85 #undef NAN
86 #undef GetObject
87 #undef CreateMutex
88 #undef CreateSemaphore
89
90 #include "v8.h"
91
92 #include "platform.h"
93
94 // Extra POSIX/ANSI routines for Win32 when when using Visual Studio C++. Please
95 // refer to The Open Group Base Specification for specification of the correct
96 // semantics for these functions.
97 // (http://www.opengroup.org/onlinepubs/000095399/)
98 #ifdef _MSC_VER
99
100 namespace v8 {
101 namespace internal {
102
103 // Test for finite value - usually defined in math.h
isfinite(double x)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
isnan(double x)112 int isnan(double x) {
113 return _isnan(x);
114 }
115
116
117 // Test for infinity - usually defined in math.h
isinf(double x)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
isless(double x,double y)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
isgreater(double x,double y)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
fpclassify(double x)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
signbit(double x)154 int signbit(double x) {
155 // We need to take care of the special case of both positive
156 // and negative versions of zero.
157 if (x == 0)
158 return _fpclass(x) & _FPCLASS_NZ;
159 else
160 return x < 0;
161 }
162
163
164 // Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
165 // defined in strings.h.
strncasecmp(const char * s1,const char * s2,int n)166 int strncasecmp(const char* s1, const char* s2, int n) {
167 return _strnicmp(s1, s2, n);
168 }
169
170 #endif // _MSC_VER
171
172
173 // Extra functions for MinGW. Most of these are the _s functions which are in
174 // the Microsoft Visual Studio C++ CRT.
175 #ifdef __MINGW32__
176
localtime_s(tm * out_tm,const time_t * time)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
_mkgmtime(tm * timeptr)186 time_t _mkgmtime(tm* timeptr) {
187 return mktime(timeptr);
188 }
189
190
fopen_s(FILE ** pFile,const char * filename,const char * mode)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
_vsnprintf_s(char * buffer,size_t sizeOfBuffer,size_t count,const char * format,va_list argptr)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
strncpy_s(char * strDest,size_t numberOfElements,const char * strSource,size_t count)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.
random()214 int random() {
215 return rand();
216 }
217
218
219 namespace v8 {
220 namespace internal {
221
ceiling(double x)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.
261 static const int64_t kTimeEpoc = 116444736000000000LL;
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.
ft()291 FILETIME& ft() { return time_.ft_; }
292
293 // Accessor for integer representation.
t()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.
Time()317 Time::Time() {
318 t() = 0;
319 }
320
321
322 // Initialize timestamp from a JavaScript timestamp.
Time(double jstime)323 Time::Time(double jstime) {
324 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
325 }
326
327
328 // Initialize timestamp from date/time components.
Time(int year,int mon,int day,int hour,int min,int sec)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.
ToJSTime()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.
GuessTimezoneNameFromBias(int bias)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.
TzSet()375 void Time::TzSet() {
376 // Just return if timezone information has already been initialized.
377 if (tz_initialized_) return;
378
379 // Initialize POSIX time zone data.
380 _tzset();
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.
397 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize),
398 "%S",
399 tzinfo_.StandardName);
400 std_tz_name_[kTzNameSize - 1] = '\0';
401 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize),
402 "%S",
403 tzinfo_.DaylightName);
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] == '@') {
411 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
412 "%s Standard Time",
413 GuessTimezoneNameFromBias(tzinfo_.Bias));
414 }
415 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
416 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
417 "%s Daylight Time",
418 GuessTimezoneNameFromBias(tzinfo_.Bias));
419 }
420
421 // Timezone information initialized.
422 tz_initialized_ = true;
423 }
424
425
426 // Return the difference in milliseconds between this and another timestamp.
Diff(Time * other)427 int64_t Time::Diff(Time* other) {
428 return (t() - other->t()) / kTimeScaler;
429 }
430
431
432 // Set timestamp to current time.
SetToCurrentTime()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;
454 static const int64_t kHundredNanosecondsPerSecond = 10000000;
455 static const int64_t kMaxClockElapsedTime =
456 60*kHundredNanosecondsPerSecond; // 1 minute
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.
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.
LocalOffset()490 int64_t Time::LocalOffset() {
491 // Initialize timezone information, if needed.
492 TzSet();
493
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().
500
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);
509
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);
516
517 return localtime.Diff(&rounded_to_second);
518 }
519
520
521 // Return whether or not daylight savings time is in effect at this time.
InDST()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
545 // Return the daylight savings time offset for this time.
DaylightSavingsOffset()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.
LocalTimezone()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
Setup()560 void OS::Setup() {
561 // Seed the random number generator.
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));
568 }
569
570
571 // Returns the accumulated user time for thread.
GetUserTime(uint32_t * secs,uint32_t * usecs)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.
TimeCurrentMillis()592 double OS::TimeCurrentMillis() {
593 Time t;
594 t.SetToCurrentTime();
595 return t.ToJSTime();
596 }
597
598 // Returns the tickcounter based on timeGetTime.
Ticks()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.
LocalTimezone(double time)606 const char* OS::LocalTimezone(double time) {
607 return Time(time).LocalTimezone();
608 }
609
610
611 // Returns the local time offset in milliseconds east of UTC without
612 // taking daylight savings time into account.
LocalTimeOffset()613 double OS::LocalTimeOffset() {
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());
618 }
619
620
621 // Returns the daylight savings offset in milliseconds for the given
622 // time.
DaylightSavingsOffset(double 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.
HasConsole()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
VPrintHelper(FILE * stream,const char * format,va_list args)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.
676 EmbeddedVector<char, 4096> buffer;
677 OS::VSNPrintF(buffer, format, args);
678 OutputDebugStringA(buffer.start());
679 }
680 }
681
682
FOpen(const char * path,const char * mode)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;
689 }
690 }
691
692
693 // Open log file in binary mode to avoid /n -> /r/n conversion.
694 const char* OS::LogFileOpenMode = "wb";
695
696
697 // Print (debug) message to console.
Print(const char * format,...)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
VPrint(const char * format,va_list args)706 void OS::VPrint(const char* format, va_list args) {
707 VPrintHelper(stdout, format, args);
708 }
709
710
711 // Print error message to console.
PrintError(const char * format,...)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
VPrintError(const char * format,va_list args)720 void OS::VPrintError(const char* format, va_list args) {
721 VPrintHelper(stderr, format, args);
722 }
723
724
SNPrintF(Vector<char> str,const char * format,...)725 int OS::SNPrintF(Vector<char> str, const char* format, ...) {
726 va_list args;
727 va_start(args, format);
728 int result = VSNPrintF(str, format, args);
729 va_end(args);
730 return result;
731 }
732
733
VSNPrintF(Vector<char> str,const char * format,va_list args)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);
736 // Make sure to zero-terminate the string if the output was
737 // truncated or if there was an error.
738 if (n < 0 || n >= str.length()) {
739 str[str.length() - 1] = '\0';
740 return -1;
741 } else {
742 return n;
743 }
744 }
745
746
StrChr(char * str,int c)747 char* OS::StrChr(char* str, int c) {
748 return const_cast<char*>(strchr(str, c));
749 }
750
751
StrNCpy(Vector<char> dest,const char * src,size_t n)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
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
UpdateAllocatedSpaceLimits(void * address,int size)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
IsOutsideAllocatedSpace(void * pointer)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
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.
GetPageSize()789 static size_t GetPageSize() {
790 static size_t page_size = 0;
791 if (page_size == 0) {
792 SYSTEM_INFO info;
793 GetSystemInfo(&info);
794 page_size = RoundUpToPowerOf2(info.dwPageSize);
795 }
796 return page_size;
797 }
798
799
800 // The allocation alignment is the guaranteed alignment for
801 // VirtualAlloc'ed blocks of memory.
AllocateAlignment()802 size_t OS::AllocateAlignment() {
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;
810 }
811
812
Allocate(const size_t requested,size_t * allocated,bool is_executable)813 void* OS::Allocate(const size_t requested,
814 size_t* allocated,
815 bool is_executable) {
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).
820 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
821 LPVOID mbase = VirtualAlloc(NULL, msize, MEM_COMMIT | MEM_RESERVE, prot);
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
Free(void * address,const size_t size)835 void OS::Free(void* address, const size_t size) {
836 // TODO(1240712): VirtualFree has a return value which is ignored here.
837 VirtualFree(address, 0, MEM_RELEASE);
838 USE(size);
839 }
840
841
842 #ifdef ENABLE_HEAP_PROTECTION
843
Protect(void * address,size_t size)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
Unprotect(void * address,size_t size,bool is_executable)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
Sleep(int milliseconds)861 void OS::Sleep(int milliseconds) {
862 ::Sleep(milliseconds);
863 }
864
865
Abort()866 void OS::Abort() {
867 if (!IsDebuggerPresent()) {
868 #ifdef _MSC_VER
869 // Make the MSVCRT do a silent abort.
870 _set_abort_behavior(0, _WRITE_ABORT_MSG);
871 _set_abort_behavior(0, _CALL_REPORTFAULT);
872 #endif // _MSC_VER
873 abort();
874 } else {
875 DebugBreak();
876 }
877 }
878
879
DebugBreak()880 void OS::DebugBreak() {
881 #ifdef _MSC_VER
882 __debugbreak();
883 #else
884 ::DebugBreak();
885 #endif
886 }
887
888
889 class Win32MemoryMappedFile : public OS::MemoryMappedFile {
890 public:
Win32MemoryMappedFile(HANDLE file,HANDLE file_mapping,void * memory)891 Win32MemoryMappedFile(HANDLE file, HANDLE file_mapping, void* memory)
892 : file_(file), file_mapping_(file_mapping), memory_(memory) { }
893 virtual ~Win32MemoryMappedFile();
memory()894 virtual void* memory() { return memory_; }
895 private:
896 HANDLE file_;
897 HANDLE file_mapping_;
898 void* memory_;
899 };
900
901
create(const char * name,int size,void * initial)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
~Win32MemoryMappedFile()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
928 // dynamically. This is to avoid being depending on dbghelp.dll and
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
968 // DbgHelp isn't supported on MinGW yet
969 #ifndef __MINGW32__
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)
TLHELP32_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;
1084 // NOTE: The modules are never unloaded and will stay around until the
1085 // application is closed.
1086 }
1087
1088
1089 // Load the symbols for generating stack traces.
LoadSymbols(HANDLE process_handle)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
LogSharedLibraryAddresses()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)
StackWalk(Vector<OS::StackFrame> frames)1171 int OS::StackWalk(Vector<OS::StackFrame> frames) {
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 #ifdef _WIN64
1190 // TODO(X64): Implement context capture.
1191 #else
1192 __asm call x
1193 __asm x: pop eax
1194 __asm mov context.Eip, eax
1195 __asm mov context.Ebp, ebp
1196 __asm mov context.Esp, esp
1197 // NOTE: At some point, we could use RtlCaptureContext(&context) to
1198 // capture the context instead of inline assembler. However it is
1199 // only available on XP, Vista, Server 2003 and Server 2008 which
1200 // might not be sufficient.
1201 #endif
1202
1203 // Initialize the stack walking
1204 STACKFRAME64 stack_frame;
1205 memset(&stack_frame, 0, sizeof(stack_frame));
1206 #ifdef _WIN64
1207 stack_frame.AddrPC.Offset = context.Rip;
1208 stack_frame.AddrFrame.Offset = context.Rbp;
1209 stack_frame.AddrStack.Offset = context.Rsp;
1210 #else
1211 stack_frame.AddrPC.Offset = context.Eip;
1212 stack_frame.AddrFrame.Offset = context.Ebp;
1213 stack_frame.AddrStack.Offset = context.Esp;
1214 #endif
1215 stack_frame.AddrPC.Mode = AddrModeFlat;
1216 stack_frame.AddrFrame.Mode = AddrModeFlat;
1217 stack_frame.AddrStack.Mode = AddrModeFlat;
1218 int frames_count = 0;
1219
1220 // Collect stack frames.
1221 int frames_size = frames.length();
1222 while (frames_count < frames_size) {
1223 ok = _StackWalk64(
1224 IMAGE_FILE_MACHINE_I386, // MachineType
1225 process_handle, // hProcess
1226 thread_handle, // hThread
1227 &stack_frame, // StackFrame
1228 &context, // ContextRecord
1229 NULL, // ReadMemoryRoutine
1230 _SymFunctionTableAccess64, // FunctionTableAccessRoutine
1231 _SymGetModuleBase64, // GetModuleBaseRoutine
1232 NULL); // TranslateAddress
1233 if (!ok) break;
1234
1235 // Store the address.
1236 ASSERT((stack_frame.AddrPC.Offset >> 32) == 0); // 32-bit address.
1237 frames[frames_count].address =
1238 reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
1239
1240 // Try to locate a symbol for this frame.
1241 DWORD64 symbol_displacement;
1242 IMAGEHLP_SYMBOL64* symbol = NULL;
1243 symbol = NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen);
1244 if (!symbol) return kStackWalkError; // Out of memory.
1245 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
1246 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
1247 symbol->MaxNameLength = kStackWalkMaxNameLen;
1248 ok = _SymGetSymFromAddr64(process_handle, // hProcess
1249 stack_frame.AddrPC.Offset, // Address
1250 &symbol_displacement, // Displacement
1251 symbol); // Symbol
1252 if (ok) {
1253 // Try to locate more source information for the symbol.
1254 IMAGEHLP_LINE64 Line;
1255 memset(&Line, 0, sizeof(Line));
1256 Line.SizeOfStruct = sizeof(Line);
1257 DWORD line_displacement;
1258 ok = _SymGetLineFromAddr64(
1259 process_handle, // hProcess
1260 stack_frame.AddrPC.Offset, // dwAddr
1261 &line_displacement, // pdwDisplacement
1262 &Line); // Line
1263 // Format a text representation of the frame based on the information
1264 // available.
1265 if (ok) {
1266 SNPrintF(MutableCStrVector(frames[frames_count].text,
1267 kStackWalkMaxTextLen),
1268 "%s %s:%d:%d",
1269 symbol->Name, Line.FileName, Line.LineNumber,
1270 line_displacement);
1271 } else {
1272 SNPrintF(MutableCStrVector(frames[frames_count].text,
1273 kStackWalkMaxTextLen),
1274 "%s",
1275 symbol->Name);
1276 }
1277 // Make sure line termination is in place.
1278 frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
1279 } else {
1280 // No text representation of this frame
1281 frames[frames_count].text[0] = '\0';
1282
1283 // Continue if we are just missing a module (for non C/C++ frames a
1284 // module will never be found).
1285 int err = GetLastError();
1286 if (err != ERROR_MOD_NOT_FOUND) {
1287 DeleteArray(symbol);
1288 break;
1289 }
1290 }
1291 DeleteArray(symbol);
1292
1293 frames_count++;
1294 }
1295
1296 // Return the number of frames filled in.
1297 return frames_count;
1298 }
1299
1300 // Restore warnings to previous settings.
1301 #pragma warning(pop)
1302
1303 #else // __MINGW32__
LogSharedLibraryAddresses()1304 void OS::LogSharedLibraryAddresses() { }
StackWalk(Vector<OS::StackFrame> frames)1305 int OS::StackWalk(Vector<OS::StackFrame> frames) { return 0; }
1306 #endif // __MINGW32__
1307
1308
nan_value()1309 double OS::nan_value() {
1310 #ifdef _MSC_VER
1311 static const __int64 nanval = 0xfff8000000000000;
1312 return *reinterpret_cast<const double*>(&nanval);
1313 #else // _MSC_VER
1314 return NAN;
1315 #endif // _MSC_VER
1316 }
1317
1318
ActivationFrameAlignment()1319 int OS::ActivationFrameAlignment() {
1320 #ifdef _WIN64
1321 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1322 #else
1323 return 8; // Floating-point math runs faster with 8-byte alignment.
1324 #endif
1325 }
1326
1327
IsReserved()1328 bool VirtualMemory::IsReserved() {
1329 return address_ != NULL;
1330 }
1331
1332
VirtualMemory(size_t size)1333 VirtualMemory::VirtualMemory(size_t size) {
1334 address_ = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
1335 size_ = size;
1336 }
1337
1338
~VirtualMemory()1339 VirtualMemory::~VirtualMemory() {
1340 if (IsReserved()) {
1341 if (0 == VirtualFree(address(), 0, MEM_RELEASE)) address_ = NULL;
1342 }
1343 }
1344
1345
Commit(void * address,size_t size,bool is_executable)1346 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1347 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1348 if (NULL == VirtualAlloc(address, size, MEM_COMMIT, prot)) {
1349 return false;
1350 }
1351
1352 UpdateAllocatedSpaceLimits(address, size);
1353 return true;
1354 }
1355
1356
Uncommit(void * address,size_t size)1357 bool VirtualMemory::Uncommit(void* address, size_t size) {
1358 ASSERT(IsReserved());
1359 return VirtualFree(address, size, MEM_DECOMMIT) != FALSE;
1360 }
1361
1362
1363 // ----------------------------------------------------------------------------
1364 // Win32 thread support.
1365
1366 // Definition of invalid thread handle and id.
1367 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
1368 static const DWORD kNoThreadId = 0;
1369
1370
1371 class ThreadHandle::PlatformData : public Malloced {
1372 public:
PlatformData(ThreadHandle::Kind kind)1373 explicit PlatformData(ThreadHandle::Kind kind) {
1374 Initialize(kind);
1375 }
1376
Initialize(ThreadHandle::Kind kind)1377 void Initialize(ThreadHandle::Kind kind) {
1378 switch (kind) {
1379 case ThreadHandle::SELF: tid_ = GetCurrentThreadId(); break;
1380 case ThreadHandle::INVALID: tid_ = kNoThreadId; break;
1381 }
1382 }
1383 DWORD tid_; // Win32 thread identifier.
1384 };
1385
1386
1387 // Entry point for threads. The supplied argument is a pointer to the thread
1388 // object. The entry function dispatches to the run method in the thread
1389 // object. It is important that this function has __stdcall calling
1390 // convention.
ThreadEntry(void * arg)1391 static unsigned int __stdcall ThreadEntry(void* arg) {
1392 Thread* thread = reinterpret_cast<Thread*>(arg);
1393 // This is also initialized by the last parameter to _beginthreadex() but we
1394 // don't know which thread will run first (the original thread or the new
1395 // one) so we initialize it here too.
1396 thread->thread_handle_data()->tid_ = GetCurrentThreadId();
1397 thread->Run();
1398 return 0;
1399 }
1400
1401
1402 // Initialize thread handle to invalid handle.
ThreadHandle(ThreadHandle::Kind kind)1403 ThreadHandle::ThreadHandle(ThreadHandle::Kind kind) {
1404 data_ = new PlatformData(kind);
1405 }
1406
1407
~ThreadHandle()1408 ThreadHandle::~ThreadHandle() {
1409 delete data_;
1410 }
1411
1412
1413 // The thread is running if it has the same id as the current thread.
IsSelf() const1414 bool ThreadHandle::IsSelf() const {
1415 return GetCurrentThreadId() == data_->tid_;
1416 }
1417
1418
1419 // Test for invalid thread handle.
IsValid() const1420 bool ThreadHandle::IsValid() const {
1421 return data_->tid_ != kNoThreadId;
1422 }
1423
1424
Initialize(ThreadHandle::Kind kind)1425 void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
1426 data_->Initialize(kind);
1427 }
1428
1429
1430 class Thread::PlatformData : public Malloced {
1431 public:
PlatformData(HANDLE thread)1432 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1433 HANDLE thread_;
1434 };
1435
1436
1437 // Initialize a Win32 thread object. The thread has an invalid thread
1438 // handle until it is started.
1439
Thread()1440 Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
1441 data_ = new PlatformData(kNoThread);
1442 }
1443
1444
1445 // Close our own handle for the thread.
~Thread()1446 Thread::~Thread() {
1447 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1448 delete data_;
1449 }
1450
1451
1452 // Create a new thread. It is important to use _beginthreadex() instead of
1453 // the Win32 function CreateThread(), because the CreateThread() does not
1454 // initialize thread specific structures in the C runtime library.
Start()1455 void Thread::Start() {
1456 data_->thread_ = reinterpret_cast<HANDLE>(
1457 _beginthreadex(NULL,
1458 0,
1459 ThreadEntry,
1460 this,
1461 0,
1462 reinterpret_cast<unsigned int*>(
1463 &thread_handle_data()->tid_)));
1464 ASSERT(IsValid());
1465 }
1466
1467
1468 // Wait for thread to terminate.
Join()1469 void Thread::Join() {
1470 WaitForSingleObject(data_->thread_, INFINITE);
1471 }
1472
1473
CreateThreadLocalKey()1474 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1475 DWORD result = TlsAlloc();
1476 ASSERT(result != TLS_OUT_OF_INDEXES);
1477 return static_cast<LocalStorageKey>(result);
1478 }
1479
1480
DeleteThreadLocalKey(LocalStorageKey key)1481 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1482 BOOL result = TlsFree(static_cast<DWORD>(key));
1483 USE(result);
1484 ASSERT(result);
1485 }
1486
1487
GetThreadLocal(LocalStorageKey key)1488 void* Thread::GetThreadLocal(LocalStorageKey key) {
1489 return TlsGetValue(static_cast<DWORD>(key));
1490 }
1491
1492
SetThreadLocal(LocalStorageKey key,void * value)1493 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1494 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1495 USE(result);
1496 ASSERT(result);
1497 }
1498
1499
1500
YieldCPU()1501 void Thread::YieldCPU() {
1502 Sleep(0);
1503 }
1504
1505
1506 // ----------------------------------------------------------------------------
1507 // Win32 mutex support.
1508 //
1509 // On Win32 mutexes are implemented using CRITICAL_SECTION objects. These are
1510 // faster than Win32 Mutex objects because they are implemented using user mode
1511 // atomic instructions. Therefore we only do ring transitions if there is lock
1512 // contention.
1513
1514 class Win32Mutex : public Mutex {
1515 public:
1516
Win32Mutex()1517 Win32Mutex() { InitializeCriticalSection(&cs_); }
1518
~Win32Mutex()1519 ~Win32Mutex() { DeleteCriticalSection(&cs_); }
1520
Lock()1521 int Lock() {
1522 EnterCriticalSection(&cs_);
1523 return 0;
1524 }
1525
Unlock()1526 int Unlock() {
1527 LeaveCriticalSection(&cs_);
1528 return 0;
1529 }
1530
1531 private:
1532 CRITICAL_SECTION cs_; // Critical section used for mutex
1533 };
1534
1535
CreateMutex()1536 Mutex* OS::CreateMutex() {
1537 return new Win32Mutex();
1538 }
1539
1540
1541 // ----------------------------------------------------------------------------
1542 // Win32 semaphore support.
1543 //
1544 // On Win32 semaphores are implemented using Win32 Semaphore objects. The
1545 // semaphores are anonymous. Also, the semaphores are initialized to have
1546 // no upper limit on count.
1547
1548
1549 class Win32Semaphore : public Semaphore {
1550 public:
Win32Semaphore(int count)1551 explicit Win32Semaphore(int count) {
1552 sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
1553 }
1554
~Win32Semaphore()1555 ~Win32Semaphore() {
1556 CloseHandle(sem);
1557 }
1558
Wait()1559 void Wait() {
1560 WaitForSingleObject(sem, INFINITE);
1561 }
1562
Wait(int timeout)1563 bool Wait(int timeout) {
1564 // Timeout in Windows API is in milliseconds.
1565 DWORD millis_timeout = timeout / 1000;
1566 return WaitForSingleObject(sem, millis_timeout) != WAIT_TIMEOUT;
1567 }
1568
Signal()1569 void Signal() {
1570 LONG dummy;
1571 ReleaseSemaphore(sem, 1, &dummy);
1572 }
1573
1574 private:
1575 HANDLE sem;
1576 };
1577
1578
CreateSemaphore(int count)1579 Semaphore* OS::CreateSemaphore(int count) {
1580 return new Win32Semaphore(count);
1581 }
1582
1583
1584 // ----------------------------------------------------------------------------
1585 // Win32 socket support.
1586 //
1587
1588 class Win32Socket : public Socket {
1589 public:
Win32Socket()1590 explicit Win32Socket() {
1591 // Create the socket.
1592 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1593 }
Win32Socket(SOCKET socket)1594 explicit Win32Socket(SOCKET socket): socket_(socket) { }
~Win32Socket()1595 virtual ~Win32Socket() { Shutdown(); }
1596
1597 // Server initialization.
1598 bool Bind(const int port);
1599 bool Listen(int backlog) const;
1600 Socket* Accept() const;
1601
1602 // Client initialization.
1603 bool Connect(const char* host, const char* port);
1604
1605 // Shutdown socket for both read and write.
1606 bool Shutdown();
1607
1608 // Data Transimission
1609 int Send(const char* data, int len) const;
1610 int Receive(char* data, int len) const;
1611
1612 bool SetReuseAddress(bool reuse_address);
1613
IsValid() const1614 bool IsValid() const { return socket_ != INVALID_SOCKET; }
1615
1616 private:
1617 SOCKET socket_;
1618 };
1619
1620
Bind(const int port)1621 bool Win32Socket::Bind(const int port) {
1622 if (!IsValid()) {
1623 return false;
1624 }
1625
1626 sockaddr_in addr;
1627 memset(&addr, 0, sizeof(addr));
1628 addr.sin_family = AF_INET;
1629 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1630 addr.sin_port = htons(port);
1631 int status = bind(socket_,
1632 reinterpret_cast<struct sockaddr *>(&addr),
1633 sizeof(addr));
1634 return status == 0;
1635 }
1636
1637
Listen(int backlog) const1638 bool Win32Socket::Listen(int backlog) const {
1639 if (!IsValid()) {
1640 return false;
1641 }
1642
1643 int status = listen(socket_, backlog);
1644 return status == 0;
1645 }
1646
1647
Accept() const1648 Socket* Win32Socket::Accept() const {
1649 if (!IsValid()) {
1650 return NULL;
1651 }
1652
1653 SOCKET socket = accept(socket_, NULL, NULL);
1654 if (socket == INVALID_SOCKET) {
1655 return NULL;
1656 } else {
1657 return new Win32Socket(socket);
1658 }
1659 }
1660
1661
Connect(const char * host,const char * port)1662 bool Win32Socket::Connect(const char* host, const char* port) {
1663 if (!IsValid()) {
1664 return false;
1665 }
1666
1667 // Lookup host and port.
1668 struct addrinfo *result = NULL;
1669 struct addrinfo hints;
1670 memset(&hints, 0, sizeof(addrinfo));
1671 hints.ai_family = AF_INET;
1672 hints.ai_socktype = SOCK_STREAM;
1673 hints.ai_protocol = IPPROTO_TCP;
1674 int status = getaddrinfo(host, port, &hints, &result);
1675 if (status != 0) {
1676 return false;
1677 }
1678
1679 // Connect.
1680 status = connect(socket_, result->ai_addr, result->ai_addrlen);
1681 freeaddrinfo(result);
1682 return status == 0;
1683 }
1684
1685
Shutdown()1686 bool Win32Socket::Shutdown() {
1687 if (IsValid()) {
1688 // Shutdown socket for both read and write.
1689 int status = shutdown(socket_, SD_BOTH);
1690 closesocket(socket_);
1691 socket_ = INVALID_SOCKET;
1692 return status == SOCKET_ERROR;
1693 }
1694 return true;
1695 }
1696
1697
Send(const char * data,int len) const1698 int Win32Socket::Send(const char* data, int len) const {
1699 int status = send(socket_, data, len, 0);
1700 return status;
1701 }
1702
1703
Receive(char * data,int len) const1704 int Win32Socket::Receive(char* data, int len) const {
1705 int status = recv(socket_, data, len, 0);
1706 return status;
1707 }
1708
1709
SetReuseAddress(bool reuse_address)1710 bool Win32Socket::SetReuseAddress(bool reuse_address) {
1711 BOOL on = reuse_address ? TRUE : FALSE;
1712 int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
1713 reinterpret_cast<char*>(&on), sizeof(on));
1714 return status == SOCKET_ERROR;
1715 }
1716
1717
Setup()1718 bool Socket::Setup() {
1719 // Initialize Winsock32
1720 int err;
1721 WSADATA winsock_data;
1722 WORD version_requested = MAKEWORD(1, 0);
1723 err = WSAStartup(version_requested, &winsock_data);
1724 if (err != 0) {
1725 PrintF("Unable to initialize Winsock, err = %d\n", Socket::LastError());
1726 }
1727
1728 return err == 0;
1729 }
1730
1731
LastError()1732 int Socket::LastError() {
1733 return WSAGetLastError();
1734 }
1735
1736
HToN(uint16_t value)1737 uint16_t Socket::HToN(uint16_t value) {
1738 return htons(value);
1739 }
1740
1741
NToH(uint16_t value)1742 uint16_t Socket::NToH(uint16_t value) {
1743 return ntohs(value);
1744 }
1745
1746
HToN(uint32_t value)1747 uint32_t Socket::HToN(uint32_t value) {
1748 return htonl(value);
1749 }
1750
1751
NToH(uint32_t value)1752 uint32_t Socket::NToH(uint32_t value) {
1753 return ntohl(value);
1754 }
1755
1756
CreateSocket()1757 Socket* OS::CreateSocket() {
1758 return new Win32Socket();
1759 }
1760
1761
1762 #ifdef ENABLE_LOGGING_AND_PROFILING
1763
1764 // ----------------------------------------------------------------------------
1765 // Win32 profiler support.
1766 //
1767 // On win32 we use a sampler thread with high priority to sample the program
1768 // counter for the profiled thread.
1769
1770 class Sampler::PlatformData : public Malloced {
1771 public:
PlatformData(Sampler * sampler)1772 explicit PlatformData(Sampler* sampler) {
1773 sampler_ = sampler;
1774 sampler_thread_ = INVALID_HANDLE_VALUE;
1775 profiled_thread_ = INVALID_HANDLE_VALUE;
1776 }
1777
1778 Sampler* sampler_;
1779 HANDLE sampler_thread_;
1780 HANDLE profiled_thread_;
1781
1782 // Sampler thread handler.
Runner()1783 void Runner() {
1784 // Context used for sampling the register state of the profiled thread.
1785 CONTEXT context;
1786 memset(&context, 0, sizeof(context));
1787 // Loop until the sampler is disengaged.
1788 while (sampler_->IsActive()) {
1789 TickSample sample;
1790
1791 // If profiling, we record the pc and sp of the profiled thread.
1792 if (sampler_->IsProfiling()
1793 && SuspendThread(profiled_thread_) != (DWORD)-1) {
1794 context.ContextFlags = CONTEXT_FULL;
1795 if (GetThreadContext(profiled_thread_, &context) != 0) {
1796 #if V8_HOST_ARCH_X64
1797 UNIMPLEMENTED();
1798 sample.pc = context.Rip;
1799 sample.sp = context.Rsp;
1800 sample.fp = context.Rbp;
1801 #else
1802 sample.pc = context.Eip;
1803 sample.sp = context.Esp;
1804 sample.fp = context.Ebp;
1805 #endif
1806 sampler_->SampleStack(&sample);
1807 }
1808 ResumeThread(profiled_thread_);
1809 }
1810
1811 // We always sample the VM state.
1812 sample.state = Logger::state();
1813 // Invoke tick handler with program counter and stack pointer.
1814 sampler_->Tick(&sample);
1815
1816 // Wait until next sampling.
1817 Sleep(sampler_->interval_);
1818 }
1819 }
1820 };
1821
1822
1823 // Entry point for sampler thread.
SamplerEntry(void * arg)1824 static unsigned int __stdcall SamplerEntry(void* arg) {
1825 Sampler::PlatformData* data =
1826 reinterpret_cast<Sampler::PlatformData*>(arg);
1827 data->Runner();
1828 return 0;
1829 }
1830
1831
1832 // Initialize a profile sampler.
Sampler(int interval,bool profiling)1833 Sampler::Sampler(int interval, bool profiling)
1834 : interval_(interval), profiling_(profiling), active_(false) {
1835 data_ = new PlatformData(this);
1836 }
1837
1838
~Sampler()1839 Sampler::~Sampler() {
1840 delete data_;
1841 }
1842
1843
1844 // Start profiling.
Start()1845 void Sampler::Start() {
1846 // If we are profiling, we need to be able to access the calling
1847 // thread.
1848 if (IsProfiling()) {
1849 // Get a handle to the calling thread. This is the thread that we are
1850 // going to profile. We need to make a copy of the handle because we are
1851 // going to use it in the sampler thread. Using GetThreadHandle() will
1852 // not work in this case. We're using OpenThread because DuplicateHandle
1853 // for some reason doesn't work in Chrome's sandbox.
1854 data_->profiled_thread_ = OpenThread(THREAD_GET_CONTEXT |
1855 THREAD_SUSPEND_RESUME |
1856 THREAD_QUERY_INFORMATION,
1857 FALSE,
1858 GetCurrentThreadId());
1859 BOOL ok = data_->profiled_thread_ != NULL;
1860 if (!ok) return;
1861 }
1862
1863 // Start sampler thread.
1864 unsigned int tid;
1865 active_ = true;
1866 data_->sampler_thread_ = reinterpret_cast<HANDLE>(
1867 _beginthreadex(NULL, 0, SamplerEntry, data_, 0, &tid));
1868 // Set thread to high priority to increase sampling accuracy.
1869 SetThreadPriority(data_->sampler_thread_, THREAD_PRIORITY_TIME_CRITICAL);
1870 }
1871
1872
1873 // Stop profiling.
Stop()1874 void Sampler::Stop() {
1875 // Seting active to false triggers termination of the sampler
1876 // thread.
1877 active_ = false;
1878
1879 // Wait for sampler thread to terminate.
1880 WaitForSingleObject(data_->sampler_thread_, INFINITE);
1881
1882 // Release the thread handles
1883 CloseHandle(data_->sampler_thread_);
1884 CloseHandle(data_->profiled_thread_);
1885 }
1886
1887
1888 #endif // ENABLE_LOGGING_AND_PROFILING
1889
1890 } } // namespace v8::internal
1891