Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / v8 / src / platform-win32.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Platform-specific code for Win32.
6
7 // Secure API functions are not available using MinGW with msvcrt.dll
8 // on Windows XP. Make sure MINGW_HAS_SECURE_API is not defined to
9 // disable definition of secure API functions in standard headers that
10 // would conflict with our own implementation.
11 #ifdef __MINGW32__
12 #include <_mingw.h>
13 #ifdef MINGW_HAS_SECURE_API
14 #undef MINGW_HAS_SECURE_API
15 #endif  // MINGW_HAS_SECURE_API
16 #endif  // __MINGW32__
17
18 #include "win32-headers.h"
19
20 #include "v8.h"
21
22 #include "codegen.h"
23 #include "isolate-inl.h"
24 #include "platform.h"
25
26 #ifdef _MSC_VER
27
28 // Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
29 // defined in strings.h.
30 int strncasecmp(const char* s1, const char* s2, int n) {
31   return _strnicmp(s1, s2, n);
32 }
33
34 #endif  // _MSC_VER
35
36
37 // Extra functions for MinGW. Most of these are the _s functions which are in
38 // the Microsoft Visual Studio C++ CRT.
39 #ifdef __MINGW32__
40
41
42 #ifndef __MINGW64_VERSION_MAJOR
43
44 #define _TRUNCATE 0
45 #define STRUNCATE 80
46
47 inline void MemoryBarrier() {
48   int barrier = 0;
49   __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
50 }
51
52 #endif  // __MINGW64_VERSION_MAJOR
53
54
55 int localtime_s(tm* out_tm, const time_t* time) {
56   tm* posix_local_time_struct = localtime(time);
57   if (posix_local_time_struct == NULL) return 1;
58   *out_tm = *posix_local_time_struct;
59   return 0;
60 }
61
62
63 int fopen_s(FILE** pFile, const char* filename, const char* mode) {
64   *pFile = fopen(filename, mode);
65   return *pFile != NULL ? 0 : 1;
66 }
67
68 int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
69                  const char* format, va_list argptr) {
70   ASSERT(count == _TRUNCATE);
71   return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
72 }
73
74
75 int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
76   CHECK(source != NULL);
77   CHECK(dest != NULL);
78   CHECK_GT(dest_size, 0);
79
80   if (count == _TRUNCATE) {
81     while (dest_size > 0 && *source != 0) {
82       *(dest++) = *(source++);
83       --dest_size;
84     }
85     if (dest_size == 0) {
86       *(dest - 1) = 0;
87       return STRUNCATE;
88     }
89   } else {
90     while (dest_size > 0 && count > 0 && *source != 0) {
91       *(dest++) = *(source++);
92       --dest_size;
93       --count;
94     }
95   }
96   CHECK_GT(dest_size, 0);
97   *dest = 0;
98   return 0;
99 }
100
101 #endif  // __MINGW32__
102
103 namespace v8 {
104 namespace internal {
105
106 intptr_t OS::MaxVirtualMemory() {
107   return 0;
108 }
109
110
111 #if V8_TARGET_ARCH_IA32
112 static void MemMoveWrapper(void* dest, const void* src, size_t size) {
113   memmove(dest, src, size);
114 }
115
116
117 // Initialize to library version so we can call this at any time during startup.
118 static OS::MemMoveFunction memmove_function = &MemMoveWrapper;
119
120 // Defined in codegen-ia32.cc.
121 OS::MemMoveFunction CreateMemMoveFunction();
122
123 // Copy memory area to disjoint memory area.
124 void OS::MemMove(void* dest, const void* src, size_t size) {
125   if (size == 0) return;
126   // Note: here we rely on dependent reads being ordered. This is true
127   // on all architectures we currently support.
128   (*memmove_function)(dest, src, size);
129 }
130
131 #endif  // V8_TARGET_ARCH_IA32
132
133 #ifdef _WIN64
134 typedef double (*ModuloFunction)(double, double);
135 static ModuloFunction modulo_function = NULL;
136 // Defined in codegen-x64.cc.
137 ModuloFunction CreateModuloFunction();
138
139 void init_modulo_function() {
140   modulo_function = CreateModuloFunction();
141 }
142
143
144 double modulo(double x, double y) {
145   // Note: here we rely on dependent reads being ordered. This is true
146   // on all architectures we currently support.
147   return (*modulo_function)(x, y);
148 }
149 #else  // Win32
150
151 double modulo(double x, double y) {
152   // Workaround MS fmod bugs. ECMA-262 says:
153   // dividend is finite and divisor is an infinity => result equals dividend
154   // dividend is a zero and divisor is nonzero finite => result equals dividend
155   if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) &&
156       !(x == 0 && (y != 0 && std::isfinite(y)))) {
157     x = fmod(x, y);
158   }
159   return x;
160 }
161
162 #endif  // _WIN64
163
164
165 #define UNARY_MATH_FUNCTION(name, generator)             \
166 static UnaryMathFunction fast_##name##_function = NULL;  \
167 void init_fast_##name##_function() {                     \
168   fast_##name##_function = generator;                    \
169 }                                                        \
170 double fast_##name(double x) {                           \
171   return (*fast_##name##_function)(x);                   \
172 }
173
174 UNARY_MATH_FUNCTION(exp, CreateExpFunction())
175 UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
176
177 #undef UNARY_MATH_FUNCTION
178
179
180 void lazily_initialize_fast_exp() {
181   if (fast_exp_function == NULL) {
182     init_fast_exp_function();
183   }
184 }
185
186
187 void MathSetup() {
188 #ifdef _WIN64
189   init_modulo_function();
190 #endif
191   // fast_exp is initialized lazily.
192   init_fast_sqrt_function();
193 }
194
195
196 class TimezoneCache {
197  public:
198   TimezoneCache() : initialized_(false) { }
199
200   void Clear() {
201     initialized_ = false;
202   }
203
204   // Initialize timezone information. The timezone information is obtained from
205   // windows. If we cannot get the timezone information we fall back to CET.
206   void InitializeIfNeeded() {
207     // Just return if timezone information has already been initialized.
208     if (initialized_) return;
209
210     // Initialize POSIX time zone data.
211     _tzset();
212     // Obtain timezone information from operating system.
213     memset(&tzinfo_, 0, sizeof(tzinfo_));
214     if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
215       // If we cannot get timezone information we fall back to CET.
216       tzinfo_.Bias = -60;
217       tzinfo_.StandardDate.wMonth = 10;
218       tzinfo_.StandardDate.wDay = 5;
219       tzinfo_.StandardDate.wHour = 3;
220       tzinfo_.StandardBias = 0;
221       tzinfo_.DaylightDate.wMonth = 3;
222       tzinfo_.DaylightDate.wDay = 5;
223       tzinfo_.DaylightDate.wHour = 2;
224       tzinfo_.DaylightBias = -60;
225     }
226
227     // Make standard and DST timezone names.
228     WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
229                         std_tz_name_, kTzNameSize, NULL, NULL);
230     std_tz_name_[kTzNameSize - 1] = '\0';
231     WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
232                         dst_tz_name_, kTzNameSize, NULL, NULL);
233     dst_tz_name_[kTzNameSize - 1] = '\0';
234
235     // If OS returned empty string or resource id (like "@tzres.dll,-211")
236     // simply guess the name from the UTC bias of the timezone.
237     // To properly resolve the resource identifier requires a library load,
238     // which is not possible in a sandbox.
239     if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
240       OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
241                    "%s Standard Time",
242                    GuessTimezoneNameFromBias(tzinfo_.Bias));
243     }
244     if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
245       OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
246                    "%s Daylight Time",
247                    GuessTimezoneNameFromBias(tzinfo_.Bias));
248     }
249     // Timezone information initialized.
250     initialized_ = true;
251   }
252
253   // Guess the name of the timezone from the bias.
254   // The guess is very biased towards the northern hemisphere.
255   const char* GuessTimezoneNameFromBias(int bias) {
256     static const int kHour = 60;
257     switch (-bias) {
258       case -9*kHour: return "Alaska";
259       case -8*kHour: return "Pacific";
260       case -7*kHour: return "Mountain";
261       case -6*kHour: return "Central";
262       case -5*kHour: return "Eastern";
263       case -4*kHour: return "Atlantic";
264       case  0*kHour: return "GMT";
265       case +1*kHour: return "Central Europe";
266       case +2*kHour: return "Eastern Europe";
267       case +3*kHour: return "Russia";
268       case +5*kHour + 30: return "India";
269       case +8*kHour: return "China";
270       case +9*kHour: return "Japan";
271       case +12*kHour: return "New Zealand";
272       default: return "Local";
273     }
274   }
275
276
277  private:
278   static const int kTzNameSize = 128;
279   bool initialized_;
280   char std_tz_name_[kTzNameSize];
281   char dst_tz_name_[kTzNameSize];
282   TIME_ZONE_INFORMATION tzinfo_;
283   friend class Win32Time;
284 };
285
286
287 // ----------------------------------------------------------------------------
288 // The Time class represents time on win32. A timestamp is represented as
289 // a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
290 // timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
291 // January 1, 1970.
292
293 class Win32Time {
294  public:
295   // Constructors.
296   Win32Time();
297   explicit Win32Time(double jstime);
298   Win32Time(int year, int mon, int day, int hour, int min, int sec);
299
300   // Convert timestamp to JavaScript representation.
301   double ToJSTime();
302
303   // Set timestamp to current time.
304   void SetToCurrentTime();
305
306   // Returns the local timezone offset in milliseconds east of UTC. This is
307   // the number of milliseconds you must add to UTC to get local time, i.e.
308   // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
309   // routine also takes into account whether daylight saving is effect
310   // at the time.
311   int64_t LocalOffset(TimezoneCache* cache);
312
313   // Returns the daylight savings time offset for the time in milliseconds.
314   int64_t DaylightSavingsOffset(TimezoneCache* cache);
315
316   // Returns a string identifying the current timezone for the
317   // timestamp taking into account daylight saving.
318   char* LocalTimezone(TimezoneCache* cache);
319
320  private:
321   // Constants for time conversion.
322   static const int64_t kTimeEpoc = 116444736000000000LL;
323   static const int64_t kTimeScaler = 10000;
324   static const int64_t kMsPerMinute = 60000;
325
326   // Constants for timezone information.
327   static const bool kShortTzNames = false;
328
329   // Return whether or not daylight savings time is in effect at this time.
330   bool InDST(TimezoneCache* cache);
331
332   // Accessor for FILETIME representation.
333   FILETIME& ft() { return time_.ft_; }
334
335   // Accessor for integer representation.
336   int64_t& t() { return time_.t_; }
337
338   // Although win32 uses 64-bit integers for representing timestamps,
339   // these are packed into a FILETIME structure. The FILETIME structure
340   // is just a struct representing a 64-bit integer. The TimeStamp union
341   // allows access to both a FILETIME and an integer representation of
342   // the timestamp.
343   union TimeStamp {
344     FILETIME ft_;
345     int64_t t_;
346   };
347
348   TimeStamp time_;
349 };
350
351
352 // Initialize timestamp to start of epoc.
353 Win32Time::Win32Time() {
354   t() = 0;
355 }
356
357
358 // Initialize timestamp from a JavaScript timestamp.
359 Win32Time::Win32Time(double jstime) {
360   t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
361 }
362
363
364 // Initialize timestamp from date/time components.
365 Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
366   SYSTEMTIME st;
367   st.wYear = year;
368   st.wMonth = mon;
369   st.wDay = day;
370   st.wHour = hour;
371   st.wMinute = min;
372   st.wSecond = sec;
373   st.wMilliseconds = 0;
374   SystemTimeToFileTime(&st, &ft());
375 }
376
377
378 // Convert timestamp to JavaScript timestamp.
379 double Win32Time::ToJSTime() {
380   return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
381 }
382
383
384 // Set timestamp to current time.
385 void Win32Time::SetToCurrentTime() {
386   // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
387   // Because we're fast, we like fast timers which have at least a
388   // 1ms resolution.
389   //
390   // timeGetTime() provides 1ms granularity when combined with
391   // timeBeginPeriod().  If the host application for v8 wants fast
392   // timers, it can use timeBeginPeriod to increase the resolution.
393   //
394   // Using timeGetTime() has a drawback because it is a 32bit value
395   // and hence rolls-over every ~49days.
396   //
397   // To use the clock, we use GetSystemTimeAsFileTime as our base;
398   // and then use timeGetTime to extrapolate current time from the
399   // start time.  To deal with rollovers, we resync the clock
400   // any time when more than kMaxClockElapsedTime has passed or
401   // whenever timeGetTime creates a rollover.
402
403   static bool initialized = false;
404   static TimeStamp init_time;
405   static DWORD init_ticks;
406   static const int64_t kHundredNanosecondsPerSecond = 10000000;
407   static const int64_t kMaxClockElapsedTime =
408       60*kHundredNanosecondsPerSecond;  // 1 minute
409
410   // If we are uninitialized, we need to resync the clock.
411   bool needs_resync = !initialized;
412
413   // Get the current time.
414   TimeStamp time_now;
415   GetSystemTimeAsFileTime(&time_now.ft_);
416   DWORD ticks_now = timeGetTime();
417
418   // Check if we need to resync due to clock rollover.
419   needs_resync |= ticks_now < init_ticks;
420
421   // Check if we need to resync due to elapsed time.
422   needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
423
424   // Check if we need to resync due to backwards time change.
425   needs_resync |= time_now.t_ < init_time.t_;
426
427   // Resync the clock if necessary.
428   if (needs_resync) {
429     GetSystemTimeAsFileTime(&init_time.ft_);
430     init_ticks = ticks_now = timeGetTime();
431     initialized = true;
432   }
433
434   // Finally, compute the actual time.  Why is this so hard.
435   DWORD elapsed = ticks_now - init_ticks;
436   this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
437 }
438
439
440 // Return the local timezone offset in milliseconds east of UTC. This
441 // takes into account whether daylight saving is in effect at the time.
442 // Only times in the 32-bit Unix range may be passed to this function.
443 // Also, adding the time-zone offset to the input must not overflow.
444 // The function EquivalentTime() in date.js guarantees this.
445 int64_t Win32Time::LocalOffset(TimezoneCache* cache) {
446   cache->InitializeIfNeeded();
447
448   Win32Time rounded_to_second(*this);
449   rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
450       1000 * kTimeScaler;
451   // Convert to local time using POSIX localtime function.
452   // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
453   // very slow.  Other browsers use localtime().
454
455   // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
456   // POSIX seconds past 1/1/1970 0:00:00.
457   double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
458   if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
459     return 0;
460   }
461   // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
462   time_t posix_time = static_cast<time_t>(unchecked_posix_time);
463
464   // Convert to local time, as struct with fields for day, hour, year, etc.
465   tm posix_local_time_struct;
466   if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
467
468   if (posix_local_time_struct.tm_isdst > 0) {
469     return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
470   } else if (posix_local_time_struct.tm_isdst == 0) {
471     return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
472   } else {
473     return cache->tzinfo_.Bias * -kMsPerMinute;
474   }
475 }
476
477
478 // Return whether or not daylight savings time is in effect at this time.
479 bool Win32Time::InDST(TimezoneCache* cache) {
480   cache->InitializeIfNeeded();
481
482   // Determine if DST is in effect at the specified time.
483   bool in_dst = false;
484   if (cache->tzinfo_.StandardDate.wMonth != 0 ||
485       cache->tzinfo_.DaylightDate.wMonth != 0) {
486     // Get the local timezone offset for the timestamp in milliseconds.
487     int64_t offset = LocalOffset(cache);
488
489     // Compute the offset for DST. The bias parameters in the timezone info
490     // are specified in minutes. These must be converted to milliseconds.
491     int64_t dstofs =
492         -(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
493
494     // If the local time offset equals the timezone bias plus the daylight
495     // bias then DST is in effect.
496     in_dst = offset == dstofs;
497   }
498
499   return in_dst;
500 }
501
502
503 // Return the daylight savings time offset for this time.
504 int64_t Win32Time::DaylightSavingsOffset(TimezoneCache* cache) {
505   return InDST(cache) ? 60 * kMsPerMinute : 0;
506 }
507
508
509 // Returns a string identifying the current timezone for the
510 // timestamp taking into account daylight saving.
511 char* Win32Time::LocalTimezone(TimezoneCache* cache) {
512   // Return the standard or DST time zone name based on whether daylight
513   // saving is in effect at the given time.
514   return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
515 }
516
517
518 void OS::PostSetUp() {
519   // Math functions depend on CPU features therefore they are initialized after
520   // CPU.
521   MathSetup();
522 #if V8_TARGET_ARCH_IA32
523   OS::MemMoveFunction generated_memmove = CreateMemMoveFunction();
524   if (generated_memmove != NULL) {
525     memmove_function = generated_memmove;
526   }
527 #endif
528 }
529
530
531 // Returns the accumulated user time for thread.
532 int OS::GetUserTime(uint32_t* secs,  uint32_t* usecs) {
533   FILETIME dummy;
534   uint64_t usertime;
535
536   // Get the amount of time that the thread has executed in user mode.
537   if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
538                       reinterpret_cast<FILETIME*>(&usertime))) return -1;
539
540   // Adjust the resolution to micro-seconds.
541   usertime /= 10;
542
543   // Convert to seconds and microseconds
544   *secs = static_cast<uint32_t>(usertime / 1000000);
545   *usecs = static_cast<uint32_t>(usertime % 1000000);
546   return 0;
547 }
548
549
550 // Returns current time as the number of milliseconds since
551 // 00:00:00 UTC, January 1, 1970.
552 double OS::TimeCurrentMillis() {
553   return Time::Now().ToJsTime();
554 }
555
556
557 TimezoneCache* OS::CreateTimezoneCache() {
558   return new TimezoneCache();
559 }
560
561
562 void OS::DisposeTimezoneCache(TimezoneCache* cache) {
563   delete cache;
564 }
565
566
567 void OS::ClearTimezoneCache(TimezoneCache* cache) {
568   cache->Clear();
569 }
570
571
572 // Returns a string identifying the current timezone taking into
573 // account daylight saving.
574 const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
575   return Win32Time(time).LocalTimezone(cache);
576 }
577
578
579 // Returns the local time offset in milliseconds east of UTC without
580 // taking daylight savings time into account.
581 double OS::LocalTimeOffset(TimezoneCache* cache) {
582   // Use current time, rounded to the millisecond.
583   Win32Time t(TimeCurrentMillis());
584   // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
585   return static_cast<double>(t.LocalOffset(cache) -
586                              t.DaylightSavingsOffset(cache));
587 }
588
589
590 // Returns the daylight savings offset in milliseconds for the given
591 // time.
592 double OS::DaylightSavingsOffset(double time, TimezoneCache* cache) {
593   int64_t offset = Win32Time(time).DaylightSavingsOffset(cache);
594   return static_cast<double>(offset);
595 }
596
597
598 int OS::GetLastError() {
599   return ::GetLastError();
600 }
601
602
603 int OS::GetCurrentProcessId() {
604   return static_cast<int>(::GetCurrentProcessId());
605 }
606
607
608 // ----------------------------------------------------------------------------
609 // Win32 console output.
610 //
611 // If a Win32 application is linked as a console application it has a normal
612 // standard output and standard error. In this case normal printf works fine
613 // for output. However, if the application is linked as a GUI application,
614 // the process doesn't have a console, and therefore (debugging) output is lost.
615 // This is the case if we are embedded in a windows program (like a browser).
616 // In order to be able to get debug output in this case the the debugging
617 // facility using OutputDebugString. This output goes to the active debugger
618 // for the process (if any). Else the output can be monitored using DBMON.EXE.
619
620 enum OutputMode {
621   UNKNOWN,  // Output method has not yet been determined.
622   CONSOLE,  // Output is written to stdout.
623   ODS       // Output is written to debug facility.
624 };
625
626 static OutputMode output_mode = UNKNOWN;  // Current output mode.
627
628
629 // Determine if the process has a console for output.
630 static bool HasConsole() {
631   // Only check the first time. Eventual race conditions are not a problem,
632   // because all threads will eventually determine the same mode.
633   if (output_mode == UNKNOWN) {
634     // We cannot just check that the standard output is attached to a console
635     // because this would fail if output is redirected to a file. Therefore we
636     // say that a process does not have an output console if either the
637     // standard output handle is invalid or its file type is unknown.
638     if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
639         GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
640       output_mode = CONSOLE;
641     else
642       output_mode = ODS;
643   }
644   return output_mode == CONSOLE;
645 }
646
647
648 static void VPrintHelper(FILE* stream, const char* format, va_list args) {
649   if ((stream == stdout || stream == stderr) && !HasConsole()) {
650     // It is important to use safe print here in order to avoid
651     // overflowing the buffer. We might truncate the output, but this
652     // does not crash.
653     EmbeddedVector<char, 4096> buffer;
654     OS::VSNPrintF(buffer, format, args);
655     OutputDebugStringA(buffer.start());
656   } else {
657     vfprintf(stream, format, args);
658   }
659 }
660
661
662 FILE* OS::FOpen(const char* path, const char* mode) {
663   FILE* result;
664   if (fopen_s(&result, path, mode) == 0) {
665     return result;
666   } else {
667     return NULL;
668   }
669 }
670
671
672 bool OS::Remove(const char* path) {
673   return (DeleteFileA(path) != 0);
674 }
675
676
677 FILE* OS::OpenTemporaryFile() {
678   // tmpfile_s tries to use the root dir, don't use it.
679   char tempPathBuffer[MAX_PATH];
680   DWORD path_result = 0;
681   path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
682   if (path_result > MAX_PATH || path_result == 0) return NULL;
683   UINT name_result = 0;
684   char tempNameBuffer[MAX_PATH];
685   name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
686   if (name_result == 0) return NULL;
687   FILE* result = FOpen(tempNameBuffer, "w+");  // Same mode as tmpfile uses.
688   if (result != NULL) {
689     Remove(tempNameBuffer);  // Delete on close.
690   }
691   return result;
692 }
693
694
695 // Open log file in binary mode to avoid /n -> /r/n conversion.
696 const char* const OS::LogFileOpenMode = "wb";
697
698
699 // Print (debug) message to console.
700 void OS::Print(const char* format, ...) {
701   va_list args;
702   va_start(args, format);
703   VPrint(format, args);
704   va_end(args);
705 }
706
707
708 void OS::VPrint(const char* format, va_list args) {
709   VPrintHelper(stdout, format, args);
710 }
711
712
713 void OS::FPrint(FILE* out, const char* format, ...) {
714   va_list args;
715   va_start(args, format);
716   VFPrint(out, format, args);
717   va_end(args);
718 }
719
720
721 void OS::VFPrint(FILE* out, const char* format, va_list args) {
722   VPrintHelper(out, format, args);
723 }
724
725
726 // Print error message to console.
727 void OS::PrintError(const char* format, ...) {
728   va_list args;
729   va_start(args, format);
730   VPrintError(format, args);
731   va_end(args);
732 }
733
734
735 void OS::VPrintError(const char* format, va_list args) {
736   VPrintHelper(stderr, format, args);
737 }
738
739
740 int OS::SNPrintF(Vector<char> str, const char* format, ...) {
741   va_list args;
742   va_start(args, format);
743   int result = VSNPrintF(str, format, args);
744   va_end(args);
745   return result;
746 }
747
748
749 int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
750   int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
751   // Make sure to zero-terminate the string if the output was
752   // truncated or if there was an error.
753   if (n < 0 || n >= str.length()) {
754     if (str.length() > 0)
755       str[str.length() - 1] = '\0';
756     return -1;
757   } else {
758     return n;
759   }
760 }
761
762
763 char* OS::StrChr(char* str, int c) {
764   return const_cast<char*>(strchr(str, c));
765 }
766
767
768 void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
769   // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
770   size_t buffer_size = static_cast<size_t>(dest.length());
771   if (n + 1 > buffer_size)  // count for trailing '\0'
772     n = _TRUNCATE;
773   int result = strncpy_s(dest.start(), dest.length(), src, n);
774   USE(result);
775   ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
776 }
777
778
779 #undef _TRUNCATE
780 #undef STRUNCATE
781
782
783 // Get the system's page size used by VirtualAlloc() or the next power
784 // of two. The reason for always returning a power of two is that the
785 // rounding up in OS::Allocate expects that.
786 static size_t GetPageSize() {
787   static size_t page_size = 0;
788   if (page_size == 0) {
789     SYSTEM_INFO info;
790     GetSystemInfo(&info);
791     page_size = RoundUpToPowerOf2(info.dwPageSize);
792   }
793   return page_size;
794 }
795
796
797 // The allocation alignment is the guaranteed alignment for
798 // VirtualAlloc'ed blocks of memory.
799 size_t OS::AllocateAlignment() {
800   static size_t allocate_alignment = 0;
801   if (allocate_alignment == 0) {
802     SYSTEM_INFO info;
803     GetSystemInfo(&info);
804     allocate_alignment = info.dwAllocationGranularity;
805   }
806   return allocate_alignment;
807 }
808
809
810 void* OS::GetRandomMmapAddr() {
811   Isolate* isolate = Isolate::UncheckedCurrent();
812   // Note that the current isolate isn't set up in a call path via
813   // CpuFeatures::Probe. We don't care about randomization in this case because
814   // the code page is immediately freed.
815   if (isolate != NULL) {
816     // The address range used to randomize RWX allocations in OS::Allocate
817     // Try not to map pages into the default range that windows loads DLLs
818     // Use a multiple of 64k to prevent committing unused memory.
819     // Note: This does not guarantee RWX regions will be within the
820     // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
821 #ifdef V8_HOST_ARCH_64_BIT
822     static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
823     static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
824 #else
825     static const intptr_t kAllocationRandomAddressMin = 0x04000000;
826     static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
827 #endif
828     uintptr_t address =
829         (isolate->random_number_generator()->NextInt() << kPageSizeBits) |
830         kAllocationRandomAddressMin;
831     address &= kAllocationRandomAddressMax;
832     return reinterpret_cast<void *>(address);
833   }
834   return NULL;
835 }
836
837
838 static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
839   LPVOID base = NULL;
840
841   if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
842     // For exectutable pages try and randomize the allocation address
843     for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
844       base = VirtualAlloc(OS::GetRandomMmapAddr(), size, action, protection);
845     }
846   }
847
848   // After three attempts give up and let the OS find an address to use.
849   if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
850
851   return base;
852 }
853
854
855 void* OS::Allocate(const size_t requested,
856                    size_t* allocated,
857                    bool is_executable) {
858   // VirtualAlloc rounds allocated size to page size automatically.
859   size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
860
861   // Windows XP SP2 allows Data Excution Prevention (DEP).
862   int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
863
864   LPVOID mbase = RandomizedVirtualAlloc(msize,
865                                         MEM_COMMIT | MEM_RESERVE,
866                                         prot);
867
868   if (mbase == NULL) {
869     LOG(Isolate::Current(), StringEvent("OS::Allocate", "VirtualAlloc failed"));
870     return NULL;
871   }
872
873   ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
874
875   *allocated = msize;
876   return mbase;
877 }
878
879
880 void OS::Free(void* address, const size_t size) {
881   // TODO(1240712): VirtualFree has a return value which is ignored here.
882   VirtualFree(address, 0, MEM_RELEASE);
883   USE(size);
884 }
885
886
887 intptr_t OS::CommitPageSize() {
888   return 4096;
889 }
890
891
892 void OS::ProtectCode(void* address, const size_t size) {
893   DWORD old_protect;
894   VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
895 }
896
897
898 void OS::Guard(void* address, const size_t size) {
899   DWORD oldprotect;
900   VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect);
901 }
902
903
904 void OS::Sleep(int milliseconds) {
905   ::Sleep(milliseconds);
906 }
907
908
909 void OS::Abort() {
910   if (FLAG_hard_abort) {
911     V8_IMMEDIATE_CRASH();
912   }
913   // Make the MSVCRT do a silent abort.
914   raise(SIGABRT);
915 }
916
917
918 void OS::DebugBreak() {
919 #ifdef _MSC_VER
920   // To avoid Visual Studio runtime support the following code can be used
921   // instead
922   // __asm { int 3 }
923   __debugbreak();
924 #else
925   ::DebugBreak();
926 #endif
927 }
928
929
930 class Win32MemoryMappedFile : public OS::MemoryMappedFile {
931  public:
932   Win32MemoryMappedFile(HANDLE file,
933                         HANDLE file_mapping,
934                         void* memory,
935                         int size)
936       : file_(file),
937         file_mapping_(file_mapping),
938         memory_(memory),
939         size_(size) { }
940   virtual ~Win32MemoryMappedFile();
941   virtual void* memory() { return memory_; }
942   virtual int size() { return size_; }
943  private:
944   HANDLE file_;
945   HANDLE file_mapping_;
946   void* memory_;
947   int size_;
948 };
949
950
951 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
952   // Open a physical file
953   HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
954       FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
955   if (file == INVALID_HANDLE_VALUE) return NULL;
956
957   int size = static_cast<int>(GetFileSize(file, NULL));
958
959   // Create a file mapping for the physical file
960   HANDLE file_mapping = CreateFileMapping(file, NULL,
961       PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
962   if (file_mapping == NULL) return NULL;
963
964   // Map a view of the file into memory
965   void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
966   return new Win32MemoryMappedFile(file, file_mapping, memory, size);
967 }
968
969
970 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
971     void* initial) {
972   // Open a physical file
973   HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
974       FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
975   if (file == NULL) return NULL;
976   // Create a file mapping for the physical file
977   HANDLE file_mapping = CreateFileMapping(file, NULL,
978       PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
979   if (file_mapping == NULL) return NULL;
980   // Map a view of the file into memory
981   void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
982   if (memory) OS::MemMove(memory, initial, size);
983   return new Win32MemoryMappedFile(file, file_mapping, memory, size);
984 }
985
986
987 Win32MemoryMappedFile::~Win32MemoryMappedFile() {
988   if (memory_ != NULL)
989     UnmapViewOfFile(memory_);
990   CloseHandle(file_mapping_);
991   CloseHandle(file_);
992 }
993
994
995 // The following code loads functions defined in DbhHelp.h and TlHelp32.h
996 // dynamically. This is to avoid being depending on dbghelp.dll and
997 // tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
998 // kernel32.dll at some point so loading functions defines in TlHelp32.h
999 // dynamically might not be necessary any more - for some versions of Windows?).
1000
1001 // Function pointers to functions dynamically loaded from dbghelp.dll.
1002 #define DBGHELP_FUNCTION_LIST(V)  \
1003   V(SymInitialize)                \
1004   V(SymGetOptions)                \
1005   V(SymSetOptions)                \
1006   V(SymGetSearchPath)             \
1007   V(SymLoadModule64)              \
1008   V(StackWalk64)                  \
1009   V(SymGetSymFromAddr64)          \
1010   V(SymGetLineFromAddr64)         \
1011   V(SymFunctionTableAccess64)     \
1012   V(SymGetModuleBase64)
1013
1014 // Function pointers to functions dynamically loaded from dbghelp.dll.
1015 #define TLHELP32_FUNCTION_LIST(V)  \
1016   V(CreateToolhelp32Snapshot)      \
1017   V(Module32FirstW)                \
1018   V(Module32NextW)
1019
1020 // Define the decoration to use for the type and variable name used for
1021 // dynamically loaded DLL function..
1022 #define DLL_FUNC_TYPE(name) _##name##_
1023 #define DLL_FUNC_VAR(name) _##name
1024
1025 // Define the type for each dynamically loaded DLL function. The function
1026 // definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1027 // from the Windows include files are redefined here to have the function
1028 // definitions to be as close to the ones in the original .h files as possible.
1029 #ifndef IN
1030 #define IN
1031 #endif
1032 #ifndef VOID
1033 #define VOID void
1034 #endif
1035
1036 // DbgHelp isn't supported on MinGW yet
1037 #ifndef __MINGW32__
1038 // DbgHelp.h functions.
1039 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
1040                                                        IN PSTR UserSearchPath,
1041                                                        IN BOOL fInvadeProcess);
1042 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
1043 typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
1044 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
1045     IN HANDLE hProcess,
1046     OUT PSTR SearchPath,
1047     IN DWORD SearchPathLength);
1048 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
1049     IN HANDLE hProcess,
1050     IN HANDLE hFile,
1051     IN PSTR ImageName,
1052     IN PSTR ModuleName,
1053     IN DWORD64 BaseOfDll,
1054     IN DWORD SizeOfDll);
1055 typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
1056     DWORD MachineType,
1057     HANDLE hProcess,
1058     HANDLE hThread,
1059     LPSTACKFRAME64 StackFrame,
1060     PVOID ContextRecord,
1061     PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1062     PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1063     PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1064     PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1065 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
1066     IN HANDLE hProcess,
1067     IN DWORD64 qwAddr,
1068     OUT PDWORD64 pdwDisplacement,
1069     OUT PIMAGEHLP_SYMBOL64 Symbol);
1070 typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
1071     IN HANDLE hProcess,
1072     IN DWORD64 qwAddr,
1073     OUT PDWORD pdwDisplacement,
1074     OUT PIMAGEHLP_LINE64 Line64);
1075 // DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1076 typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
1077     HANDLE hProcess,
1078     DWORD64 AddrBase);  // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1079 typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1080     HANDLE hProcess,
1081     DWORD64 AddrBase);  // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1082
1083 // TlHelp32.h functions.
1084 typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1085     DWORD dwFlags,
1086     DWORD th32ProcessID);
1087 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1088                                                         LPMODULEENTRY32W lpme);
1089 typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1090                                                        LPMODULEENTRY32W lpme);
1091
1092 #undef IN
1093 #undef VOID
1094
1095 // Declare a variable for each dynamically loaded DLL function.
1096 #define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1097 DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1098 TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1099 #undef DEF_DLL_FUNCTION
1100
1101 // Load the functions. This function has a lot of "ugly" macros in order to
1102 // keep down code duplication.
1103
1104 static bool LoadDbgHelpAndTlHelp32() {
1105   static bool dbghelp_loaded = false;
1106
1107   if (dbghelp_loaded) return true;
1108
1109   HMODULE module;
1110
1111   // Load functions from the dbghelp.dll module.
1112   module = LoadLibrary(TEXT("dbghelp.dll"));
1113   if (module == NULL) {
1114     return false;
1115   }
1116
1117 #define LOAD_DLL_FUNC(name)                                                 \
1118   DLL_FUNC_VAR(name) =                                                      \
1119       reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1120
1121 DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1122
1123 #undef LOAD_DLL_FUNC
1124
1125   // Load functions from the kernel32.dll module (the TlHelp32.h function used
1126   // to be in tlhelp32.dll but are now moved to kernel32.dll).
1127   module = LoadLibrary(TEXT("kernel32.dll"));
1128   if (module == NULL) {
1129     return false;
1130   }
1131
1132 #define LOAD_DLL_FUNC(name)                                                 \
1133   DLL_FUNC_VAR(name) =                                                      \
1134       reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1135
1136 TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1137
1138 #undef LOAD_DLL_FUNC
1139
1140   // Check that all functions where loaded.
1141   bool result =
1142 #define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1143
1144 DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1145 TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1146
1147 #undef DLL_FUNC_LOADED
1148   true;
1149
1150   dbghelp_loaded = result;
1151   return result;
1152   // NOTE: The modules are never unloaded and will stay around until the
1153   // application is closed.
1154 }
1155
1156 #undef DBGHELP_FUNCTION_LIST
1157 #undef TLHELP32_FUNCTION_LIST
1158 #undef DLL_FUNC_VAR
1159 #undef DLL_FUNC_TYPE
1160
1161
1162 // Load the symbols for generating stack traces.
1163 static bool LoadSymbols(Isolate* isolate, HANDLE process_handle) {
1164   static bool symbols_loaded = false;
1165
1166   if (symbols_loaded) return true;
1167
1168   BOOL ok;
1169
1170   // Initialize the symbol engine.
1171   ok = _SymInitialize(process_handle,  // hProcess
1172                       NULL,            // UserSearchPath
1173                       false);          // fInvadeProcess
1174   if (!ok) return false;
1175
1176   DWORD options = _SymGetOptions();
1177   options |= SYMOPT_LOAD_LINES;
1178   options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1179   options = _SymSetOptions(options);
1180
1181   char buf[OS::kStackWalkMaxNameLen] = {0};
1182   ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1183   if (!ok) {
1184     int err = GetLastError();
1185     PrintF("%d\n", err);
1186     return false;
1187   }
1188
1189   HANDLE snapshot = _CreateToolhelp32Snapshot(
1190       TH32CS_SNAPMODULE,       // dwFlags
1191       GetCurrentProcessId());  // th32ProcessId
1192   if (snapshot == INVALID_HANDLE_VALUE) return false;
1193   MODULEENTRY32W module_entry;
1194   module_entry.dwSize = sizeof(module_entry);  // Set the size of the structure.
1195   BOOL cont = _Module32FirstW(snapshot, &module_entry);
1196   while (cont) {
1197     DWORD64 base;
1198     // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1199     // both unicode and ASCII strings even though the parameter is PSTR.
1200     base = _SymLoadModule64(
1201         process_handle,                                       // hProcess
1202         0,                                                    // hFile
1203         reinterpret_cast<PSTR>(module_entry.szExePath),       // ImageName
1204         reinterpret_cast<PSTR>(module_entry.szModule),        // ModuleName
1205         reinterpret_cast<DWORD64>(module_entry.modBaseAddr),  // BaseOfDll
1206         module_entry.modBaseSize);                            // SizeOfDll
1207     if (base == 0) {
1208       int err = GetLastError();
1209       if (err != ERROR_MOD_NOT_FOUND &&
1210           err != ERROR_INVALID_HANDLE) return false;
1211     }
1212     LOG(isolate,
1213         SharedLibraryEvent(
1214             module_entry.szExePath,
1215             reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1216             reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1217                                            module_entry.modBaseSize)));
1218     cont = _Module32NextW(snapshot, &module_entry);
1219   }
1220   CloseHandle(snapshot);
1221
1222   symbols_loaded = true;
1223   return true;
1224 }
1225
1226
1227 void OS::LogSharedLibraryAddresses(Isolate* isolate) {
1228   // SharedLibraryEvents are logged when loading symbol information.
1229   // Only the shared libraries loaded at the time of the call to
1230   // LogSharedLibraryAddresses are logged.  DLLs loaded after
1231   // initialization are not accounted for.
1232   if (!LoadDbgHelpAndTlHelp32()) return;
1233   HANDLE process_handle = GetCurrentProcess();
1234   LoadSymbols(isolate, process_handle);
1235 }
1236
1237
1238 void OS::SignalCodeMovingGC() {
1239 }
1240
1241
1242 uint64_t OS::TotalPhysicalMemory() {
1243   MEMORYSTATUSEX memory_info;
1244   memory_info.dwLength = sizeof(memory_info);
1245   if (!GlobalMemoryStatusEx(&memory_info)) {
1246     UNREACHABLE();
1247     return 0;
1248   }
1249
1250   return static_cast<uint64_t>(memory_info.ullTotalPhys);
1251 }
1252
1253
1254 #else  // __MINGW32__
1255 void OS::LogSharedLibraryAddresses(Isolate* isolate) { }
1256 void OS::SignalCodeMovingGC() { }
1257 #endif  // __MINGW32__
1258
1259
1260 uint64_t OS::CpuFeaturesImpliedByPlatform() {
1261   return 0;  // Windows runs on anything.
1262 }
1263
1264
1265 double OS::nan_value() {
1266 #ifdef _MSC_VER
1267   // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
1268   // in mask set, so value equals mask.
1269   static const __int64 nanval = kQuietNaNMask;
1270   return *reinterpret_cast<const double*>(&nanval);
1271 #else  // _MSC_VER
1272   return NAN;
1273 #endif  // _MSC_VER
1274 }
1275
1276
1277 int OS::ActivationFrameAlignment() {
1278 #ifdef _WIN64
1279   return 16;  // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1280 #elif defined(__MINGW32__)
1281   // With gcc 4.4 the tree vectorization optimizer can generate code
1282   // that requires 16 byte alignment such as movdqa on x86.
1283   return 16;
1284 #else
1285   return 8;  // Floating-point math runs faster with 8-byte alignment.
1286 #endif
1287 }
1288
1289
1290 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
1291
1292
1293 VirtualMemory::VirtualMemory(size_t size)
1294     : address_(ReserveRegion(size)), size_(size) { }
1295
1296
1297 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1298     : address_(NULL), size_(0) {
1299   ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
1300   size_t request_size = RoundUp(size + alignment,
1301                                 static_cast<intptr_t>(OS::AllocateAlignment()));
1302   void* address = ReserveRegion(request_size);
1303   if (address == NULL) return;
1304   Address base = RoundUp(static_cast<Address>(address), alignment);
1305   // Try reducing the size by freeing and then reallocating a specific area.
1306   bool result = ReleaseRegion(address, request_size);
1307   USE(result);
1308   ASSERT(result);
1309   address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1310   if (address != NULL) {
1311     request_size = size;
1312     ASSERT(base == static_cast<Address>(address));
1313   } else {
1314     // Resizing failed, just go with a bigger area.
1315     address = ReserveRegion(request_size);
1316     if (address == NULL) return;
1317   }
1318   address_ = address;
1319   size_ = request_size;
1320 }
1321
1322
1323 VirtualMemory::~VirtualMemory() {
1324   if (IsReserved()) {
1325     bool result = ReleaseRegion(address(), size());
1326     ASSERT(result);
1327     USE(result);
1328   }
1329 }
1330
1331
1332 bool VirtualMemory::IsReserved() {
1333   return address_ != NULL;
1334 }
1335
1336
1337 void VirtualMemory::Reset() {
1338   address_ = NULL;
1339   size_ = 0;
1340 }
1341
1342
1343 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1344   return CommitRegion(address, size, is_executable);
1345 }
1346
1347
1348 bool VirtualMemory::Uncommit(void* address, size_t size) {
1349   ASSERT(IsReserved());
1350   return UncommitRegion(address, size);
1351 }
1352
1353
1354 bool VirtualMemory::Guard(void* address) {
1355   if (NULL == VirtualAlloc(address,
1356                            OS::CommitPageSize(),
1357                            MEM_COMMIT,
1358                            PAGE_NOACCESS)) {
1359     return false;
1360   }
1361   return true;
1362 }
1363
1364
1365 void* VirtualMemory::ReserveRegion(size_t size) {
1366   return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
1367 }
1368
1369
1370 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1371   int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1372   if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1373     return false;
1374   }
1375   return true;
1376 }
1377
1378
1379 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1380   return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1381 }
1382
1383
1384 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1385   return VirtualFree(base, 0, MEM_RELEASE) != 0;
1386 }
1387
1388
1389 bool VirtualMemory::HasLazyCommits() {
1390   // TODO(alph): implement for the platform.
1391   return false;
1392 }
1393
1394
1395 // ----------------------------------------------------------------------------
1396 // Win32 thread support.
1397
1398 // Definition of invalid thread handle and id.
1399 static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
1400
1401 // Entry point for threads. The supplied argument is a pointer to the thread
1402 // object. The entry function dispatches to the run method in the thread
1403 // object. It is important that this function has __stdcall calling
1404 // convention.
1405 static unsigned int __stdcall ThreadEntry(void* arg) {
1406   Thread* thread = reinterpret_cast<Thread*>(arg);
1407   thread->NotifyStartedAndRun();
1408   return 0;
1409 }
1410
1411
1412 class Thread::PlatformData : public Malloced {
1413  public:
1414   explicit PlatformData(HANDLE thread) : thread_(thread) {}
1415   HANDLE thread_;
1416   unsigned thread_id_;
1417 };
1418
1419
1420 // Initialize a Win32 thread object. The thread has an invalid thread
1421 // handle until it is started.
1422
1423 Thread::Thread(const Options& options)
1424     : stack_size_(options.stack_size()),
1425       start_semaphore_(NULL) {
1426   data_ = new PlatformData(kNoThread);
1427   set_name(options.name());
1428 }
1429
1430
1431 void Thread::set_name(const char* name) {
1432   OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
1433   name_[sizeof(name_) - 1] = '\0';
1434 }
1435
1436
1437 // Close our own handle for the thread.
1438 Thread::~Thread() {
1439   if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1440   delete data_;
1441 }
1442
1443
1444 // Create a new thread. It is important to use _beginthreadex() instead of
1445 // the Win32 function CreateThread(), because the CreateThread() does not
1446 // initialize thread specific structures in the C runtime library.
1447 void Thread::Start() {
1448   data_->thread_ = reinterpret_cast<HANDLE>(
1449       _beginthreadex(NULL,
1450                      static_cast<unsigned>(stack_size_),
1451                      ThreadEntry,
1452                      this,
1453                      0,
1454                      &data_->thread_id_));
1455 }
1456
1457
1458 // Wait for thread to terminate.
1459 void Thread::Join() {
1460   if (data_->thread_id_ != GetCurrentThreadId()) {
1461     WaitForSingleObject(data_->thread_, INFINITE);
1462   }
1463 }
1464
1465
1466 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1467   DWORD result = TlsAlloc();
1468   ASSERT(result != TLS_OUT_OF_INDEXES);
1469   return static_cast<LocalStorageKey>(result);
1470 }
1471
1472
1473 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1474   BOOL result = TlsFree(static_cast<DWORD>(key));
1475   USE(result);
1476   ASSERT(result);
1477 }
1478
1479
1480 void* Thread::GetThreadLocal(LocalStorageKey key) {
1481   return TlsGetValue(static_cast<DWORD>(key));
1482 }
1483
1484
1485 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1486   BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1487   USE(result);
1488   ASSERT(result);
1489 }
1490
1491
1492
1493 void Thread::YieldCPU() {
1494   Sleep(0);
1495 }
1496
1497 } }  // namespace v8::internal