blob: b91f2a69d9eaf2166ad0d255339e23e080630ddd [file] [log] [blame]
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +00001// Copyright 2012 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000029
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +000030// Secure API functions are not available using MinGW with msvcrt.dll
31// on Windows XP. Make sure MINGW_HAS_SECURE_API is not defined to
32// disable definition of secure API functions in standard headers that
33// would conflict with our own implementation.
34#ifdef __MINGW32__
35#include <_mingw.h>
36#ifdef MINGW_HAS_SECURE_API
37#undef MINGW_HAS_SECURE_API
38#endif // MINGW_HAS_SECURE_API
39#endif // __MINGW32__
40
kasperl@chromium.orga5551262010-12-07 12:49:48 +000041#define V8_WIN32_HEADERS_FULL
42#include "win32-headers.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
44#include "v8.h"
45
ulan@chromium.org9a21ec42012-03-06 08:42:24 +000046#include "codegen.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000047#include "platform.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000048#include "vm-state-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049
iposva@chromium.org245aa852009-02-10 00:49:54 +000050#ifdef _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052// Case-insensitive bounded string comparisons. Use stricmp() on Win32. Usually
53// defined in strings.h.
54int strncasecmp(const char* s1, const char* s2, int n) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000055 return _strnicmp(s1, s2, n);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000056}
57
iposva@chromium.org245aa852009-02-10 00:49:54 +000058#endif // _MSC_VER
59
60
61// Extra functions for MinGW. Most of these are the _s functions which are in
62// the Microsoft Visual Studio C++ CRT.
63#ifdef __MINGW32__
64
svenpanne@chromium.orgfb046332012-04-19 12:02:44 +000065
66#ifndef __MINGW64_VERSION_MAJOR
67
68#define _TRUNCATE 0
69#define STRUNCATE 80
70
71inline void MemoryBarrier() {
72 int barrier = 0;
73 __asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
74}
75
76#endif // __MINGW64_VERSION_MAJOR
77
78
iposva@chromium.org245aa852009-02-10 00:49:54 +000079int localtime_s(tm* out_tm, const time_t* time) {
80 tm* posix_local_time_struct = localtime(time);
81 if (posix_local_time_struct == NULL) return 1;
82 *out_tm = *posix_local_time_struct;
83 return 0;
84}
85
86
iposva@chromium.org245aa852009-02-10 00:49:54 +000087int fopen_s(FILE** pFile, const char* filename, const char* mode) {
88 *pFile = fopen(filename, mode);
89 return *pFile != NULL ? 0 : 1;
90}
91
iposva@chromium.org245aa852009-02-10 00:49:54 +000092int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
93 const char* format, va_list argptr) {
sgjesse@chromium.org6db88712011-07-11 11:41:22 +000094 ASSERT(count == _TRUNCATE);
iposva@chromium.org245aa852009-02-10 00:49:54 +000095 return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
96}
iposva@chromium.org245aa852009-02-10 00:49:54 +000097
98
sgjesse@chromium.org6db88712011-07-11 11:41:22 +000099int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
100 CHECK(source != NULL);
101 CHECK(dest != NULL);
102 CHECK_GT(dest_size, 0);
103
104 if (count == _TRUNCATE) {
105 while (dest_size > 0 && *source != 0) {
106 *(dest++) = *(source++);
107 --dest_size;
108 }
109 if (dest_size == 0) {
110 *(dest - 1) = 0;
111 return STRUNCATE;
112 }
113 } else {
114 while (dest_size > 0 && count > 0 && *source != 0) {
115 *(dest++) = *(source++);
116 --dest_size;
117 --count;
118 }
119 }
120 CHECK_GT(dest_size, 0);
121 *dest = 0;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000122 return 0;
123}
124
125#endif // __MINGW32__
126
127// Generate a pseudo-random number in the range 0-2^31-1. Usually
128// defined in stdlib.h. Missing in both Microsoft Visual Studio C++ and MinGW.
129int random() {
130 return rand();
131}
132
133
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000134namespace v8 {
135namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000136
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000137intptr_t OS::MaxVirtualMemory() {
138 return 0;
139}
140
141
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000142double ceiling(double x) {
143 return ceil(x);
144}
145
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000146
147static Mutex* limit_mutex = NULL;
148
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000149#if defined(V8_TARGET_ARCH_IA32)
150static OS::MemCopyFunction memcopy_function = NULL;
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000151// Defined in codegen-ia32.cc.
152OS::MemCopyFunction CreateMemCopyFunction();
153
154// Copy memory area to disjoint memory area.
155void OS::MemCopy(void* dest, const void* src, size_t size) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000156 // Note: here we rely on dependent reads being ordered. This is true
157 // on all architectures we currently support.
158 (*memcopy_function)(dest, src, size);
159#ifdef DEBUG
160 CHECK_EQ(0, memcmp(dest, src, size));
161#endif
162}
163#endif // V8_TARGET_ARCH_IA32
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000164
ager@chromium.org3811b432009-10-28 14:53:37 +0000165#ifdef _WIN64
166typedef double (*ModuloFunction)(double, double);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000167static ModuloFunction modulo_function = NULL;
ager@chromium.org3811b432009-10-28 14:53:37 +0000168// Defined in codegen-x64.cc.
169ModuloFunction CreateModuloFunction();
170
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000171void init_modulo_function() {
172 modulo_function = CreateModuloFunction();
173}
174
ager@chromium.org3811b432009-10-28 14:53:37 +0000175double modulo(double x, double y) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000176 // Note: here we rely on dependent reads being ordered. This is true
177 // on all architectures we currently support.
178 return (*modulo_function)(x, y);
ager@chromium.org3811b432009-10-28 14:53:37 +0000179}
180#else // Win32
181
182double modulo(double x, double y) {
183 // Workaround MS fmod bugs. ECMA-262 says:
184 // dividend is finite and divisor is an infinity => result equals dividend
185 // dividend is a zero and divisor is nonzero finite => result equals dividend
186 if (!(isfinite(x) && (!isfinite(y) && !isnan(y))) &&
187 !(x == 0 && (y != 0 && isfinite(y)))) {
188 x = fmod(x, y);
189 }
190 return x;
191}
192
193#endif // _WIN64
194
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000195
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000196#define UNARY_MATH_FUNCTION(name, generator) \
197static UnaryMathFunction fast_##name##_function = NULL; \
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000198void init_fast_##name##_function() { \
199 fast_##name##_function = generator; \
200} \
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000201double fast_##name(double x) { \
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000202 return (*fast_##name##_function)(x); \
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000203}
204
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000205UNARY_MATH_FUNCTION(sin, CreateTranscendentalFunction(TranscendentalCache::SIN))
206UNARY_MATH_FUNCTION(cos, CreateTranscendentalFunction(TranscendentalCache::COS))
207UNARY_MATH_FUNCTION(tan, CreateTranscendentalFunction(TranscendentalCache::TAN))
208UNARY_MATH_FUNCTION(log, CreateTranscendentalFunction(TranscendentalCache::LOG))
danno@chromium.org1f34ad32012-11-26 14:53:56 +0000209UNARY_MATH_FUNCTION(exp, CreateExpFunction())
yangguo@chromium.org154ff992012-03-13 08:09:54 +0000210UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000211
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +0000212#undef UNARY_MATH_FUNCTION
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000213
214
danno@chromium.org1f34ad32012-11-26 14:53:56 +0000215void lazily_initialize_fast_exp() {
216 if (fast_exp_function == NULL) {
217 init_fast_exp_function();
218 }
219}
220
221
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000222void MathSetup() {
223#ifdef _WIN64
224 init_modulo_function();
225#endif
226 init_fast_sin_function();
227 init_fast_cos_function();
228 init_fast_tan_function();
229 init_fast_log_function();
danno@chromium.org1f34ad32012-11-26 14:53:56 +0000230 // fast_exp is initialized lazily.
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000231 init_fast_sqrt_function();
232}
233
234
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235// ----------------------------------------------------------------------------
236// The Time class represents time on win32. A timestamp is represented as
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000237// a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000238// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
239// January 1, 1970.
240
241class Time {
242 public:
243 // Constructors.
244 Time();
245 explicit Time(double jstime);
246 Time(int year, int mon, int day, int hour, int min, int sec);
247
248 // Convert timestamp to JavaScript representation.
249 double ToJSTime();
250
251 // Set timestamp to current time.
252 void SetToCurrentTime();
253
254 // Returns the local timezone offset in milliseconds east of UTC. This is
255 // the number of milliseconds you must add to UTC to get local time, i.e.
256 // LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
257 // routine also takes into account whether daylight saving is effect
258 // at the time.
259 int64_t LocalOffset();
260
261 // Returns the daylight savings time offset for the time in milliseconds.
262 int64_t DaylightSavingsOffset();
263
264 // Returns a string identifying the current timezone for the
265 // timestamp taking into account daylight saving.
266 char* LocalTimezone();
267
268 private:
269 // Constants for time conversion.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000270 static const int64_t kTimeEpoc = 116444736000000000LL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000271 static const int64_t kTimeScaler = 10000;
272 static const int64_t kMsPerMinute = 60000;
273
274 // Constants for timezone information.
275 static const int kTzNameSize = 128;
276 static const bool kShortTzNames = false;
277
278 // Timezone information. We need to have static buffers for the
279 // timezone names because we return pointers to these in
280 // LocalTimezone().
281 static bool tz_initialized_;
282 static TIME_ZONE_INFORMATION tzinfo_;
283 static char std_tz_name_[kTzNameSize];
284 static char dst_tz_name_[kTzNameSize];
285
286 // Initialize the timezone information (if not already done).
287 static void TzSet();
288
289 // Guess the name of the timezone from the bias.
290 static const char* GuessTimezoneNameFromBias(int bias);
291
292 // Return whether or not daylight savings time is in effect at this time.
293 bool InDST();
294
295 // Return the difference (in milliseconds) between this timestamp and
296 // another timestamp.
297 int64_t Diff(Time* other);
298
299 // Accessor for FILETIME representation.
300 FILETIME& ft() { return time_.ft_; }
301
302 // Accessor for integer representation.
303 int64_t& t() { return time_.t_; }
304
305 // Although win32 uses 64-bit integers for representing timestamps,
306 // these are packed into a FILETIME structure. The FILETIME structure
307 // is just a struct representing a 64-bit integer. The TimeStamp union
308 // allows access to both a FILETIME and an integer representation of
309 // the timestamp.
310 union TimeStamp {
311 FILETIME ft_;
312 int64_t t_;
313 };
314
315 TimeStamp time_;
316};
317
318// Static variables.
319bool Time::tz_initialized_ = false;
320TIME_ZONE_INFORMATION Time::tzinfo_;
321char Time::std_tz_name_[kTzNameSize];
322char Time::dst_tz_name_[kTzNameSize];
323
324
325// Initialize timestamp to start of epoc.
326Time::Time() {
327 t() = 0;
328}
329
330
331// Initialize timestamp from a JavaScript timestamp.
332Time::Time(double jstime) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000333 t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334}
335
336
337// Initialize timestamp from date/time components.
338Time::Time(int year, int mon, int day, int hour, int min, int sec) {
339 SYSTEMTIME st;
340 st.wYear = year;
341 st.wMonth = mon;
342 st.wDay = day;
343 st.wHour = hour;
344 st.wMinute = min;
345 st.wSecond = sec;
346 st.wMilliseconds = 0;
347 SystemTimeToFileTime(&st, &ft());
348}
349
350
351// Convert timestamp to JavaScript timestamp.
352double Time::ToJSTime() {
353 return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
354}
355
356
357// Guess the name of the timezone from the bias.
358// The guess is very biased towards the northern hemisphere.
359const char* Time::GuessTimezoneNameFromBias(int bias) {
360 static const int kHour = 60;
361 switch (-bias) {
362 case -9*kHour: return "Alaska";
363 case -8*kHour: return "Pacific";
364 case -7*kHour: return "Mountain";
365 case -6*kHour: return "Central";
366 case -5*kHour: return "Eastern";
367 case -4*kHour: return "Atlantic";
368 case 0*kHour: return "GMT";
369 case +1*kHour: return "Central Europe";
370 case +2*kHour: return "Eastern Europe";
371 case +3*kHour: return "Russia";
372 case +5*kHour + 30: return "India";
373 case +8*kHour: return "China";
374 case +9*kHour: return "Japan";
375 case +12*kHour: return "New Zealand";
376 default: return "Local";
377 }
378}
379
380
381// Initialize timezone information. The timezone information is obtained from
382// windows. If we cannot get the timezone information we fall back to CET.
383// Please notice that this code is not thread-safe.
384void Time::TzSet() {
385 // Just return if timezone information has already been initialized.
386 if (tz_initialized_) return;
387
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000388 // Initialize POSIX time zone data.
389 _tzset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000390 // Obtain timezone information from operating system.
391 memset(&tzinfo_, 0, sizeof(tzinfo_));
392 if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
393 // If we cannot get timezone information we fall back to CET.
394 tzinfo_.Bias = -60;
395 tzinfo_.StandardDate.wMonth = 10;
396 tzinfo_.StandardDate.wDay = 5;
397 tzinfo_.StandardDate.wHour = 3;
398 tzinfo_.StandardBias = 0;
399 tzinfo_.DaylightDate.wMonth = 3;
400 tzinfo_.DaylightDate.wDay = 5;
401 tzinfo_.DaylightDate.wHour = 2;
402 tzinfo_.DaylightBias = -60;
403 }
404
405 // Make standard and DST timezone names.
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000406 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1,
407 std_tz_name_, kTzNameSize, NULL, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000408 std_tz_name_[kTzNameSize - 1] = '\0';
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000409 WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1,
410 dst_tz_name_, kTzNameSize, NULL, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000411 dst_tz_name_[kTzNameSize - 1] = '\0';
412
413 // If OS returned empty string or resource id (like "@tzres.dll,-211")
414 // simply guess the name from the UTC bias of the timezone.
415 // To properly resolve the resource identifier requires a library load,
416 // which is not possible in a sandbox.
417 if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000418 OS::SNPrintF(Vector<char>(std_tz_name_, kTzNameSize - 1),
419 "%s Standard Time",
420 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000421 }
422 if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000423 OS::SNPrintF(Vector<char>(dst_tz_name_, kTzNameSize - 1),
424 "%s Daylight Time",
425 GuessTimezoneNameFromBias(tzinfo_.Bias));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000426 }
427
428 // Timezone information initialized.
429 tz_initialized_ = true;
430}
431
432
433// Return the difference in milliseconds between this and another timestamp.
434int64_t Time::Diff(Time* other) {
435 return (t() - other->t()) / kTimeScaler;
436}
437
438
439// Set timestamp to current time.
440void Time::SetToCurrentTime() {
441 // The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
442 // Because we're fast, we like fast timers which have at least a
443 // 1ms resolution.
444 //
445 // timeGetTime() provides 1ms granularity when combined with
446 // timeBeginPeriod(). If the host application for v8 wants fast
447 // timers, it can use timeBeginPeriod to increase the resolution.
448 //
449 // Using timeGetTime() has a drawback because it is a 32bit value
450 // and hence rolls-over every ~49days.
451 //
452 // To use the clock, we use GetSystemTimeAsFileTime as our base;
453 // and then use timeGetTime to extrapolate current time from the
454 // start time. To deal with rollovers, we resync the clock
455 // any time when more than kMaxClockElapsedTime has passed or
456 // whenever timeGetTime creates a rollover.
457
458 static bool initialized = false;
459 static TimeStamp init_time;
460 static DWORD init_ticks;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000461 static const int64_t kHundredNanosecondsPerSecond = 10000000;
462 static const int64_t kMaxClockElapsedTime =
463 60*kHundredNanosecondsPerSecond; // 1 minute
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000464
465 // If we are uninitialized, we need to resync the clock.
466 bool needs_resync = !initialized;
467
468 // Get the current time.
469 TimeStamp time_now;
470 GetSystemTimeAsFileTime(&time_now.ft_);
471 DWORD ticks_now = timeGetTime();
472
473 // Check if we need to resync due to clock rollover.
474 needs_resync |= ticks_now < init_ticks;
475
476 // Check if we need to resync due to elapsed time.
477 needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
478
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000479 // Check if we need to resync due to backwards time change.
480 needs_resync |= time_now.t_ < init_time.t_;
481
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482 // Resync the clock if necessary.
483 if (needs_resync) {
484 GetSystemTimeAsFileTime(&init_time.ft_);
485 init_ticks = ticks_now = timeGetTime();
486 initialized = true;
487 }
488
489 // Finally, compute the actual time. Why is this so hard.
490 DWORD elapsed = ticks_now - init_ticks;
491 this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
492}
493
494
495// Return the local timezone offset in milliseconds east of UTC. This
496// takes into account whether daylight saving is in effect at the time.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000497// Only times in the 32-bit Unix range may be passed to this function.
498// Also, adding the time-zone offset to the input must not overflow.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000499// The function EquivalentTime() in date.js guarantees this.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500int64_t Time::LocalOffset() {
501 // Initialize timezone information, if needed.
502 TzSet();
503
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000504 Time rounded_to_second(*this);
505 rounded_to_second.t() = rounded_to_second.t() / 1000 / kTimeScaler *
506 1000 * kTimeScaler;
507 // Convert to local time using POSIX localtime function.
508 // Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
509 // very slow. Other browsers use localtime().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000510
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000511 // Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
512 // POSIX seconds past 1/1/1970 0:00:00.
513 double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
514 if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
515 return 0;
516 }
517 // Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
518 time_t posix_time = static_cast<time_t>(unchecked_posix_time);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000519
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000520 // Convert to local time, as struct with fields for day, hour, year, etc.
521 tm posix_local_time_struct;
522 if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000523
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000524 if (posix_local_time_struct.tm_isdst > 0) {
525 return (tzinfo_.Bias + tzinfo_.DaylightBias) * -kMsPerMinute;
526 } else if (posix_local_time_struct.tm_isdst == 0) {
527 return (tzinfo_.Bias + tzinfo_.StandardBias) * -kMsPerMinute;
528 } else {
529 return tzinfo_.Bias * -kMsPerMinute;
530 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000531}
532
533
534// Return whether or not daylight savings time is in effect at this time.
535bool Time::InDST() {
536 // Initialize timezone information, if needed.
537 TzSet();
538
539 // Determine if DST is in effect at the specified time.
540 bool in_dst = false;
541 if (tzinfo_.StandardDate.wMonth != 0 || tzinfo_.DaylightDate.wMonth != 0) {
542 // Get the local timezone offset for the timestamp in milliseconds.
543 int64_t offset = LocalOffset();
544
545 // Compute the offset for DST. The bias parameters in the timezone info
546 // are specified in minutes. These must be converted to milliseconds.
547 int64_t dstofs = -(tzinfo_.Bias + tzinfo_.DaylightBias) * kMsPerMinute;
548
549 // If the local time offset equals the timezone bias plus the daylight
550 // bias then DST is in effect.
551 in_dst = offset == dstofs;
552 }
553
554 return in_dst;
555}
556
557
ager@chromium.org32912102009-01-16 10:38:43 +0000558// Return the daylight savings time offset for this time.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000559int64_t Time::DaylightSavingsOffset() {
560 return InDST() ? 60 * kMsPerMinute : 0;
561}
562
563
564// Returns a string identifying the current timezone for the
565// timestamp taking into account daylight saving.
566char* Time::LocalTimezone() {
567 // Return the standard or DST time zone name based on whether daylight
568 // saving is in effect at the given time.
569 return InDST() ? dst_tz_name_ : std_tz_name_;
570}
571
572
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000573void OS::PostSetUp() {
574 // Math functions depend on CPU features therefore they are initialized after
575 // CPU.
576 MathSetup();
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000577#if defined(V8_TARGET_ARCH_IA32)
578 memcopy_function = CreateMemCopyFunction();
579#endif
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000580}
581
582
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000583// Returns the accumulated user time for thread.
584int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
585 FILETIME dummy;
586 uint64_t usertime;
587
588 // Get the amount of time that the thread has executed in user mode.
589 if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
590 reinterpret_cast<FILETIME*>(&usertime))) return -1;
591
592 // Adjust the resolution to micro-seconds.
593 usertime /= 10;
594
595 // Convert to seconds and microseconds
596 *secs = static_cast<uint32_t>(usertime / 1000000);
597 *usecs = static_cast<uint32_t>(usertime % 1000000);
598 return 0;
599}
600
601
602// Returns current time as the number of milliseconds since
603// 00:00:00 UTC, January 1, 1970.
604double OS::TimeCurrentMillis() {
605 Time t;
606 t.SetToCurrentTime();
607 return t.ToJSTime();
608}
609
610// Returns the tickcounter based on timeGetTime.
611int64_t OS::Ticks() {
612 return timeGetTime() * 1000; // Convert to microseconds.
613}
614
615
616// Returns a string identifying the current timezone taking into
617// account daylight saving.
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000618const char* OS::LocalTimezone(double time) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000619 return Time(time).LocalTimezone();
620}
621
622
kasper.lund7276f142008-07-30 08:49:36 +0000623// Returns the local time offset in milliseconds east of UTC without
624// taking daylight savings time into account.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625double OS::LocalTimeOffset() {
kasper.lund7276f142008-07-30 08:49:36 +0000626 // Use current time, rounded to the millisecond.
627 Time t(TimeCurrentMillis());
628 // Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
629 return static_cast<double>(t.LocalOffset() - t.DaylightSavingsOffset());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000630}
631
632
633// Returns the daylight savings offset in milliseconds for the given
634// time.
635double OS::DaylightSavingsOffset(double time) {
636 int64_t offset = Time(time).DaylightSavingsOffset();
637 return static_cast<double>(offset);
638}
639
640
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000641int OS::GetLastError() {
642 return ::GetLastError();
643}
644
645
rossberg@chromium.org657d53b2012-07-12 11:06:03 +0000646int OS::GetCurrentProcessId() {
647 return static_cast<int>(::GetCurrentProcessId());
648}
649
650
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000651// ----------------------------------------------------------------------------
652// Win32 console output.
653//
654// If a Win32 application is linked as a console application it has a normal
655// standard output and standard error. In this case normal printf works fine
656// for output. However, if the application is linked as a GUI application,
657// the process doesn't have a console, and therefore (debugging) output is lost.
658// This is the case if we are embedded in a windows program (like a browser).
659// In order to be able to get debug output in this case the the debugging
660// facility using OutputDebugString. This output goes to the active debugger
661// for the process (if any). Else the output can be monitored using DBMON.EXE.
662
663enum OutputMode {
664 UNKNOWN, // Output method has not yet been determined.
665 CONSOLE, // Output is written to stdout.
666 ODS // Output is written to debug facility.
667};
668
669static OutputMode output_mode = UNKNOWN; // Current output mode.
670
671
672// Determine if the process has a console for output.
673static bool HasConsole() {
674 // Only check the first time. Eventual race conditions are not a problem,
675 // because all threads will eventually determine the same mode.
676 if (output_mode == UNKNOWN) {
677 // We cannot just check that the standard output is attached to a console
678 // because this would fail if output is redirected to a file. Therefore we
679 // say that a process does not have an output console if either the
680 // standard output handle is invalid or its file type is unknown.
681 if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
682 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
683 output_mode = CONSOLE;
684 else
685 output_mode = ODS;
686 }
687 return output_mode == CONSOLE;
688}
689
690
691static void VPrintHelper(FILE* stream, const char* format, va_list args) {
692 if (HasConsole()) {
693 vfprintf(stream, format, args);
694 } else {
695 // It is important to use safe print here in order to avoid
696 // overflowing the buffer. We might truncate the output, but this
697 // does not crash.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000698 EmbeddedVector<char, 4096> buffer;
699 OS::VSNPrintF(buffer, format, args);
700 OutputDebugStringA(buffer.start());
701 }
702}
703
704
705FILE* OS::FOpen(const char* path, const char* mode) {
706 FILE* result;
707 if (fopen_s(&result, path, mode) == 0) {
708 return result;
709 } else {
710 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000711 }
712}
713
714
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000715bool OS::Remove(const char* path) {
716 return (DeleteFileA(path) != 0);
717}
718
719
whesse@chromium.org030d38e2011-07-13 13:23:34 +0000720FILE* OS::OpenTemporaryFile() {
721 // tmpfile_s tries to use the root dir, don't use it.
722 char tempPathBuffer[MAX_PATH];
723 DWORD path_result = 0;
724 path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
725 if (path_result > MAX_PATH || path_result == 0) return NULL;
726 UINT name_result = 0;
727 char tempNameBuffer[MAX_PATH];
728 name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
729 if (name_result == 0) return NULL;
730 FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
731 if (result != NULL) {
732 Remove(tempNameBuffer); // Delete on close.
733 }
734 return result;
735}
736
737
ager@chromium.org71daaf62009-04-01 07:22:49 +0000738// Open log file in binary mode to avoid /n -> /r/n conversion.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000739const char* const OS::LogFileOpenMode = "wb";
ager@chromium.org71daaf62009-04-01 07:22:49 +0000740
741
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000742// Print (debug) message to console.
743void OS::Print(const char* format, ...) {
744 va_list args;
745 va_start(args, format);
746 VPrint(format, args);
747 va_end(args);
748}
749
750
751void OS::VPrint(const char* format, va_list args) {
752 VPrintHelper(stdout, format, args);
753}
754
755
whesse@chromium.org023421e2010-12-21 12:19:12 +0000756void OS::FPrint(FILE* out, const char* format, ...) {
757 va_list args;
758 va_start(args, format);
759 VFPrint(out, format, args);
760 va_end(args);
761}
762
763
764void OS::VFPrint(FILE* out, const char* format, va_list args) {
765 VPrintHelper(out, format, args);
766}
767
768
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000769// Print error message to console.
770void OS::PrintError(const char* format, ...) {
771 va_list args;
772 va_start(args, format);
773 VPrintError(format, args);
774 va_end(args);
775}
776
777
778void OS::VPrintError(const char* format, va_list args) {
779 VPrintHelper(stderr, format, args);
780}
781
782
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000783int OS::SNPrintF(Vector<char> str, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000784 va_list args;
785 va_start(args, format);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000786 int result = VSNPrintF(str, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000787 va_end(args);
788 return result;
789}
790
791
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000792int OS::VSNPrintF(Vector<char> str, const char* format, va_list args) {
793 int n = _vsnprintf_s(str.start(), str.length(), _TRUNCATE, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000794 // Make sure to zero-terminate the string if the output was
795 // truncated or if there was an error.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000796 if (n < 0 || n >= str.length()) {
whesse@chromium.org023421e2010-12-21 12:19:12 +0000797 if (str.length() > 0)
798 str[str.length() - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000799 return -1;
800 } else {
801 return n;
802 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000803}
804
805
ager@chromium.org381abbb2009-02-25 13:23:22 +0000806char* OS::StrChr(char* str, int c) {
807 return const_cast<char*>(strchr(str, c));
808}
809
810
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000811void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000812 // Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
813 size_t buffer_size = static_cast<size_t>(dest.length());
814 if (n + 1 > buffer_size) // count for trailing '\0'
815 n = _TRUNCATE;
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000816 int result = strncpy_s(dest.start(), dest.length(), src, n);
817 USE(result);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000818 ASSERT(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000819}
820
821
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +0000822#undef _TRUNCATE
823#undef STRUNCATE
824
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000825// We keep the lowest and highest addresses mapped as a quick way of
826// determining that pointers are outside the heap (used mostly in assertions
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000827// and verification). The estimate is conservative, i.e., not all addresses in
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000828// 'allocated' space are actually allocated to our heap. The range is
829// [lowest, highest), inclusive on the low and and exclusive on the high end.
830static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
831static void* highest_ever_allocated = reinterpret_cast<void*>(0);
832
833
834static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000835 ASSERT(limit_mutex != NULL);
836 ScopedLock lock(limit_mutex);
837
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838 lowest_ever_allocated = Min(lowest_ever_allocated, address);
839 highest_ever_allocated =
840 Max(highest_ever_allocated,
841 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
842}
843
844
845bool OS::IsOutsideAllocatedSpace(void* pointer) {
846 if (pointer < lowest_ever_allocated || pointer >= highest_ever_allocated)
847 return true;
848 // Ask the Windows API
849 if (IsBadWritePtr(pointer, 1))
850 return true;
851 return false;
852}
853
854
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000855// Get the system's page size used by VirtualAlloc() or the next power
856// of two. The reason for always returning a power of two is that the
857// rounding up in OS::Allocate expects that.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000858static size_t GetPageSize() {
859 static size_t page_size = 0;
860 if (page_size == 0) {
861 SYSTEM_INFO info;
862 GetSystemInfo(&info);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000863 page_size = RoundUpToPowerOf2(info.dwPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000864 }
865 return page_size;
866}
867
868
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000869// The allocation alignment is the guaranteed alignment for
870// VirtualAlloc'ed blocks of memory.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000871size_t OS::AllocateAlignment() {
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000872 static size_t allocate_alignment = 0;
873 if (allocate_alignment == 0) {
874 SYSTEM_INFO info;
875 GetSystemInfo(&info);
876 allocate_alignment = info.dwAllocationGranularity;
877 }
878 return allocate_alignment;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000879}
880
881
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000882static void* GetRandomAddr() {
883 Isolate* isolate = Isolate::UncheckedCurrent();
884 // Note that the current isolate isn't set up in a call path via
885 // CpuFeatures::Probe. We don't care about randomization in this case because
886 // the code page is immediately freed.
887 if (isolate != NULL) {
888 // The address range used to randomize RWX allocations in OS::Allocate
889 // Try not to map pages into the default range that windows loads DLLs
890 // Use a multiple of 64k to prevent committing unused memory.
891 // Note: This does not guarantee RWX regions will be within the
892 // range kAllocationRandomAddressMin to kAllocationRandomAddressMax
893#ifdef V8_HOST_ARCH_64_BIT
894 static const intptr_t kAllocationRandomAddressMin = 0x0000000080000000;
895 static const intptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
896#else
897 static const intptr_t kAllocationRandomAddressMin = 0x04000000;
898 static const intptr_t kAllocationRandomAddressMax = 0x3FFF0000;
899#endif
900 uintptr_t address = (V8::RandomPrivate(isolate) << kPageSizeBits)
901 | kAllocationRandomAddressMin;
902 address &= kAllocationRandomAddressMax;
903 return reinterpret_cast<void *>(address);
904 }
905 return NULL;
906}
907
908
909static void* RandomizedVirtualAlloc(size_t size, int action, int protection) {
910 LPVOID base = NULL;
911
912 if (protection == PAGE_EXECUTE_READWRITE || protection == PAGE_NOACCESS) {
913 // For exectutable pages try and randomize the allocation address
914 for (size_t attempts = 0; base == NULL && attempts < 3; ++attempts) {
915 base = VirtualAlloc(GetRandomAddr(), size, action, protection);
916 }
917 }
918
919 // After three attempts give up and let the OS find an address to use.
920 if (base == NULL) base = VirtualAlloc(NULL, size, action, protection);
921
922 return base;
923}
924
925
kasper.lund7276f142008-07-30 08:49:36 +0000926void* OS::Allocate(const size_t requested,
927 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000928 bool is_executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000929 // VirtualAlloc rounds allocated size to page size automatically.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000930 size_t msize = RoundUp(requested, static_cast<int>(GetPageSize()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931
932 // Windows XP SP2 allows Data Excution Prevention (DEP).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000933 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000934
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +0000935 LPVOID mbase = RandomizedVirtualAlloc(msize,
936 MEM_COMMIT | MEM_RESERVE,
937 prot);
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000938
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000939 if (mbase == NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000940 LOG(ISOLATE, StringEvent("OS::Allocate", "VirtualAlloc failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000941 return NULL;
942 }
943
944 ASSERT(IsAligned(reinterpret_cast<size_t>(mbase), OS::AllocateAlignment()));
945
946 *allocated = msize;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000947 UpdateAllocatedSpaceLimits(mbase, static_cast<int>(msize));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000948 return mbase;
949}
950
951
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000952void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000953 // TODO(1240712): VirtualFree has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000954 VirtualFree(address, 0, MEM_RELEASE);
955 USE(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000956}
957
958
ricow@chromium.org64e3a4b2011-12-13 08:07:27 +0000959intptr_t OS::CommitPageSize() {
960 return 4096;
961}
962
963
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000964void OS::ProtectCode(void* address, const size_t size) {
965 DWORD old_protect;
966 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
967}
968
969
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000970void OS::Guard(void* address, const size_t size) {
971 DWORD oldprotect;
972 VirtualProtect(address, size, PAGE_READONLY | PAGE_GUARD, &oldprotect);
973}
974
975
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000976void OS::Sleep(int milliseconds) {
977 ::Sleep(milliseconds);
978}
979
980
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000981int OS::NumberOfCores() {
982 SYSTEM_INFO info;
983 GetSystemInfo(&info);
984 return info.dwNumberOfProcessors;
985}
986
987
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000988void OS::Abort() {
rossberg@chromium.org2c067b12012-03-19 11:01:52 +0000989 if (IsDebuggerPresent() || FLAG_break_on_abort) {
990 DebugBreak();
991 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000992 // Make the MSVCRT do a silent abort.
ulan@chromium.org9a21ec42012-03-06 08:42:24 +0000993 raise(SIGABRT);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000994 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000995}
996
997
kasper.lund7276f142008-07-30 08:49:36 +0000998void OS::DebugBreak() {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000999#ifdef _MSC_VER
kasper.lund7276f142008-07-30 08:49:36 +00001000 __debugbreak();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001001#else
1002 ::DebugBreak();
1003#endif
kasper.lund7276f142008-07-30 08:49:36 +00001004}
1005
1006
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001007void OS::DumpBacktrace() {
1008 // Currently unsupported.
1009}
1010
1011
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001012class Win32MemoryMappedFile : public OS::MemoryMappedFile {
1013 public:
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001014 Win32MemoryMappedFile(HANDLE file,
1015 HANDLE file_mapping,
1016 void* memory,
1017 int size)
1018 : file_(file),
1019 file_mapping_(file_mapping),
1020 memory_(memory),
1021 size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022 virtual ~Win32MemoryMappedFile();
1023 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001024 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001025 private:
1026 HANDLE file_;
1027 HANDLE file_mapping_;
1028 void* memory_;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001029 int size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001030};
1031
1032
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001033OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
1034 // Open a physical file
1035 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
1036 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +00001037 if (file == INVALID_HANDLE_VALUE) return NULL;
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001038
1039 int size = static_cast<int>(GetFileSize(file, NULL));
1040
1041 // Create a file mapping for the physical file
1042 HANDLE file_mapping = CreateFileMapping(file, NULL,
1043 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
1044 if (file_mapping == NULL) return NULL;
1045
1046 // Map a view of the file into memory
1047 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
1048 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
1049}
1050
1051
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001052OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
1053 void* initial) {
1054 // Open a physical file
1055 HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
1056 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
1057 if (file == NULL) return NULL;
1058 // Create a file mapping for the physical file
1059 HANDLE file_mapping = CreateFileMapping(file, NULL,
1060 PAGE_READWRITE, 0, static_cast<DWORD>(size), NULL);
1061 if (file_mapping == NULL) return NULL;
1062 // Map a view of the file into memory
1063 void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
1064 if (memory) memmove(memory, initial, size);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +00001065 return new Win32MemoryMappedFile(file, file_mapping, memory, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001066}
1067
1068
1069Win32MemoryMappedFile::~Win32MemoryMappedFile() {
1070 if (memory_ != NULL)
1071 UnmapViewOfFile(memory_);
1072 CloseHandle(file_mapping_);
1073 CloseHandle(file_);
1074}
1075
1076
1077// The following code loads functions defined in DbhHelp.h and TlHelp32.h
ager@chromium.org32912102009-01-16 10:38:43 +00001078// dynamically. This is to avoid being depending on dbghelp.dll and
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001079// tlhelp32.dll when running (the functions in tlhelp32.dll have been moved to
1080// kernel32.dll at some point so loading functions defines in TlHelp32.h
1081// dynamically might not be necessary any more - for some versions of Windows?).
1082
1083// Function pointers to functions dynamically loaded from dbghelp.dll.
1084#define DBGHELP_FUNCTION_LIST(V) \
1085 V(SymInitialize) \
1086 V(SymGetOptions) \
1087 V(SymSetOptions) \
1088 V(SymGetSearchPath) \
1089 V(SymLoadModule64) \
1090 V(StackWalk64) \
1091 V(SymGetSymFromAddr64) \
1092 V(SymGetLineFromAddr64) \
1093 V(SymFunctionTableAccess64) \
1094 V(SymGetModuleBase64)
1095
1096// Function pointers to functions dynamically loaded from dbghelp.dll.
1097#define TLHELP32_FUNCTION_LIST(V) \
1098 V(CreateToolhelp32Snapshot) \
1099 V(Module32FirstW) \
1100 V(Module32NextW)
1101
1102// Define the decoration to use for the type and variable name used for
1103// dynamically loaded DLL function..
1104#define DLL_FUNC_TYPE(name) _##name##_
1105#define DLL_FUNC_VAR(name) _##name
1106
1107// Define the type for each dynamically loaded DLL function. The function
1108// definitions are copied from DbgHelp.h and TlHelp32.h. The IN and VOID macros
1109// from the Windows include files are redefined here to have the function
1110// definitions to be as close to the ones in the original .h files as possible.
1111#ifndef IN
1112#define IN
1113#endif
1114#ifndef VOID
1115#define VOID void
1116#endif
1117
iposva@chromium.org245aa852009-02-10 00:49:54 +00001118// DbgHelp isn't supported on MinGW yet
1119#ifndef __MINGW32__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001120// DbgHelp.h functions.
1121typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
1122 IN PSTR UserSearchPath,
1123 IN BOOL fInvadeProcess);
1124typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
1125typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
1126typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
1127 IN HANDLE hProcess,
1128 OUT PSTR SearchPath,
1129 IN DWORD SearchPathLength);
1130typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
1131 IN HANDLE hProcess,
1132 IN HANDLE hFile,
1133 IN PSTR ImageName,
1134 IN PSTR ModuleName,
1135 IN DWORD64 BaseOfDll,
1136 IN DWORD SizeOfDll);
1137typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
1138 DWORD MachineType,
1139 HANDLE hProcess,
1140 HANDLE hThread,
1141 LPSTACKFRAME64 StackFrame,
1142 PVOID ContextRecord,
1143 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
1144 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
1145 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
1146 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
1147typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
1148 IN HANDLE hProcess,
1149 IN DWORD64 qwAddr,
1150 OUT PDWORD64 pdwDisplacement,
1151 OUT PIMAGEHLP_SYMBOL64 Symbol);
1152typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
1153 IN HANDLE hProcess,
1154 IN DWORD64 qwAddr,
1155 OUT PDWORD pdwDisplacement,
1156 OUT PIMAGEHLP_LINE64 Line64);
1157// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
1158typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
1159 HANDLE hProcess,
1160 DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
1161typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
1162 HANDLE hProcess,
1163 DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
1164
1165// TlHelp32.h functions.
1166typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
1167 DWORD dwFlags,
1168 DWORD th32ProcessID);
1169typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
1170 LPMODULEENTRY32W lpme);
1171typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
1172 LPMODULEENTRY32W lpme);
1173
1174#undef IN
1175#undef VOID
1176
1177// Declare a variable for each dynamically loaded DLL function.
1178#define DEF_DLL_FUNCTION(name) DLL_FUNC_TYPE(name) DLL_FUNC_VAR(name) = NULL;
1179DBGHELP_FUNCTION_LIST(DEF_DLL_FUNCTION)
1180TLHELP32_FUNCTION_LIST(DEF_DLL_FUNCTION)
1181#undef DEF_DLL_FUNCTION
1182
1183// Load the functions. This function has a lot of "ugly" macros in order to
1184// keep down code duplication.
1185
1186static bool LoadDbgHelpAndTlHelp32() {
1187 static bool dbghelp_loaded = false;
1188
1189 if (dbghelp_loaded) return true;
1190
1191 HMODULE module;
1192
1193 // Load functions from the dbghelp.dll module.
1194 module = LoadLibrary(TEXT("dbghelp.dll"));
1195 if (module == NULL) {
1196 return false;
1197 }
1198
1199#define LOAD_DLL_FUNC(name) \
1200 DLL_FUNC_VAR(name) = \
1201 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1202
1203DBGHELP_FUNCTION_LIST(LOAD_DLL_FUNC)
1204
1205#undef LOAD_DLL_FUNC
1206
1207 // Load functions from the kernel32.dll module (the TlHelp32.h function used
1208 // to be in tlhelp32.dll but are now moved to kernel32.dll).
1209 module = LoadLibrary(TEXT("kernel32.dll"));
1210 if (module == NULL) {
1211 return false;
1212 }
1213
1214#define LOAD_DLL_FUNC(name) \
1215 DLL_FUNC_VAR(name) = \
1216 reinterpret_cast<DLL_FUNC_TYPE(name)>(GetProcAddress(module, #name));
1217
1218TLHELP32_FUNCTION_LIST(LOAD_DLL_FUNC)
1219
1220#undef LOAD_DLL_FUNC
1221
1222 // Check that all functions where loaded.
1223 bool result =
1224#define DLL_FUNC_LOADED(name) (DLL_FUNC_VAR(name) != NULL) &&
1225
1226DBGHELP_FUNCTION_LIST(DLL_FUNC_LOADED)
1227TLHELP32_FUNCTION_LIST(DLL_FUNC_LOADED)
1228
1229#undef DLL_FUNC_LOADED
1230 true;
1231
1232 dbghelp_loaded = result;
1233 return result;
ager@chromium.org32912102009-01-16 10:38:43 +00001234 // NOTE: The modules are never unloaded and will stay around until the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001235 // application is closed.
1236}
1237
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00001238#undef DBGHELP_FUNCTION_LIST
1239#undef TLHELP32_FUNCTION_LIST
1240#undef DLL_FUNC_VAR
1241#undef DLL_FUNC_TYPE
1242
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001243
1244// Load the symbols for generating stack traces.
1245static bool LoadSymbols(HANDLE process_handle) {
1246 static bool symbols_loaded = false;
1247
1248 if (symbols_loaded) return true;
1249
1250 BOOL ok;
1251
1252 // Initialize the symbol engine.
1253 ok = _SymInitialize(process_handle, // hProcess
1254 NULL, // UserSearchPath
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001255 false); // fInvadeProcess
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001256 if (!ok) return false;
1257
1258 DWORD options = _SymGetOptions();
1259 options |= SYMOPT_LOAD_LINES;
1260 options |= SYMOPT_FAIL_CRITICAL_ERRORS;
1261 options = _SymSetOptions(options);
1262
1263 char buf[OS::kStackWalkMaxNameLen] = {0};
1264 ok = _SymGetSearchPath(process_handle, buf, OS::kStackWalkMaxNameLen);
1265 if (!ok) {
1266 int err = GetLastError();
1267 PrintF("%d\n", err);
1268 return false;
1269 }
1270
1271 HANDLE snapshot = _CreateToolhelp32Snapshot(
1272 TH32CS_SNAPMODULE, // dwFlags
1273 GetCurrentProcessId()); // th32ProcessId
1274 if (snapshot == INVALID_HANDLE_VALUE) return false;
1275 MODULEENTRY32W module_entry;
1276 module_entry.dwSize = sizeof(module_entry); // Set the size of the structure.
1277 BOOL cont = _Module32FirstW(snapshot, &module_entry);
1278 while (cont) {
1279 DWORD64 base;
1280 // NOTE the SymLoadModule64 function has the peculiarity of accepting a
1281 // both unicode and ASCII strings even though the parameter is PSTR.
1282 base = _SymLoadModule64(
1283 process_handle, // hProcess
1284 0, // hFile
1285 reinterpret_cast<PSTR>(module_entry.szExePath), // ImageName
1286 reinterpret_cast<PSTR>(module_entry.szModule), // ModuleName
1287 reinterpret_cast<DWORD64>(module_entry.modBaseAddr), // BaseOfDll
1288 module_entry.modBaseSize); // SizeOfDll
1289 if (base == 0) {
1290 int err = GetLastError();
1291 if (err != ERROR_MOD_NOT_FOUND &&
1292 err != ERROR_INVALID_HANDLE) return false;
1293 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001294 LOG(i::Isolate::Current(),
1295 SharedLibraryEvent(
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001296 module_entry.szExePath,
1297 reinterpret_cast<unsigned int>(module_entry.modBaseAddr),
1298 reinterpret_cast<unsigned int>(module_entry.modBaseAddr +
1299 module_entry.modBaseSize)));
1300 cont = _Module32NextW(snapshot, &module_entry);
1301 }
1302 CloseHandle(snapshot);
1303
1304 symbols_loaded = true;
1305 return true;
1306}
1307
1308
1309void OS::LogSharedLibraryAddresses() {
1310 // SharedLibraryEvents are logged when loading symbol information.
1311 // Only the shared libraries loaded at the time of the call to
1312 // LogSharedLibraryAddresses are logged. DLLs loaded after
1313 // initialization are not accounted for.
1314 if (!LoadDbgHelpAndTlHelp32()) return;
1315 HANDLE process_handle = GetCurrentProcess();
1316 LoadSymbols(process_handle);
1317}
1318
1319
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00001320void OS::SignalCodeMovingGC() {
1321}
1322
1323
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001324// Walk the stack using the facilities in dbghelp.dll and tlhelp32.dll
1325
1326// Switch off warning 4748 (/GS can not protect parameters and local variables
1327// from local buffer overrun because optimizations are disabled in function) as
1328// it is triggered by the use of inline assembler.
1329#pragma warning(push)
1330#pragma warning(disable : 4748)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001331int OS::StackWalk(Vector<OS::StackFrame> frames) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001332 BOOL ok;
1333
1334 // Load the required functions from DLL's.
1335 if (!LoadDbgHelpAndTlHelp32()) return kStackWalkError;
1336
1337 // Get the process and thread handles.
1338 HANDLE process_handle = GetCurrentProcess();
1339 HANDLE thread_handle = GetCurrentThread();
1340
1341 // Read the symbols.
1342 if (!LoadSymbols(process_handle)) return kStackWalkError;
1343
1344 // Capture current context.
1345 CONTEXT context;
ager@chromium.org3811b432009-10-28 14:53:37 +00001346 RtlCaptureContext(&context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001347
1348 // Initialize the stack walking
1349 STACKFRAME64 stack_frame;
1350 memset(&stack_frame, 0, sizeof(stack_frame));
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001351#ifdef _WIN64
1352 stack_frame.AddrPC.Offset = context.Rip;
1353 stack_frame.AddrFrame.Offset = context.Rbp;
1354 stack_frame.AddrStack.Offset = context.Rsp;
1355#else
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001356 stack_frame.AddrPC.Offset = context.Eip;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001357 stack_frame.AddrFrame.Offset = context.Ebp;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001358 stack_frame.AddrStack.Offset = context.Esp;
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001359#endif
1360 stack_frame.AddrPC.Mode = AddrModeFlat;
1361 stack_frame.AddrFrame.Mode = AddrModeFlat;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001362 stack_frame.AddrStack.Mode = AddrModeFlat;
1363 int frames_count = 0;
1364
1365 // Collect stack frames.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001366 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001367 while (frames_count < frames_size) {
1368 ok = _StackWalk64(
1369 IMAGE_FILE_MACHINE_I386, // MachineType
1370 process_handle, // hProcess
1371 thread_handle, // hThread
1372 &stack_frame, // StackFrame
1373 &context, // ContextRecord
1374 NULL, // ReadMemoryRoutine
1375 _SymFunctionTableAccess64, // FunctionTableAccessRoutine
1376 _SymGetModuleBase64, // GetModuleBaseRoutine
1377 NULL); // TranslateAddress
1378 if (!ok) break;
1379
1380 // Store the address.
1381 ASSERT((stack_frame.AddrPC.Offset >> 32) == 0); // 32-bit address.
1382 frames[frames_count].address =
1383 reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
1384
1385 // Try to locate a symbol for this frame.
1386 DWORD64 symbol_displacement;
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001387 SmartArrayPointer<IMAGEHLP_SYMBOL64> symbol(
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001388 NewArray<IMAGEHLP_SYMBOL64>(kStackWalkMaxNameLen));
1389 if (symbol.is_empty()) return kStackWalkError; // Out of memory.
1390 memset(*symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + kStackWalkMaxNameLen);
1391 (*symbol)->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
1392 (*symbol)->MaxNameLength = kStackWalkMaxNameLen;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001393 ok = _SymGetSymFromAddr64(process_handle, // hProcess
1394 stack_frame.AddrPC.Offset, // Address
1395 &symbol_displacement, // Displacement
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001396 *symbol); // Symbol
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001397 if (ok) {
1398 // Try to locate more source information for the symbol.
1399 IMAGEHLP_LINE64 Line;
1400 memset(&Line, 0, sizeof(Line));
1401 Line.SizeOfStruct = sizeof(Line);
1402 DWORD line_displacement;
1403 ok = _SymGetLineFromAddr64(
1404 process_handle, // hProcess
1405 stack_frame.AddrPC.Offset, // dwAddr
1406 &line_displacement, // pdwDisplacement
1407 &Line); // Line
1408 // Format a text representation of the frame based on the information
1409 // available.
1410 if (ok) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001411 SNPrintF(MutableCStrVector(frames[frames_count].text,
1412 kStackWalkMaxTextLen),
1413 "%s %s:%d:%d",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001414 (*symbol)->Name, Line.FileName, Line.LineNumber,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001415 line_displacement);
1416 } else {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001417 SNPrintF(MutableCStrVector(frames[frames_count].text,
1418 kStackWalkMaxTextLen),
1419 "%s",
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +00001420 (*symbol)->Name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421 }
1422 // Make sure line termination is in place.
1423 frames[frames_count].text[kStackWalkMaxTextLen - 1] = '\0';
1424 } else {
1425 // No text representation of this frame
1426 frames[frames_count].text[0] = '\0';
1427
1428 // Continue if we are just missing a module (for non C/C++ frames a
1429 // module will never be found).
1430 int err = GetLastError();
1431 if (err != ERROR_MOD_NOT_FOUND) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001432 break;
1433 }
1434 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001435
1436 frames_count++;
1437 }
1438
1439 // Return the number of frames filled in.
1440 return frames_count;
1441}
1442
1443// Restore warnings to previous settings.
1444#pragma warning(pop)
1445
iposva@chromium.org245aa852009-02-10 00:49:54 +00001446#else // __MINGW32__
1447void OS::LogSharedLibraryAddresses() { }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001448void OS::SignalCodeMovingGC() { }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001449int OS::StackWalk(Vector<OS::StackFrame> frames) { return 0; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001450#endif // __MINGW32__
1451
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001452
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001453uint64_t OS::CpuFeaturesImpliedByPlatform() {
1454 return 0; // Windows runs on anything.
1455}
1456
1457
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001458double OS::nan_value() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001459#ifdef _MSC_VER
ager@chromium.org3811b432009-10-28 14:53:37 +00001460 // Positive Quiet NaN with no payload (aka. Indeterminate) has all bits
1461 // in mask set, so value equals mask.
1462 static const __int64 nanval = kQuietNaNMask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463 return *reinterpret_cast<const double*>(&nanval);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001464#else // _MSC_VER
1465 return NAN;
1466#endif // _MSC_VER
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467}
1468
ager@chromium.org236ad962008-09-25 09:45:57 +00001469
1470int OS::ActivationFrameAlignment() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001471#ifdef _WIN64
1472 return 16; // Windows 64-bit ABI requires the stack to be 16-byte aligned.
1473#else
1474 return 8; // Floating-point math runs faster with 8-byte alignment.
1475#endif
ager@chromium.org236ad962008-09-25 09:45:57 +00001476}
1477
1478
kmillikin@chromium.org9155e252010-05-26 13:27:57 +00001479void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
1480 MemoryBarrier();
1481 *ptr = value;
1482}
1483
1484
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001485VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001486
1487
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001488VirtualMemory::VirtualMemory(size_t size)
1489 : address_(ReserveRegion(size)), size_(size) { }
1490
1491
1492VirtualMemory::VirtualMemory(size_t size, size_t alignment)
1493 : address_(NULL), size_(0) {
1494 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
1495 size_t request_size = RoundUp(size + alignment,
1496 static_cast<intptr_t>(OS::AllocateAlignment()));
1497 void* address = ReserveRegion(request_size);
1498 if (address == NULL) return;
1499 Address base = RoundUp(static_cast<Address>(address), alignment);
1500 // Try reducing the size by freeing and then reallocating a specific area.
1501 bool result = ReleaseRegion(address, request_size);
1502 USE(result);
1503 ASSERT(result);
1504 address = VirtualAlloc(base, size, MEM_RESERVE, PAGE_NOACCESS);
1505 if (address != NULL) {
1506 request_size = size;
1507 ASSERT(base == static_cast<Address>(address));
1508 } else {
1509 // Resizing failed, just go with a bigger area.
1510 address = ReserveRegion(request_size);
1511 if (address == NULL) return;
1512 }
1513 address_ = address;
1514 size_ = request_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001515}
1516
1517
1518VirtualMemory::~VirtualMemory() {
1519 if (IsReserved()) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001520 bool result = ReleaseRegion(address_, size_);
1521 ASSERT(result);
1522 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001523 }
1524}
1525
1526
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001527bool VirtualMemory::IsReserved() {
1528 return address_ != NULL;
1529}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001530
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001531
1532void VirtualMemory::Reset() {
1533 address_ = NULL;
1534 size_ = 0;
1535}
1536
1537
1538bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
1539 if (CommitRegion(address, size, is_executable)) {
1540 UpdateAllocatedSpaceLimits(address, static_cast<int>(size));
1541 return true;
1542 }
1543 return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001544}
1545
1546
1547bool VirtualMemory::Uncommit(void* address, size_t size) {
1548 ASSERT(IsReserved());
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001549 return UncommitRegion(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001550}
1551
1552
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001553void* VirtualMemory::ReserveRegion(size_t size) {
kmillikin@chromium.orgbe6bd102012-02-23 08:45:21 +00001554 return RandomizedVirtualAlloc(size, MEM_RESERVE, PAGE_NOACCESS);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001555}
1556
1557
1558bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
1559 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
1560 if (NULL == VirtualAlloc(base, size, MEM_COMMIT, prot)) {
1561 return false;
1562 }
1563
1564 UpdateAllocatedSpaceLimits(base, static_cast<int>(size));
1565 return true;
1566}
1567
1568
yangguo@chromium.orgab30bb82012-02-24 14:41:46 +00001569bool VirtualMemory::Guard(void* address) {
1570 if (NULL == VirtualAlloc(address,
1571 OS::CommitPageSize(),
1572 MEM_COMMIT,
1573 PAGE_READONLY | PAGE_GUARD)) {
1574 return false;
1575 }
1576 return true;
1577}
1578
1579
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001580bool VirtualMemory::UncommitRegion(void* base, size_t size) {
1581 return VirtualFree(base, size, MEM_DECOMMIT) != 0;
1582}
1583
1584
1585bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
1586 return VirtualFree(base, 0, MEM_RELEASE) != 0;
1587}
1588
1589
danno@chromium.org72204d52012-10-31 10:02:10 +00001590bool VirtualMemory::HasLazyCommits() {
1591 // TODO(alph): implement for the platform.
1592 return false;
1593}
1594
1595
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001596// ----------------------------------------------------------------------------
1597// Win32 thread support.
1598
1599// Definition of invalid thread handle and id.
1600static const HANDLE kNoThread = INVALID_HANDLE_VALUE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001601
1602// Entry point for threads. The supplied argument is a pointer to the thread
1603// object. The entry function dispatches to the run method in the thread
1604// object. It is important that this function has __stdcall calling
1605// convention.
1606static unsigned int __stdcall ThreadEntry(void* arg) {
1607 Thread* thread = reinterpret_cast<Thread*>(arg);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608 thread->Run();
1609 return 0;
1610}
1611
1612
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001613class Thread::PlatformData : public Malloced {
1614 public:
1615 explicit PlatformData(HANDLE thread) : thread_(thread) {}
1616 HANDLE thread_;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001617 unsigned thread_id_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618};
1619
1620
1621// Initialize a Win32 thread object. The thread has an invalid thread
1622// handle until it is started.
1623
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +00001624Thread::Thread(const Options& options)
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00001625 : stack_size_(options.stack_size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001626 data_ = new PlatformData(kNoThread);
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00001627 set_name(options.name());
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001628}
1629
1630
1631void Thread::set_name(const char* name) {
erik.corry@gmail.com0511e242011-01-19 11:11:08 +00001632 OS::StrNCpy(Vector<char>(name_, sizeof(name_)), name, strlen(name));
lrn@chromium.org5d00b602011-01-05 09:51:43 +00001633 name_[sizeof(name_) - 1] = '\0';
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001634}
1635
1636
1637// Close our own handle for the thread.
1638Thread::~Thread() {
1639 if (data_->thread_ != kNoThread) CloseHandle(data_->thread_);
1640 delete data_;
1641}
1642
1643
1644// Create a new thread. It is important to use _beginthreadex() instead of
1645// the Win32 function CreateThread(), because the CreateThread() does not
1646// initialize thread specific structures in the C runtime library.
1647void Thread::Start() {
1648 data_->thread_ = reinterpret_cast<HANDLE>(
1649 _beginthreadex(NULL,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001650 static_cast<unsigned>(stack_size_),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001651 ThreadEntry,
1652 this,
1653 0,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001654 &data_->thread_id_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001655}
1656
1657
1658// Wait for thread to terminate.
1659void Thread::Join() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001660 if (data_->thread_id_ != GetCurrentThreadId()) {
1661 WaitForSingleObject(data_->thread_, INFINITE);
1662 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001663}
1664
1665
1666Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
1667 DWORD result = TlsAlloc();
1668 ASSERT(result != TLS_OUT_OF_INDEXES);
1669 return static_cast<LocalStorageKey>(result);
1670}
1671
1672
1673void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
1674 BOOL result = TlsFree(static_cast<DWORD>(key));
1675 USE(result);
1676 ASSERT(result);
1677}
1678
1679
1680void* Thread::GetThreadLocal(LocalStorageKey key) {
1681 return TlsGetValue(static_cast<DWORD>(key));
1682}
1683
1684
1685void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
1686 BOOL result = TlsSetValue(static_cast<DWORD>(key), value);
1687 USE(result);
1688 ASSERT(result);
1689}
1690
1691
1692
1693void Thread::YieldCPU() {
1694 Sleep(0);
1695}
1696
1697
1698// ----------------------------------------------------------------------------
1699// Win32 mutex support.
1700//
1701// On Win32 mutexes are implemented using CRITICAL_SECTION objects. These are
1702// faster than Win32 Mutex objects because they are implemented using user mode
1703// atomic instructions. Therefore we only do ring transitions if there is lock
1704// contention.
1705
1706class Win32Mutex : public Mutex {
1707 public:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001708 Win32Mutex() { InitializeCriticalSection(&cs_); }
1709
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001710 virtual ~Win32Mutex() { DeleteCriticalSection(&cs_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001711
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001712 virtual int Lock() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001713 EnterCriticalSection(&cs_);
1714 return 0;
1715 }
1716
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001717 virtual int Unlock() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001718 LeaveCriticalSection(&cs_);
1719 return 0;
1720 }
1721
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001722
1723 virtual bool TryLock() {
1724 // Returns non-zero if critical section is entered successfully entered.
1725 return TryEnterCriticalSection(&cs_);
1726 }
1727
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001728 private:
1729 CRITICAL_SECTION cs_; // Critical section used for mutex
1730};
1731
1732
1733Mutex* OS::CreateMutex() {
1734 return new Win32Mutex();
1735}
1736
1737
1738// ----------------------------------------------------------------------------
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001739// Win32 semaphore support.
1740//
1741// On Win32 semaphores are implemented using Win32 Semaphore objects. The
1742// semaphores are anonymous. Also, the semaphores are initialized to have
1743// no upper limit on count.
1744
1745
1746class Win32Semaphore : public Semaphore {
1747 public:
1748 explicit Win32Semaphore(int count) {
1749 sem = ::CreateSemaphoreA(NULL, count, 0x7fffffff, NULL);
1750 }
1751
1752 ~Win32Semaphore() {
1753 CloseHandle(sem);
1754 }
1755
1756 void Wait() {
1757 WaitForSingleObject(sem, INFINITE);
1758 }
1759
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001760 bool Wait(int timeout) {
1761 // Timeout in Windows API is in milliseconds.
1762 DWORD millis_timeout = timeout / 1000;
1763 return WaitForSingleObject(sem, millis_timeout) != WAIT_TIMEOUT;
1764 }
1765
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001766 void Signal() {
1767 LONG dummy;
1768 ReleaseSemaphore(sem, 1, &dummy);
1769 }
1770
1771 private:
1772 HANDLE sem;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001773};
1774
1775
1776Semaphore* OS::CreateSemaphore(int count) {
1777 return new Win32Semaphore(count);
1778}
1779
ager@chromium.org381abbb2009-02-25 13:23:22 +00001780
1781// ----------------------------------------------------------------------------
1782// Win32 socket support.
1783//
1784
1785class Win32Socket : public Socket {
1786 public:
1787 explicit Win32Socket() {
1788 // Create the socket.
1789 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1790 }
1791 explicit Win32Socket(SOCKET socket): socket_(socket) { }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001792 virtual ~Win32Socket() { Shutdown(); }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001793
1794 // Server initialization.
1795 bool Bind(const int port);
1796 bool Listen(int backlog) const;
1797 Socket* Accept() const;
1798
1799 // Client initialization.
1800 bool Connect(const char* host, const char* port);
1801
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001802 // Shutdown socket for both read and write.
1803 bool Shutdown();
1804
ager@chromium.org381abbb2009-02-25 13:23:22 +00001805 // Data Transimission
1806 int Send(const char* data, int len) const;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001807 int Receive(char* data, int len) const;
1808
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001809 bool SetReuseAddress(bool reuse_address);
1810
ager@chromium.org381abbb2009-02-25 13:23:22 +00001811 bool IsValid() const { return socket_ != INVALID_SOCKET; }
1812
1813 private:
1814 SOCKET socket_;
1815};
1816
1817
1818bool Win32Socket::Bind(const int port) {
1819 if (!IsValid()) {
1820 return false;
1821 }
1822
1823 sockaddr_in addr;
1824 memset(&addr, 0, sizeof(addr));
1825 addr.sin_family = AF_INET;
1826 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1827 addr.sin_port = htons(port);
1828 int status = bind(socket_,
1829 reinterpret_cast<struct sockaddr *>(&addr),
1830 sizeof(addr));
1831 return status == 0;
1832}
1833
1834
1835bool Win32Socket::Listen(int backlog) const {
1836 if (!IsValid()) {
1837 return false;
1838 }
1839
1840 int status = listen(socket_, backlog);
1841 return status == 0;
1842}
1843
1844
1845Socket* Win32Socket::Accept() const {
1846 if (!IsValid()) {
1847 return NULL;
1848 }
1849
1850 SOCKET socket = accept(socket_, NULL, NULL);
1851 if (socket == INVALID_SOCKET) {
1852 return NULL;
1853 } else {
1854 return new Win32Socket(socket);
1855 }
1856}
1857
1858
1859bool Win32Socket::Connect(const char* host, const char* port) {
1860 if (!IsValid()) {
1861 return false;
1862 }
1863
1864 // Lookup host and port.
1865 struct addrinfo *result = NULL;
1866 struct addrinfo hints;
1867 memset(&hints, 0, sizeof(addrinfo));
1868 hints.ai_family = AF_INET;
1869 hints.ai_socktype = SOCK_STREAM;
1870 hints.ai_protocol = IPPROTO_TCP;
1871 int status = getaddrinfo(host, port, &hints, &result);
1872 if (status != 0) {
1873 return false;
1874 }
1875
1876 // Connect.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001877 status = connect(socket_,
1878 result->ai_addr,
1879 static_cast<int>(result->ai_addrlen));
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001880 freeaddrinfo(result);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001881 return status == 0;
1882}
1883
1884
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001885bool Win32Socket::Shutdown() {
1886 if (IsValid()) {
1887 // Shutdown socket for both read and write.
1888 int status = shutdown(socket_, SD_BOTH);
1889 closesocket(socket_);
1890 socket_ = INVALID_SOCKET;
1891 return status == SOCKET_ERROR;
1892 }
1893 return true;
1894}
1895
1896
ager@chromium.org381abbb2009-02-25 13:23:22 +00001897int Win32Socket::Send(const char* data, int len) const {
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001898 if (len <= 0) return 0;
1899 int written = 0;
1900 while (written < len) {
1901 int status = send(socket_, data + written, len - written, 0);
1902 if (status == 0) {
1903 break;
1904 } else if (status > 0) {
1905 written += status;
1906 } else {
1907 return 0;
1908 }
1909 }
1910 return written;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001911}
1912
1913
ager@chromium.org381abbb2009-02-25 13:23:22 +00001914int Win32Socket::Receive(char* data, int len) const {
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001915 if (len <= 0) return 0;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001916 int status = recv(socket_, data, len, 0);
ulan@chromium.org0e3f88b2012-05-22 09:16:05 +00001917 return (status == SOCKET_ERROR) ? 0 : status;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001918}
1919
1920
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001921bool Win32Socket::SetReuseAddress(bool reuse_address) {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001922 BOOL on = reuse_address ? true : false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001923 int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
1924 reinterpret_cast<char*>(&on), sizeof(on));
1925 return status == SOCKET_ERROR;
1926}
1927
1928
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001929bool Socket::SetUp() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001930 // Initialize Winsock32
1931 int err;
1932 WSADATA winsock_data;
1933 WORD version_requested = MAKEWORD(1, 0);
1934 err = WSAStartup(version_requested, &winsock_data);
1935 if (err != 0) {
1936 PrintF("Unable to initialize Winsock, err = %d\n", Socket::LastError());
1937 }
1938
1939 return err == 0;
1940}
1941
1942
1943int Socket::LastError() {
1944 return WSAGetLastError();
1945}
1946
1947
1948uint16_t Socket::HToN(uint16_t value) {
1949 return htons(value);
1950}
1951
1952
1953uint16_t Socket::NToH(uint16_t value) {
1954 return ntohs(value);
1955}
1956
1957
1958uint32_t Socket::HToN(uint32_t value) {
1959 return htonl(value);
1960}
1961
1962
1963uint32_t Socket::NToH(uint32_t value) {
1964 return ntohl(value);
1965}
1966
1967
1968Socket* OS::CreateSocket() {
1969 return new Win32Socket();
1970}
1971
1972
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001973// ----------------------------------------------------------------------------
1974// Win32 profiler support.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001975
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001976class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001977 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001978 // Get a handle to the calling thread. This is the thread that we are
1979 // going to profile. We need to make a copy of the handle because we are
1980 // going to use it in the sampler thread. Using GetThreadHandle() will
1981 // not work in this case. We're using OpenThread because DuplicateHandle
1982 // for some reason doesn't work in Chrome's sandbox.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001983 PlatformData() : profiled_thread_(OpenThread(THREAD_GET_CONTEXT |
1984 THREAD_SUSPEND_RESUME |
1985 THREAD_QUERY_INFORMATION,
1986 false,
1987 GetCurrentThreadId())) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001988
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001989 ~PlatformData() {
1990 if (profiled_thread_ != NULL) {
1991 CloseHandle(profiled_thread_);
1992 profiled_thread_ = NULL;
1993 }
1994 }
1995
1996 HANDLE profiled_thread() { return profiled_thread_; }
1997
1998 private:
1999 HANDLE profiled_thread_;
2000};
2001
2002
2003class SamplerThread : public Thread {
2004 public:
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00002005 static const int kSamplerThreadStackSize = 64 * KB;
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00002006
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002007 explicit SamplerThread(int interval)
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00002008 : Thread(Thread::Options("SamplerThread", kSamplerThreadStackSize)),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002009 interval_(interval) {}
2010
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00002011 static void SetUp() { if (!mutex_) mutex_ = OS::CreateMutex(); }
2012 static void TearDown() { delete mutex_; }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00002013
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002014 static void AddActiveSampler(Sampler* sampler) {
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00002015 ScopedLock lock(mutex_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002016 SamplerRegistry::AddActiveSampler(sampler);
2017 if (instance_ == NULL) {
2018 instance_ = new SamplerThread(sampler->interval());
2019 instance_->Start();
2020 } else {
2021 ASSERT(instance_->interval_ == sampler->interval());
2022 }
2023 }
2024
2025 static void RemoveActiveSampler(Sampler* sampler) {
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00002026 ScopedLock lock(mutex_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002027 SamplerRegistry::RemoveActiveSampler(sampler);
2028 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00002029 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002030 delete instance_;
2031 instance_ = NULL;
2032 }
2033 }
2034
2035 // Implement Thread::Run().
2036 virtual void Run() {
2037 SamplerRegistry::State state;
2038 while ((state = SamplerRegistry::GetState()) !=
2039 SamplerRegistry::HAS_NO_SAMPLERS) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002040 // When CPU profiling is enabled both JavaScript and C++ code is
2041 // profiled. We must not suspend.
rossberg@chromium.orgcddc71f2012-12-07 12:40:13 +00002042 if (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS) {
2043 SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this);
2044 } else {
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002045 if (RuntimeProfiler::WaitForSomeIsolateToEnterJS()) continue;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002046 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002047 OS::Sleep(interval_);
2048 }
2049 }
2050
2051 static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
2052 if (!sampler->isolate()->IsInitialized()) return;
2053 if (!sampler->IsProfiling()) return;
2054 SamplerThread* sampler_thread =
2055 reinterpret_cast<SamplerThread*>(raw_sampler_thread);
2056 sampler_thread->SampleContext(sampler);
2057 }
2058
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002059 void SampleContext(Sampler* sampler) {
2060 HANDLE profiled_thread = sampler->platform_data()->profiled_thread();
2061 if (profiled_thread == NULL) return;
2062
2063 // Context used for sampling the register state of the profiled thread.
2064 CONTEXT context;
2065 memset(&context, 0, sizeof(context));
2066
rossberg@chromium.org89e18f52012-10-22 13:09:53 +00002067 TickSample sample_obj;
mmassi@chromium.org49a44672012-12-04 13:52:03 +00002068 TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
rossberg@chromium.org89e18f52012-10-22 13:09:53 +00002069 if (sample == NULL) sample = &sample_obj;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002070
2071 static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
2072 if (SuspendThread(profiled_thread) == kSuspendFailed) return;
2073 sample->state = sampler->isolate()->current_vm_state();
2074
2075 context.ContextFlags = CONTEXT_FULL;
2076 if (GetThreadContext(profiled_thread, &context) != 0) {
2077#if V8_HOST_ARCH_X64
2078 sample->pc = reinterpret_cast<Address>(context.Rip);
2079 sample->sp = reinterpret_cast<Address>(context.Rsp);
2080 sample->fp = reinterpret_cast<Address>(context.Rbp);
2081#else
2082 sample->pc = reinterpret_cast<Address>(context.Eip);
2083 sample->sp = reinterpret_cast<Address>(context.Esp);
2084 sample->fp = reinterpret_cast<Address>(context.Ebp);
2085#endif
2086 sampler->SampleStack(sample);
2087 sampler->Tick(sample);
2088 }
2089 ResumeThread(profiled_thread);
2090 }
2091
2092 const int interval_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002093
2094 // Protects the process wide state below.
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00002095 static Mutex* mutex_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002096 static SamplerThread* instance_;
2097
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +00002098 private:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002099 DISALLOW_COPY_AND_ASSIGN(SamplerThread);
2100};
2101
2102
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00002103Mutex* SamplerThread::mutex_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002104SamplerThread* SamplerThread::instance_ = NULL;
2105
2106
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00002107void OS::SetUp() {
2108 // Seed the random number generator.
2109 // Convert the current time to a 64-bit integer first, before converting it
2110 // to an unsigned. Going directly can cause an overflow and the seed to be
2111 // set to all ones. The seed will be identical for different instances that
2112 // call this setup code within the same millisecond.
2113 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
2114 srand(static_cast<unsigned int>(seed));
2115 limit_mutex = CreateMutex();
2116 SamplerThread::SetUp();
2117}
2118
2119
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00002120void OS::TearDown() {
2121 SamplerThread::TearDown();
2122 delete limit_mutex;
2123}
2124
2125
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002126Sampler::Sampler(Isolate* isolate, int interval)
2127 : isolate_(isolate),
2128 interval_(interval),
2129 profiling_(false),
2130 active_(false),
2131 samples_taken_(0) {
2132 data_ = new PlatformData;
2133}
2134
2135
2136Sampler::~Sampler() {
2137 ASSERT(!IsActive());
2138 delete data_;
2139}
2140
2141
2142void Sampler::Start() {
2143 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002144 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002145 SamplerThread::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002146}
2147
2148
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002149void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002150 ASSERT(IsActive());
2151 SamplerThread::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002152 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002153}
2154
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002155
mstarzinger@chromium.org71fc3462013-02-27 09:34:27 +00002156bool Sampler::CanSampleOnProfilerEventsProcessorThread() {
2157 return false;
2158}
2159
2160
2161void Sampler::DoSample() {
2162}
2163
2164
2165void Sampler::StartProfiling() {
2166}
2167
2168
2169void Sampler::StopProfiling() {
2170}
2171
2172
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002173} } // namespace v8::internal