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