-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
platform-win32.cc
1425 lines (1167 loc) Β· 45.8 KB
/
platform-win32.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Platform-specific code for Win32.
// Secure API functions are not available using MinGW with msvcrt.dll
// on Windows XP. Make sure MINGW_HAS_SECURE_API is not defined to
// disable definition of secure API functions in standard headers that
// would conflict with our own implementation.
#ifdef __MINGW32__
#include <_mingw.h>
#ifdef MINGW_HAS_SECURE_API
#undef MINGW_HAS_SECURE_API
#endif // MINGW_HAS_SECURE_API
#endif // __MINGW32__
#include <limits>
#include "src/base/win32-headers.h"
#include "src/base/bits.h"
#include "src/base/lazy-instance.h"
#include "src/base/macros.h"
#include "src/base/platform/platform.h"
#include "src/base/platform/time.h"
#include "src/base/timezone-cache.h"
#include "src/base/utils/random-number-generator.h"
#include <VersionHelpers.h>
#if defined(_MSC_VER)
#include <crtdbg.h> // NOLINT
#endif // defined(_MSC_VER)
// Extra functions for MinGW. Most of these are the _s functions which are in
// the Microsoft Visual Studio C++ CRT.
#ifdef __MINGW32__
#ifndef __MINGW64_VERSION_MAJOR
#define _TRUNCATE 0
#define STRUNCATE 80
inline void MemoryFence() {
int barrier = 0;
__asm__ __volatile__("xchgl %%eax,%0 ":"=r" (barrier));
}
#endif // __MINGW64_VERSION_MAJOR
int localtime_s(tm* out_tm, const time_t* time) {
tm* posix_local_time_struct = localtime_r(time, out_tm);
if (posix_local_time_struct == nullptr) return 1;
return 0;
}
int fopen_s(FILE** pFile, const char* filename, const char* mode) {
*pFile = fopen(filename, mode);
return *pFile != nullptr ? 0 : 1;
}
int _vsnprintf_s(char* buffer, size_t sizeOfBuffer, size_t count,
const char* format, va_list argptr) {
DCHECK(count == _TRUNCATE);
return _vsnprintf(buffer, sizeOfBuffer, format, argptr);
}
int strncpy_s(char* dest, size_t dest_size, const char* source, size_t count) {
CHECK(source != nullptr);
CHECK(dest != nullptr);
CHECK_GT(dest_size, 0);
if (count == _TRUNCATE) {
while (dest_size > 0 && *source != 0) {
*(dest++) = *(source++);
--dest_size;
}
if (dest_size == 0) {
*(dest - 1) = 0;
return STRUNCATE;
}
} else {
while (dest_size > 0 && count > 0 && *source != 0) {
*(dest++) = *(source++);
--dest_size;
--count;
}
}
CHECK_GT(dest_size, 0);
*dest = 0;
return 0;
}
#endif // __MINGW32__
namespace v8 {
namespace base {
namespace {
bool g_hard_abort = false;
} // namespace
class WindowsTimezoneCache : public TimezoneCache {
public:
WindowsTimezoneCache() : initialized_(false) {}
~WindowsTimezoneCache() override {}
void Clear(TimeZoneDetection) override { initialized_ = false; }
const char* LocalTimezone(double time) override;
double LocalTimeOffset(double time, bool is_utc) override;
double DaylightSavingsOffset(double time) override;
// Initialize timezone information. The timezone information is obtained from
// windows. If we cannot get the timezone information we fall back to CET.
void InitializeIfNeeded() {
// Just return if timezone information has already been initialized.
if (initialized_) return;
// Initialize POSIX time zone data.
_tzset();
// Obtain timezone information from operating system.
memset(&tzinfo_, 0, sizeof(tzinfo_));
if (GetTimeZoneInformation(&tzinfo_) == TIME_ZONE_ID_INVALID) {
// If we cannot get timezone information we fall back to CET.
tzinfo_.Bias = -60;
tzinfo_.StandardDate.wMonth = 10;
tzinfo_.StandardDate.wDay = 5;
tzinfo_.StandardDate.wHour = 3;
tzinfo_.StandardBias = 0;
tzinfo_.DaylightDate.wMonth = 3;
tzinfo_.DaylightDate.wDay = 5;
tzinfo_.DaylightDate.wHour = 2;
tzinfo_.DaylightBias = -60;
}
// Make standard and DST timezone names.
WideCharToMultiByte(CP_UTF8, 0, tzinfo_.StandardName, -1, std_tz_name_,
kTzNameSize, nullptr, nullptr);
std_tz_name_[kTzNameSize - 1] = '\0';
WideCharToMultiByte(CP_UTF8, 0, tzinfo_.DaylightName, -1, dst_tz_name_,
kTzNameSize, nullptr, nullptr);
dst_tz_name_[kTzNameSize - 1] = '\0';
// If OS returned empty string or resource id (like "@tzres.dll,-211")
// simply guess the name from the UTC bias of the timezone.
// To properly resolve the resource identifier requires a library load,
// which is not possible in a sandbox.
if (std_tz_name_[0] == '\0' || std_tz_name_[0] == '@') {
OS::SNPrintF(std_tz_name_, kTzNameSize - 1,
"%s Standard Time",
GuessTimezoneNameFromBias(tzinfo_.Bias));
}
if (dst_tz_name_[0] == '\0' || dst_tz_name_[0] == '@') {
OS::SNPrintF(dst_tz_name_, kTzNameSize - 1,
"%s Daylight Time",
GuessTimezoneNameFromBias(tzinfo_.Bias));
}
// Timezone information initialized.
initialized_ = true;
}
// Guess the name of the timezone from the bias.
// The guess is very biased towards the northern hemisphere.
const char* GuessTimezoneNameFromBias(int bias) {
static const int kHour = 60;
switch (-bias) {
case -9*kHour: return "Alaska";
case -8*kHour: return "Pacific";
case -7*kHour: return "Mountain";
case -6*kHour: return "Central";
case -5*kHour: return "Eastern";
case -4*kHour: return "Atlantic";
case 0*kHour: return "GMT";
case +1*kHour: return "Central Europe";
case +2*kHour: return "Eastern Europe";
case +3*kHour: return "Russia";
case +5*kHour + 30: return "India";
case +8*kHour: return "China";
case +9*kHour: return "Japan";
case +12*kHour: return "New Zealand";
default: return "Local";
}
}
private:
static const int kTzNameSize = 128;
bool initialized_;
char std_tz_name_[kTzNameSize];
char dst_tz_name_[kTzNameSize];
TIME_ZONE_INFORMATION tzinfo_;
friend class Win32Time;
};
// ----------------------------------------------------------------------------
// The Time class represents time on win32. A timestamp is represented as
// a 64-bit integer in 100 nanoseconds since January 1, 1601 (UTC). JavaScript
// timestamps are represented as a doubles in milliseconds since 00:00:00 UTC,
// January 1, 1970.
class Win32Time {
public:
// Constructors.
Win32Time();
explicit Win32Time(double jstime);
Win32Time(int year, int mon, int day, int hour, int min, int sec);
// Convert timestamp to JavaScript representation.
double ToJSTime();
// Set timestamp to current time.
void SetToCurrentTime();
// Returns the local timezone offset in milliseconds east of UTC. This is
// the number of milliseconds you must add to UTC to get local time, i.e.
// LocalOffset(CET) = 3600000 and LocalOffset(PST) = -28800000. This
// routine also takes into account whether daylight saving is effect
// at the time.
int64_t LocalOffset(WindowsTimezoneCache* cache);
// Returns the daylight savings time offset for the time in milliseconds.
int64_t DaylightSavingsOffset(WindowsTimezoneCache* cache);
// Returns a string identifying the current timezone for the
// timestamp taking into account daylight saving.
char* LocalTimezone(WindowsTimezoneCache* cache);
private:
// Constants for time conversion.
static const int64_t kTimeEpoc = 116444736000000000LL;
static const int64_t kTimeScaler = 10000;
static const int64_t kMsPerMinute = 60000;
// Constants for timezone information.
static const bool kShortTzNames = false;
// Return whether or not daylight savings time is in effect at this time.
bool InDST(WindowsTimezoneCache* cache);
// Accessor for FILETIME representation.
FILETIME& ft() { return time_.ft_; }
// Accessor for integer representation.
int64_t& t() { return time_.t_; }
// Although win32 uses 64-bit integers for representing timestamps,
// these are packed into a FILETIME structure. The FILETIME structure
// is just a struct representing a 64-bit integer. The TimeStamp union
// allows access to both a FILETIME and an integer representation of
// the timestamp.
union TimeStamp {
FILETIME ft_;
int64_t t_;
};
TimeStamp time_;
};
// Initialize timestamp to start of epoc.
Win32Time::Win32Time() {
t() = 0;
}
// Initialize timestamp from a JavaScript timestamp.
Win32Time::Win32Time(double jstime) {
t() = static_cast<int64_t>(jstime) * kTimeScaler + kTimeEpoc;
}
// Initialize timestamp from date/time components.
Win32Time::Win32Time(int year, int mon, int day, int hour, int min, int sec) {
SYSTEMTIME st;
st.wYear = year;
st.wMonth = mon;
st.wDay = day;
st.wHour = hour;
st.wMinute = min;
st.wSecond = sec;
st.wMilliseconds = 0;
SystemTimeToFileTime(&st, &ft());
}
// Convert timestamp to JavaScript timestamp.
double Win32Time::ToJSTime() {
return static_cast<double>((t() - kTimeEpoc) / kTimeScaler);
}
// Set timestamp to current time.
void Win32Time::SetToCurrentTime() {
// The default GetSystemTimeAsFileTime has a ~15.5ms resolution.
// Because we're fast, we like fast timers which have at least a
// 1ms resolution.
//
// timeGetTime() provides 1ms granularity when combined with
// timeBeginPeriod(). If the host application for v8 wants fast
// timers, it can use timeBeginPeriod to increase the resolution.
//
// Using timeGetTime() has a drawback because it is a 32bit value
// and hence rolls-over every ~49days.
//
// To use the clock, we use GetSystemTimeAsFileTime as our base;
// and then use timeGetTime to extrapolate current time from the
// start time. To deal with rollovers, we resync the clock
// any time when more than kMaxClockElapsedTime has passed or
// whenever timeGetTime creates a rollover.
static bool initialized = false;
static TimeStamp init_time;
static DWORD init_ticks;
static const int64_t kHundredNanosecondsPerSecond = 10000000;
static const int64_t kMaxClockElapsedTime =
60*kHundredNanosecondsPerSecond; // 1 minute
// If we are uninitialized, we need to resync the clock.
bool needs_resync = !initialized;
// Get the current time.
TimeStamp time_now;
GetSystemTimeAsFileTime(&time_now.ft_);
DWORD ticks_now = timeGetTime();
// Check if we need to resync due to clock rollover.
needs_resync |= ticks_now < init_ticks;
// Check if we need to resync due to elapsed time.
needs_resync |= (time_now.t_ - init_time.t_) > kMaxClockElapsedTime;
// Check if we need to resync due to backwards time change.
needs_resync |= time_now.t_ < init_time.t_;
// Resync the clock if necessary.
if (needs_resync) {
GetSystemTimeAsFileTime(&init_time.ft_);
init_ticks = ticks_now = timeGetTime();
initialized = true;
}
// Finally, compute the actual time. Why is this so hard.
DWORD elapsed = ticks_now - init_ticks;
this->time_.t_ = init_time.t_ + (static_cast<int64_t>(elapsed) * 10000);
}
// Return the local timezone offset in milliseconds east of UTC. This
// takes into account whether daylight saving is in effect at the time.
// Only times in the 32-bit Unix range may be passed to this function.
// Also, adding the time-zone offset to the input must not overflow.
// The function EquivalentTime() in date.js guarantees this.
int64_t Win32Time::LocalOffset(WindowsTimezoneCache* cache) {
cache->InitializeIfNeeded();
Win32Time rounded_to_second(*this);
rounded_to_second.t() =
rounded_to_second.t() / 1000 / kTimeScaler * 1000 * kTimeScaler;
// Convert to local time using POSIX localtime function.
// Windows XP Service Pack 3 made SystemTimeToTzSpecificLocalTime()
// very slow. Other browsers use localtime().
// Convert from JavaScript milliseconds past 1/1/1970 0:00:00 to
// POSIX seconds past 1/1/1970 0:00:00.
double unchecked_posix_time = rounded_to_second.ToJSTime() / 1000;
if (unchecked_posix_time > INT_MAX || unchecked_posix_time < 0) {
return 0;
}
// Because _USE_32BIT_TIME_T is defined, time_t is a 32-bit int.
time_t posix_time = static_cast<time_t>(unchecked_posix_time);
// Convert to local time, as struct with fields for day, hour, year, etc.
tm posix_local_time_struct;
if (localtime_s(&posix_local_time_struct, &posix_time)) return 0;
if (posix_local_time_struct.tm_isdst > 0) {
return (cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * -kMsPerMinute;
} else if (posix_local_time_struct.tm_isdst == 0) {
return (cache->tzinfo_.Bias + cache->tzinfo_.StandardBias) * -kMsPerMinute;
} else {
return cache->tzinfo_.Bias * -kMsPerMinute;
}
}
// Return whether or not daylight savings time is in effect at this time.
bool Win32Time::InDST(WindowsTimezoneCache* cache) {
cache->InitializeIfNeeded();
// Determine if DST is in effect at the specified time.
bool in_dst = false;
if (cache->tzinfo_.StandardDate.wMonth != 0 ||
cache->tzinfo_.DaylightDate.wMonth != 0) {
// Get the local timezone offset for the timestamp in milliseconds.
int64_t offset = LocalOffset(cache);
// Compute the offset for DST. The bias parameters in the timezone info
// are specified in minutes. These must be converted to milliseconds.
int64_t dstofs =
-(cache->tzinfo_.Bias + cache->tzinfo_.DaylightBias) * kMsPerMinute;
// If the local time offset equals the timezone bias plus the daylight
// bias then DST is in effect.
in_dst = offset == dstofs;
}
return in_dst;
}
// Return the daylight savings time offset for this time.
int64_t Win32Time::DaylightSavingsOffset(WindowsTimezoneCache* cache) {
return InDST(cache) ? 60 * kMsPerMinute : 0;
}
// Returns a string identifying the current timezone for the
// timestamp taking into account daylight saving.
char* Win32Time::LocalTimezone(WindowsTimezoneCache* cache) {
// Return the standard or DST time zone name based on whether daylight
// saving is in effect at the given time.
return InDST(cache) ? cache->dst_tz_name_ : cache->std_tz_name_;
}
// Returns the accumulated user time for thread.
int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
FILETIME dummy;
uint64_t usertime;
// Get the amount of time that the thread has executed in user mode.
if (!GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &dummy,
reinterpret_cast<FILETIME*>(&usertime))) return -1;
// Adjust the resolution to micro-seconds.
usertime /= 10;
// Convert to seconds and microseconds
*secs = static_cast<uint32_t>(usertime / 1000000);
*usecs = static_cast<uint32_t>(usertime % 1000000);
return 0;
}
// Returns current time as the number of milliseconds since
// 00:00:00 UTC, January 1, 1970.
double OS::TimeCurrentMillis() {
return Time::Now().ToJsTime();
}
// Returns a string identifying the current timezone taking into
// account daylight saving.
const char* WindowsTimezoneCache::LocalTimezone(double time) {
return Win32Time(time).LocalTimezone(this);
}
// Returns the local time offset in milliseconds east of UTC without
// taking daylight savings time into account.
double WindowsTimezoneCache::LocalTimeOffset(double time_ms, bool is_utc) {
// Ignore is_utc and time_ms for now. That way, the behavior wouldn't
// change with icu_timezone_data disabled.
// Use current time, rounded to the millisecond.
Win32Time t(OS::TimeCurrentMillis());
// Time::LocalOffset inlcudes any daylight savings offset, so subtract it.
return static_cast<double>(t.LocalOffset(this) -
t.DaylightSavingsOffset(this));
}
// Returns the daylight savings offset in milliseconds for the given
// time.
double WindowsTimezoneCache::DaylightSavingsOffset(double time) {
int64_t offset = Win32Time(time).DaylightSavingsOffset(this);
return static_cast<double>(offset);
}
TimezoneCache* OS::CreateTimezoneCache() { return new WindowsTimezoneCache(); }
int OS::GetLastError() {
return ::GetLastError();
}
int OS::GetCurrentProcessId() {
return static_cast<int>(::GetCurrentProcessId());
}
int OS::GetCurrentThreadId() {
return static_cast<int>(::GetCurrentThreadId());
}
void OS::ExitProcess(int exit_code) {
// Use TerminateProcess avoid races between isolate threads and
// static destructors.
fflush(stdout);
fflush(stderr);
TerminateProcess(GetCurrentProcess(), exit_code);
}
// ----------------------------------------------------------------------------
// Win32 console output.
//
// If a Win32 application is linked as a console application it has a normal
// standard output and standard error. In this case normal printf works fine
// for output. However, if the application is linked as a GUI application,
// the process doesn't have a console, and therefore (debugging) output is lost.
// This is the case if we are embedded in a windows program (like a browser).
// In order to be able to get debug output in this case the the debugging
// facility using OutputDebugString. This output goes to the active debugger
// for the process (if any). Else the output can be monitored using DBMON.EXE.
enum OutputMode {
UNKNOWN, // Output method has not yet been determined.
CONSOLE, // Output is written to stdout.
ODS // Output is written to debug facility.
};
static OutputMode output_mode = UNKNOWN; // Current output mode.
// Determine if the process has a console for output.
static bool HasConsole() {
// Only check the first time. Eventual race conditions are not a problem,
// because all threads will eventually determine the same mode.
if (output_mode == UNKNOWN) {
// We cannot just check that the standard output is attached to a console
// because this would fail if output is redirected to a file. Therefore we
// say that a process does not have an output console if either the
// standard output handle is invalid or its file type is unknown.
if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE &&
GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) != FILE_TYPE_UNKNOWN)
output_mode = CONSOLE;
else
output_mode = ODS;
}
return output_mode == CONSOLE;
}
static void VPrintHelper(FILE* stream, const char* format, va_list args) {
if ((stream == stdout || stream == stderr) && !HasConsole()) {
// It is important to use safe print here in order to avoid
// overflowing the buffer. We might truncate the output, but this
// does not crash.
char buffer[4096];
OS::VSNPrintF(buffer, sizeof(buffer), format, args);
OutputDebugStringA(buffer);
} else {
vfprintf(stream, format, args);
}
}
FILE* OS::FOpen(const char* path, const char* mode) {
FILE* result;
if (fopen_s(&result, path, mode) == 0) {
return result;
} else {
return nullptr;
}
}
bool OS::Remove(const char* path) {
return (DeleteFileA(path) != 0);
}
char OS::DirectorySeparator() { return '\\'; }
bool OS::isDirectorySeparator(const char ch) {
return ch == '/' || ch == '\\';
}
FILE* OS::OpenTemporaryFile() {
// tmpfile_s tries to use the root dir, don't use it.
char tempPathBuffer[MAX_PATH];
DWORD path_result = 0;
path_result = GetTempPathA(MAX_PATH, tempPathBuffer);
if (path_result > MAX_PATH || path_result == 0) return nullptr;
UINT name_result = 0;
char tempNameBuffer[MAX_PATH];
name_result = GetTempFileNameA(tempPathBuffer, "", 0, tempNameBuffer);
if (name_result == 0) return nullptr;
FILE* result = FOpen(tempNameBuffer, "w+"); // Same mode as tmpfile uses.
if (result != nullptr) {
Remove(tempNameBuffer); // Delete on close.
}
return result;
}
// Open log file in binary mode to avoid /n -> /r/n conversion.
const char* const OS::LogFileOpenMode = "wb";
// Print (debug) message to console.
void OS::Print(const char* format, ...) {
va_list args;
va_start(args, format);
VPrint(format, args);
va_end(args);
}
void OS::VPrint(const char* format, va_list args) {
VPrintHelper(stdout, format, args);
}
void OS::FPrint(FILE* out, const char* format, ...) {
va_list args;
va_start(args, format);
VFPrint(out, format, args);
va_end(args);
}
void OS::VFPrint(FILE* out, const char* format, va_list args) {
VPrintHelper(out, format, args);
}
// Print error message to console.
void OS::PrintError(const char* format, ...) {
va_list args;
va_start(args, format);
VPrintError(format, args);
va_end(args);
}
void OS::VPrintError(const char* format, va_list args) {
VPrintHelper(stderr, format, args);
}
int OS::SNPrintF(char* str, int length, const char* format, ...) {
va_list args;
va_start(args, format);
int result = VSNPrintF(str, length, format, args);
va_end(args);
return result;
}
int OS::VSNPrintF(char* str, int length, const char* format, va_list args) {
int n = _vsnprintf_s(str, length, _TRUNCATE, format, args);
// Make sure to zero-terminate the string if the output was
// truncated or if there was an error.
if (n < 0 || n >= length) {
if (length > 0)
str[length - 1] = '\0';
return -1;
} else {
return n;
}
}
void OS::StrNCpy(char* dest, int length, const char* src, size_t n) {
// Use _TRUNCATE or strncpy_s crashes (by design) if buffer is too small.
size_t buffer_size = static_cast<size_t>(length);
if (n + 1 > buffer_size) // count for trailing '\0'
n = _TRUNCATE;
int result = strncpy_s(dest, length, src, n);
USE(result);
DCHECK(result == 0 || (n == _TRUNCATE && result == STRUNCATE));
}
#undef _TRUNCATE
#undef STRUNCATE
DEFINE_LAZY_LEAKY_OBJECT_GETTER(RandomNumberGenerator,
GetPlatformRandomNumberGenerator)
static LazyMutex rng_mutex = LAZY_MUTEX_INITIALIZER;
void OS::Initialize(bool hard_abort, const char* const gc_fake_mmap) {
g_hard_abort = hard_abort;
}
// static
size_t OS::AllocatePageSize() {
static size_t allocate_alignment = 0;
if (allocate_alignment == 0) {
SYSTEM_INFO info;
GetSystemInfo(&info);
allocate_alignment = info.dwAllocationGranularity;
}
return allocate_alignment;
}
// static
size_t OS::CommitPageSize() {
static size_t page_size = 0;
if (page_size == 0) {
SYSTEM_INFO info;
GetSystemInfo(&info);
page_size = info.dwPageSize;
DCHECK_EQ(4096, page_size);
}
return page_size;
}
// static
void OS::SetRandomMmapSeed(int64_t seed) {
if (seed) {
MutexGuard guard(rng_mutex.Pointer());
GetPlatformRandomNumberGenerator()->SetSeed(seed);
}
}
// static
void* OS::GetRandomMmapAddr() {
// The address range used to randomize RWX allocations in OS::Allocate
// Try not to map pages into the default range that windows loads DLLs
// Use a multiple of 64k to prevent committing unused memory.
// Note: This does not guarantee RWX regions will be within the
// range kAllocationRandomAddressMin to kAllocationRandomAddressMax
#ifdef V8_HOST_ARCH_64_BIT
static const uintptr_t kAllocationRandomAddressMin = 0x0000000080000000;
static const uintptr_t kAllocationRandomAddressMax = 0x000003FFFFFF0000;
#else
static const uintptr_t kAllocationRandomAddressMin = 0x04000000;
static const uintptr_t kAllocationRandomAddressMax = 0x3FFF0000;
#endif
uintptr_t address;
{
MutexGuard guard(rng_mutex.Pointer());
GetPlatformRandomNumberGenerator()->NextBytes(&address, sizeof(address));
}
address <<= kPageSizeBits;
address += kAllocationRandomAddressMin;
address &= kAllocationRandomAddressMax;
return reinterpret_cast<void*>(address);
}
namespace {
DWORD GetProtectionFromMemoryPermission(OS::MemoryPermission access) {
switch (access) {
case OS::MemoryPermission::kNoAccess:
case OS::MemoryPermission::kNoAccessWillJitLater:
return PAGE_NOACCESS;
case OS::MemoryPermission::kRead:
return PAGE_READONLY;
case OS::MemoryPermission::kReadWrite:
return PAGE_READWRITE;
case OS::MemoryPermission::kReadWriteExecute:
if (IsWindows10OrGreater())
return PAGE_EXECUTE_READWRITE | PAGE_TARGETS_INVALID;
return PAGE_EXECUTE_READWRITE;
case OS::MemoryPermission::kReadExecute:
if (IsWindows10OrGreater())
return PAGE_EXECUTE_READ | PAGE_TARGETS_INVALID;
return PAGE_EXECUTE_READ;
}
UNREACHABLE();
}
uint8_t* RandomizedVirtualAlloc(size_t size, DWORD flags, DWORD protect,
void* hint) {
LPVOID base = nullptr;
static BOOL use_aslr = -1;
#ifdef V8_HOST_ARCH_32_BIT
// Don't bother randomizing on 32-bit hosts, because they lack the room and
// don't have viable ASLR anyway.
if (use_aslr == -1 && !IsWow64Process(GetCurrentProcess(), &use_aslr))
use_aslr = FALSE;
#else
use_aslr = TRUE;
#endif
if (use_aslr && protect != PAGE_READWRITE) {
// For executable or reserved pages try to randomize the allocation address.
base = VirtualAlloc(hint, size, flags, protect);
}
// On failure, let the OS find an address to use.
if (base == nullptr) {
base = VirtualAlloc(nullptr, size, flags, protect);
}
return reinterpret_cast<uint8_t*>(base);
}
} // namespace
// static
void* OS::Allocate(void* hint, size_t size, size_t alignment,
MemoryPermission access) {
size_t page_size = AllocatePageSize();
DCHECK_EQ(0, size % page_size);
DCHECK_EQ(0, alignment % page_size);
DCHECK_LE(page_size, alignment);
hint = AlignedAddress(hint, alignment);
DWORD flags = (access == OS::MemoryPermission::kNoAccess)
? MEM_RESERVE
: MEM_RESERVE | MEM_COMMIT;
DWORD protect = GetProtectionFromMemoryPermission(access);
// First, try an exact size aligned allocation.
uint8_t* base = RandomizedVirtualAlloc(size, flags, protect, hint);
if (base == nullptr) return nullptr; // Can't allocate, we're OOM.
// If address is suitably aligned, we're done.
uint8_t* aligned_base = reinterpret_cast<uint8_t*>(
RoundUp(reinterpret_cast<uintptr_t>(base), alignment));
if (base == aligned_base) return reinterpret_cast<void*>(base);
// Otherwise, free it and try a larger allocation.
CHECK(Free(base, size));
// Clear the hint. It's unlikely we can allocate at this address.
hint = nullptr;
// Add the maximum misalignment so we are guaranteed an aligned base address
// in the allocated region.
size_t padded_size = size + (alignment - page_size);
const int kMaxAttempts = 3;
aligned_base = nullptr;
for (int i = 0; i < kMaxAttempts; ++i) {
base = RandomizedVirtualAlloc(padded_size, flags, protect, hint);
if (base == nullptr) return nullptr; // Can't allocate, we're OOM.
// Try to trim the allocation by freeing the padded allocation and then
// calling VirtualAlloc at the aligned base.
CHECK(Free(base, padded_size));
aligned_base = reinterpret_cast<uint8_t*>(
RoundUp(reinterpret_cast<uintptr_t>(base), alignment));
base = reinterpret_cast<uint8_t*>(
VirtualAlloc(aligned_base, size, flags, protect));
// We might not get the reduced allocation due to a race. In that case,
// base will be nullptr.
if (base != nullptr) break;
}
DCHECK_IMPLIES(base, base == aligned_base);
return reinterpret_cast<void*>(base);
}
// static
bool OS::Free(void* address, const size_t size) {
DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % AllocatePageSize());
DCHECK_EQ(0, size % AllocatePageSize());
USE(size);
return VirtualFree(address, 0, MEM_RELEASE) != 0;
}
// static
bool OS::Release(void* address, size_t size) {
DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
DCHECK_EQ(0, size % CommitPageSize());
return VirtualFree(address, size, MEM_DECOMMIT) != 0;
}
// static
bool OS::SetPermissions(void* address, size_t size, MemoryPermission access) {
DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
DCHECK_EQ(0, size % CommitPageSize());
if (access == MemoryPermission::kNoAccess) {
return VirtualFree(address, size, MEM_DECOMMIT) != 0;
}
DWORD protect = GetProtectionFromMemoryPermission(access);
return VirtualAlloc(address, size, MEM_COMMIT, protect) != nullptr;
}
// static
bool OS::DiscardSystemPages(void* address, size_t size) {
// On Windows, discarded pages are not returned to the system immediately and
// not guaranteed to be zeroed when returned to the application.
using DiscardVirtualMemoryFunction =
DWORD(WINAPI*)(PVOID virtualAddress, SIZE_T size);
static std::atomic<DiscardVirtualMemoryFunction> discard_virtual_memory(
reinterpret_cast<DiscardVirtualMemoryFunction>(-1));
if (discard_virtual_memory ==
reinterpret_cast<DiscardVirtualMemoryFunction>(-1))
discard_virtual_memory =
reinterpret_cast<DiscardVirtualMemoryFunction>(GetProcAddress(
GetModuleHandle(L"Kernel32.dll"), "DiscardVirtualMemory"));
// Use DiscardVirtualMemory when available because it releases faster than
// MEM_RESET.
DiscardVirtualMemoryFunction discard_function = discard_virtual_memory.load();
if (discard_function) {
DWORD ret = discard_function(address, size);
if (!ret) return true;
}
// DiscardVirtualMemory is buggy in Win10 SP0, so fall back to MEM_RESET on
// failure.
void* ptr = VirtualAlloc(address, size, MEM_RESET, PAGE_READWRITE);
CHECK(ptr);
return ptr;
}
// static
bool OS::HasLazyCommits() {
// TODO(alph): implement for the platform.
return false;
}
void OS::Sleep(TimeDelta interval) {
::Sleep(static_cast<DWORD>(interval.InMilliseconds()));
}
void OS::Abort() {
// Give a chance to debug the failure.
if (IsDebuggerPresent()) {
DebugBreak();
}
// Before aborting, make sure to flush output buffers.
fflush(stdout);
fflush(stderr);
if (g_hard_abort) {
V8_IMMEDIATE_CRASH();
}
// Make the MSVCRT do a silent abort.
raise(SIGABRT);
// Make sure function doesn't return.
abort();
}
void OS::DebugBreak() {
#if V8_CC_MSVC
// To avoid Visual Studio runtime support the following code can be used
// instead
// __asm { int 3 }
__debugbreak();
#else
::DebugBreak();
#endif
}
class Win32MemoryMappedFile final : public OS::MemoryMappedFile {
public:
Win32MemoryMappedFile(HANDLE file, HANDLE file_mapping, void* memory,
size_t size)
: file_(file),
file_mapping_(file_mapping),
memory_(memory),
size_(size) {}
~Win32MemoryMappedFile() final;
void* memory() const final { return memory_; }
size_t size() const final { return size_; }
private:
HANDLE const file_;
HANDLE const file_mapping_;
void* const memory_;
size_t const size_;
};
// static
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name,
FileMode mode) {
// Open a physical file.
DWORD access = GENERIC_READ;
if (mode == FileMode::kReadWrite) {
access |= GENERIC_WRITE;
}
HANDLE file = CreateFileA(name, access, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, 0, nullptr);
if (file == INVALID_HANDLE_VALUE) return nullptr;
DWORD size = GetFileSize(file, nullptr);
if (size == 0) return new Win32MemoryMappedFile(file, nullptr, nullptr, 0);
DWORD protection =
(mode == FileMode::kReadOnly) ? PAGE_READONLY : PAGE_READWRITE;
// Create a file mapping for the physical file.
HANDLE file_mapping =
CreateFileMapping(file, nullptr, protection, 0, size, nullptr);
if (file_mapping == nullptr) return nullptr;
// Map a view of the file into memory.
DWORD view_access =
(mode == FileMode::kReadOnly) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;
void* memory = MapViewOfFile(file_mapping, view_access, 0, 0, size);
return new Win32MemoryMappedFile(file, file_mapping, memory, size);
}
// static