This repository has been archived by the owner on Mar 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathos_windows.cpp
5881 lines (5059 loc) · 196 KB
/
os_windows.cpp
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 (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// Must be at least Windows 2000 or XP to use IsDebuggerPresent
#define _WIN32_WINNT 0x500
// no precompiled headers
#include "classfile/classLoader.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/icBuffer.hpp"
#include "code/vtableStubs.hpp"
#include "compiler/compileBroker.hpp"
#include "compiler/disassembler.hpp"
#include "interpreter/interpreter.hpp"
#include "jvm_windows.h"
#include "memory/allocation.inline.hpp"
#include "memory/filemap.hpp"
#include "mutex_windows.inline.hpp"
#include "oops/oop.inline.hpp"
#include "os_share_windows.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm.h"
#include "prims/jvm_misc.hpp"
#include "runtime/arguments.hpp"
#include "runtime/extendedPC.hpp"
#include "runtime/globals.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/orderAccess.inline.hpp"
#include "runtime/osThread.hpp"
#include "runtime/perfMemory.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/statSampler.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadCritical.hpp"
#include "runtime/timer.hpp"
#include "services/attachListener.hpp"
#include "services/memTracker.hpp"
#include "services/runtimeService.hpp"
#include "utilities/decoder.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
#include "utilities/growableArray.hpp"
#include "utilities/vmError.hpp"
#ifdef _DEBUG
#include <crtdbg.h>
#endif
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/timeb.h>
#include <objidl.h>
#include <shlobj.h>
#include <malloc.h>
#include <signal.h>
#include <direct.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <process.h> // For _beginthreadex(), _endthreadex()
#include <imagehlp.h> // For os::dll_address_to_function_name
/* for enumerating dll libraries */
#include <vdmdbg.h>
// for timer info max values which include all bits
#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
// For DLL loading/load error detection
// Values of PE COFF
#define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c
#define IMAGE_FILE_SIGNATURE_LENGTH 4
static HANDLE main_process;
static HANDLE main_thread;
static int main_thread_id;
static FILETIME process_creation_time;
static FILETIME process_exit_time;
static FILETIME process_user_time;
static FILETIME process_kernel_time;
#ifdef _M_IA64
#define __CPU__ ia64
#else
#ifdef _M_AMD64
#define __CPU__ amd64
#else
#define __CPU__ i486
#endif
#endif
// save DLL module handle, used by GetModuleFileName
HINSTANCE vm_lib_handle;
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
switch (reason) {
case DLL_PROCESS_ATTACH:
vm_lib_handle = hinst;
if(ForceTimeHighResolution)
timeBeginPeriod(1L);
break;
case DLL_PROCESS_DETACH:
if(ForceTimeHighResolution)
timeEndPeriod(1L);
break;
default:
break;
}
return true;
}
static inline double fileTimeAsDouble(FILETIME* time) {
const double high = (double) ((unsigned int) ~0);
const double split = 10000000.0;
double result = (time->dwLowDateTime / split) +
time->dwHighDateTime * (high/split);
return result;
}
// Implementation of os
bool os::getenv(const char* name, char* buffer, int len) {
int result = GetEnvironmentVariable(name, buffer, len);
return result > 0 && result < len;
}
bool os::unsetenv(const char* name) {
assert(name != NULL, "Null pointer");
return (SetEnvironmentVariable(name, NULL) == TRUE);
}
// No setuid programs under Windows.
bool os::have_special_privileges() {
return false;
}
// This method is a periodic task to check for misbehaving JNI applications
// under CheckJNI, we can add any periodic checks here.
// For Windows at the moment does nothing
void os::run_periodic_checks() {
return;
}
#ifndef _WIN64
// previous UnhandledExceptionFilter, if there is one
static LPTOP_LEVEL_EXCEPTION_FILTER prev_uef_handler = NULL;
LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo);
#endif
void os::init_system_properties_values() {
/* sysclasspath, java_home, dll_dir */
{
char *home_path;
char *dll_path;
char *pslash;
char *bin = "\\bin";
char home_dir[MAX_PATH];
if (!getenv("_ALT_JAVA_HOME_DIR", home_dir, MAX_PATH)) {
os::jvm_path(home_dir, sizeof(home_dir));
// Found the full path to jvm.dll.
// Now cut the path to <java_home>/jre if we can.
*(strrchr(home_dir, '\\')) = '\0'; /* get rid of \jvm.dll */
pslash = strrchr(home_dir, '\\');
if (pslash != NULL) {
*pslash = '\0'; /* get rid of \{client|server} */
pslash = strrchr(home_dir, '\\');
if (pslash != NULL)
*pslash = '\0'; /* get rid of \bin */
}
}
home_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + 1, mtInternal);
if (home_path == NULL)
return;
strcpy(home_path, home_dir);
Arguments::set_java_home(home_path);
dll_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + strlen(bin) + 1, mtInternal);
if (dll_path == NULL)
return;
strcpy(dll_path, home_dir);
strcat(dll_path, bin);
Arguments::set_dll_dir(dll_path);
if (!set_boot_path('\\', ';'))
return;
}
/* library_path */
#define EXT_DIR "\\lib\\ext"
#define BIN_DIR "\\bin"
#define PACKAGE_DIR "\\Sun\\Java"
{
/* Win32 library search order (See the documentation for LoadLibrary):
*
* 1. The directory from which application is loaded.
* 2. The system wide Java Extensions directory (Java only)
* 3. System directory (GetSystemDirectory)
* 4. Windows directory (GetWindowsDirectory)
* 5. The PATH environment variable
* 6. The current directory
*/
char *library_path;
char tmp[MAX_PATH];
char *path_str = ::getenv("PATH");
library_path = NEW_C_HEAP_ARRAY(char, MAX_PATH * 5 + sizeof(PACKAGE_DIR) +
sizeof(BIN_DIR) + (path_str ? strlen(path_str) : 0) + 10, mtInternal);
library_path[0] = '\0';
GetModuleFileName(NULL, tmp, sizeof(tmp));
*(strrchr(tmp, '\\')) = '\0';
strcat(library_path, tmp);
GetWindowsDirectory(tmp, sizeof(tmp));
strcat(library_path, ";");
strcat(library_path, tmp);
strcat(library_path, PACKAGE_DIR BIN_DIR);
GetSystemDirectory(tmp, sizeof(tmp));
strcat(library_path, ";");
strcat(library_path, tmp);
GetWindowsDirectory(tmp, sizeof(tmp));
strcat(library_path, ";");
strcat(library_path, tmp);
if (path_str) {
strcat(library_path, ";");
strcat(library_path, path_str);
}
strcat(library_path, ";.");
Arguments::set_library_path(library_path);
FREE_C_HEAP_ARRAY(char, library_path, mtInternal);
}
/* Default extensions directory */
{
char path[MAX_PATH];
char buf[2 * MAX_PATH + 2 * sizeof(EXT_DIR) + sizeof(PACKAGE_DIR) + 1];
GetWindowsDirectory(path, MAX_PATH);
sprintf(buf, "%s%s;%s%s%s", Arguments::get_java_home(), EXT_DIR,
path, PACKAGE_DIR, EXT_DIR);
Arguments::set_ext_dirs(buf);
}
#undef EXT_DIR
#undef BIN_DIR
#undef PACKAGE_DIR
/* Default endorsed standards directory. */
{
#define ENDORSED_DIR "\\lib\\endorsed"
size_t len = strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR);
char * buf = NEW_C_HEAP_ARRAY(char, len, mtInternal);
sprintf(buf, "%s%s", Arguments::get_java_home(), ENDORSED_DIR);
Arguments::set_endorsed_dirs(buf);
#undef ENDORSED_DIR
}
#ifndef _WIN64
// set our UnhandledExceptionFilter and save any previous one
prev_uef_handler = SetUnhandledExceptionFilter(Handle_FLT_Exception);
#endif
// Done
return;
}
void os::breakpoint() {
DebugBreak();
}
// Invoked from the BREAKPOINT Macro
extern "C" void breakpoint() {
os::breakpoint();
}
/*
* RtlCaptureStackBackTrace Windows API may not exist prior to Windows XP.
* So far, this method is only used by Native Memory Tracking, which is
* only supported on Windows XP or later.
*/
int os::get_native_stack(address* stack, int frames, int toSkip) {
#ifdef _NMT_NOINLINE_
toSkip ++;
#endif
int captured = Kernel32Dll::RtlCaptureStackBackTrace(toSkip + 1, frames,
(PVOID*)stack, NULL);
for (int index = captured; index < frames; index ++) {
stack[index] = NULL;
}
return captured;
}
// os::current_stack_base()
//
// Returns the base of the stack, which is the stack's
// starting address. This function must be called
// while running on the stack of the thread being queried.
address os::current_stack_base() {
MEMORY_BASIC_INFORMATION minfo;
address stack_bottom;
size_t stack_size;
VirtualQuery(&minfo, &minfo, sizeof(minfo));
stack_bottom = (address)minfo.AllocationBase;
stack_size = minfo.RegionSize;
// Add up the sizes of all the regions with the same
// AllocationBase.
while( 1 )
{
VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo));
if ( stack_bottom == (address)minfo.AllocationBase )
stack_size += minfo.RegionSize;
else
break;
}
#ifdef _M_IA64
// IA64 has memory and register stacks
//
// This is the stack layout you get on NT/IA64 if you specify 1MB stack limit
// at thread creation (1MB backing store growing upwards, 1MB memory stack
// growing downwards, 2MB summed up)
//
// ...
// ------- top of stack (high address) -----
// |
// | 1MB
// | Backing Store (Register Stack)
// |
// | / \
// | |
// | |
// | |
// ------------------------ stack base -----
// | 1MB
// | Memory Stack
// |
// | |
// | |
// | |
// | \ /
// |
// ----- bottom of stack (low address) -----
// ...
stack_size = stack_size / 2;
#endif
return stack_bottom + stack_size;
}
size_t os::current_stack_size() {
size_t sz;
MEMORY_BASIC_INFORMATION minfo;
VirtualQuery(&minfo, &minfo, sizeof(minfo));
sz = (size_t)os::current_stack_base() - (size_t)minfo.AllocationBase;
return sz;
}
struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
const struct tm* time_struct_ptr = localtime(clock);
if (time_struct_ptr != NULL) {
*res = *time_struct_ptr;
return res;
}
return NULL;
}
LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo);
// Thread start routine for all new Java threads
static unsigned __stdcall java_start(Thread* thread) {
// Try to randomize the cache line index of hot stack frames.
// This helps when threads of the same stack traces evict each other's
// cache lines. The threads can be either from the same JVM instance, or
// from different JVM instances. The benefit is especially true for
// processors with hyperthreading technology.
static int counter = 0;
int pid = os::current_process_id();
_alloca(((pid ^ counter++) & 7) * 128);
OSThread* osthr = thread->osthread();
assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
if (UseNUMA) {
int lgrp_id = os::numa_get_group_id();
if (lgrp_id != -1) {
thread->set_lgrp_id(lgrp_id);
}
}
// Install a win32 structured exception handler around every thread created
// by VM, so VM can genrate error dump when an exception occurred in non-
// Java thread (e.g. VM thread).
__try {
thread->run();
} __except(topLevelExceptionFilter(
(_EXCEPTION_POINTERS*)_exception_info())) {
// Nothing to do.
}
// One less thread is executing
// When the VMThread gets here, the main thread may have already exited
// which frees the CodeHeap containing the Atomic::add code
if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count);
}
return 0;
}
static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle, int thread_id) {
// Allocate the OSThread object
OSThread* osthread = new OSThread(NULL, NULL);
if (osthread == NULL) return NULL;
// Initialize support for Java interrupts
HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
if (interrupt_event == NULL) {
delete osthread;
return NULL;
}
osthread->set_interrupt_event(interrupt_event);
// Store info on the Win32 thread into the OSThread
osthread->set_thread_handle(thread_handle);
osthread->set_thread_id(thread_id);
if (UseNUMA) {
int lgrp_id = os::numa_get_group_id();
if (lgrp_id != -1) {
thread->set_lgrp_id(lgrp_id);
}
}
// Initial thread state is INITIALIZED, not SUSPENDED
osthread->set_state(INITIALIZED);
return osthread;
}
bool os::create_attached_thread(JavaThread* thread) {
#ifdef ASSERT
thread->verify_not_published();
#endif
HANDLE thread_h;
if (!DuplicateHandle(main_process, GetCurrentThread(), GetCurrentProcess(),
&thread_h, THREAD_ALL_ACCESS, false, 0)) {
fatal("DuplicateHandle failed\n");
}
OSThread* osthread = create_os_thread(thread, thread_h,
(int)current_thread_id());
if (osthread == NULL) {
return false;
}
// Initial thread state is RUNNABLE
osthread->set_state(RUNNABLE);
thread->set_osthread(osthread);
return true;
}
bool os::create_main_thread(JavaThread* thread) {
#ifdef ASSERT
thread->verify_not_published();
#endif
if (_starting_thread == NULL) {
_starting_thread = create_os_thread(thread, main_thread, main_thread_id);
if (_starting_thread == NULL) {
return false;
}
}
// The primordial thread is runnable from the start)
_starting_thread->set_state(RUNNABLE);
thread->set_osthread(_starting_thread);
return true;
}
// Allocate and initialize a new OSThread
bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
unsigned thread_id;
// Allocate the OSThread object
OSThread* osthread = new OSThread(NULL, NULL);
if (osthread == NULL) {
return false;
}
// Initialize support for Java interrupts
HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
if (interrupt_event == NULL) {
delete osthread;
return NULL;
}
osthread->set_interrupt_event(interrupt_event);
osthread->set_interrupted(false);
thread->set_osthread(osthread);
if (stack_size == 0) {
switch (thr_type) {
case os::java_thread:
// Java threads use ThreadStackSize which default value can be changed with the flag -Xss
if (JavaThread::stack_size_at_create() > 0)
stack_size = JavaThread::stack_size_at_create();
break;
case os::compiler_thread:
if (CompilerThreadStackSize > 0) {
stack_size = (size_t)(CompilerThreadStackSize * K);
break;
} // else fall through:
// use VMThreadStackSize if CompilerThreadStackSize is not defined
case os::vm_thread:
case os::pgc_thread:
case os::cgc_thread:
case os::watcher_thread:
if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
break;
}
}
// Create the Win32 thread
//
// Contrary to what MSDN document says, "stack_size" in _beginthreadex()
// does not specify stack size. Instead, it specifies the size of
// initially committed space. The stack size is determined by
// PE header in the executable. If the committed "stack_size" is larger
// than default value in the PE header, the stack is rounded up to the
// nearest multiple of 1MB. For example if the launcher has default
// stack size of 320k, specifying any size less than 320k does not
// affect the actual stack size at all, it only affects the initial
// commitment. On the other hand, specifying 'stack_size' larger than
// default value may cause significant increase in memory usage, because
// not only the stack space will be rounded up to MB, but also the
// entire space is committed upfront.
//
// Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION'
// for CreateThread() that can treat 'stack_size' as stack size. However we
// are not supposed to call CreateThread() directly according to MSDN
// document because JVM uses C runtime library. The good news is that the
// flag appears to work with _beginthredex() as well.
#ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
#define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000)
#endif
HANDLE thread_handle =
(HANDLE)_beginthreadex(NULL,
(unsigned)stack_size,
(unsigned (__stdcall *)(void*)) java_start,
thread,
CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
&thread_id);
if (thread_handle == NULL) {
// perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again
// without the flag.
thread_handle =
(HANDLE)_beginthreadex(NULL,
(unsigned)stack_size,
(unsigned (__stdcall *)(void*)) java_start,
thread,
CREATE_SUSPENDED,
&thread_id);
}
if (thread_handle == NULL) {
// Need to clean up stuff we've allocated so far
CloseHandle(osthread->interrupt_event());
thread->set_osthread(NULL);
delete osthread;
return NULL;
}
Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count);
// Store info on the Win32 thread into the OSThread
osthread->set_thread_handle(thread_handle);
osthread->set_thread_id(thread_id);
// Initial thread state is INITIALIZED, not SUSPENDED
osthread->set_state(INITIALIZED);
// The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
return true;
}
// Free Win32 resources related to the OSThread
void os::free_thread(OSThread* osthread) {
assert(osthread != NULL, "osthread not set");
CloseHandle(osthread->thread_handle());
CloseHandle(osthread->interrupt_event());
delete osthread;
}
static int has_performance_count = 0;
static jlong first_filetime;
static jlong initial_performance_count;
static jlong performance_frequency;
jlong as_long(LARGE_INTEGER x) {
jlong result = 0; // initialization to avoid warning
set_high(&result, x.HighPart);
set_low(&result, x.LowPart);
return result;
}
jlong os::elapsed_counter() {
LARGE_INTEGER count;
if (has_performance_count) {
QueryPerformanceCounter(&count);
return as_long(count) - initial_performance_count;
} else {
FILETIME wt;
GetSystemTimeAsFileTime(&wt);
return (jlong_from(wt.dwHighDateTime, wt.dwLowDateTime) - first_filetime);
}
}
jlong os::elapsed_frequency() {
if (has_performance_count) {
return performance_frequency;
} else {
// the FILETIME time is the number of 100-nanosecond intervals since January 1,1601.
return 10000000;
}
}
julong os::available_memory() {
return win32::available_memory();
}
julong os::win32::available_memory() {
// Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
// value if total memory is larger than 4GB
MEMORYSTATUSEX ms;
ms.dwLength = sizeof(ms);
GlobalMemoryStatusEx(&ms);
return (julong)ms.ullAvailPhys;
}
julong os::physical_memory() {
return win32::physical_memory();
}
bool os::has_allocatable_memory_limit(julong* limit) {
MEMORYSTATUSEX ms;
ms.dwLength = sizeof(ms);
GlobalMemoryStatusEx(&ms);
#ifdef _LP64
*limit = (julong)ms.ullAvailVirtual;
return true;
#else
// Limit to 1400m because of the 2gb address space wall
*limit = MIN2((julong)1400*M, (julong)ms.ullAvailVirtual);
return true;
#endif
}
// VC6 lacks DWORD_PTR
#if _MSC_VER < 1300
typedef UINT_PTR DWORD_PTR;
#endif
int os::active_processor_count() {
// User has overridden the number of active processors
if (ActiveProcessorCount > 0) {
if (PrintActiveCpus) {
tty->print_cr("active_processor_count: "
"active processor count set by user : %d",
ActiveProcessorCount);
}
return ActiveProcessorCount;
}
DWORD_PTR lpProcessAffinityMask = 0;
DWORD_PTR lpSystemAffinityMask = 0;
int proc_count = processor_count();
if (proc_count <= sizeof(UINT_PTR) * BitsPerByte &&
GetProcessAffinityMask(GetCurrentProcess(), &lpProcessAffinityMask, &lpSystemAffinityMask)) {
// Nof active processors is number of bits in process affinity mask
int bitcount = 0;
while (lpProcessAffinityMask != 0) {
lpProcessAffinityMask = lpProcessAffinityMask & (lpProcessAffinityMask-1);
bitcount++;
}
return bitcount;
} else {
return proc_count;
}
}
void os::set_native_thread_name(const char *name) {
// See: http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
//
// Note that unfortunately this only works if the process
// is already attached to a debugger; debugger must observe
// the exception below to show the correct name.
const DWORD MS_VC_EXCEPTION = 0x406D1388;
struct {
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in user addr space)
DWORD dwThreadID; // thread ID (-1=caller thread)
DWORD dwFlags; // reserved for future use, must be zero
} info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = -1;
info.dwFlags = 0;
__try {
RaiseException (MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(DWORD), (const ULONG_PTR*)&info );
} __except(EXCEPTION_CONTINUE_EXECUTION) {}
}
bool os::distribute_processes(uint length, uint* distribution) {
// Not yet implemented.
return false;
}
bool os::bind_to_processor(uint processor_id) {
// Not yet implemented.
return false;
}
static void initialize_performance_counter() {
LARGE_INTEGER count;
if (QueryPerformanceFrequency(&count)) {
has_performance_count = 1;
performance_frequency = as_long(count);
QueryPerformanceCounter(&count);
initial_performance_count = as_long(count);
} else {
has_performance_count = 0;
FILETIME wt;
GetSystemTimeAsFileTime(&wt);
first_filetime = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
}
}
double os::elapsedTime() {
return (double) elapsed_counter() / (double) elapsed_frequency();
}
// Windows format:
// The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
// Java format:
// Java standards require the number of milliseconds since 1/1/1970
// Constant offset - calculated using offset()
static jlong _offset = 116444736000000000;
// Fake time counter for reproducible results when debugging
static jlong fake_time = 0;
#ifdef ASSERT
// Just to be safe, recalculate the offset in debug mode
static jlong _calculated_offset = 0;
static int _has_calculated_offset = 0;
jlong offset() {
if (_has_calculated_offset) return _calculated_offset;
SYSTEMTIME java_origin;
java_origin.wYear = 1970;
java_origin.wMonth = 1;
java_origin.wDayOfWeek = 0; // ignored
java_origin.wDay = 1;
java_origin.wHour = 0;
java_origin.wMinute = 0;
java_origin.wSecond = 0;
java_origin.wMilliseconds = 0;
FILETIME jot;
if (!SystemTimeToFileTime(&java_origin, &jot)) {
fatal(err_msg("Error = %d\nWindows error", GetLastError()));
}
_calculated_offset = jlong_from(jot.dwHighDateTime, jot.dwLowDateTime);
_has_calculated_offset = 1;
assert(_calculated_offset == _offset, "Calculated and constant time offsets must be equal");
return _calculated_offset;
}
#else
jlong offset() {
return _offset;
}
#endif
jlong windows_to_java_time(FILETIME wt) {
jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
return (a - offset()) / 10000;
}
FILETIME java_to_windows_time(jlong l) {
jlong a = (l * 10000) + offset();
FILETIME result;
result.dwHighDateTime = high(a);
result.dwLowDateTime = low(a);
return result;
}
bool os::supports_vtime() { return true; }
bool os::enable_vtime() { return false; }
bool os::vtime_enabled() { return false; }
double os::elapsedVTime() {
FILETIME created;
FILETIME exited;
FILETIME kernel;
FILETIME user;
if (GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user) != 0) {
// the resolution of windows_to_java_time() should be sufficient (ms)
return (double) (windows_to_java_time(kernel) + windows_to_java_time(user)) / MILLIUNITS;
} else {
return elapsedTime();
}
}
jlong os::javaTimeMillis() {
if (UseFakeTimers) {
return fake_time++;
} else {
FILETIME wt;
GetSystemTimeAsFileTime(&wt);
return windows_to_java_time(wt);
}
}
jlong os::javaTimeNanos() {
if (!has_performance_count) {
return javaTimeMillis() * NANOSECS_PER_MILLISEC; // the best we can do.
} else {
LARGE_INTEGER current_count;
QueryPerformanceCounter(¤t_count);
double current = as_long(current_count);
double freq = performance_frequency;
jlong time = (jlong)((current/freq) * NANOSECS_PER_SEC);
return time;
}
}
void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
if (!has_performance_count) {
// javaTimeMillis() doesn't have much percision,
// but it is not going to wrap -- so all 64 bits
info_ptr->max_value = ALL_64_BITS;
// this is a wall clock timer, so may skip
info_ptr->may_skip_backward = true;
info_ptr->may_skip_forward = true;
} else {
jlong freq = performance_frequency;
if (freq < NANOSECS_PER_SEC) {
// the performance counter is 64 bits and we will
// be multiplying it -- so no wrap in 64 bits
info_ptr->max_value = ALL_64_BITS;
} else if (freq > NANOSECS_PER_SEC) {
// use the max value the counter can reach to
// determine the max value which could be returned
julong max_counter = (julong)ALL_64_BITS;
info_ptr->max_value = (jlong)(max_counter / (freq / NANOSECS_PER_SEC));
} else {
// the performance counter is 64 bits and we will
// be using it directly -- so no wrap in 64 bits
info_ptr->max_value = ALL_64_BITS;
}
// using a counter, so no skipping
info_ptr->may_skip_backward = false;
info_ptr->may_skip_forward = false;
}
info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
}
char* os::local_time_string(char *buf, size_t buflen) {
SYSTEMTIME st;
GetLocalTime(&st);
jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
bool os::getTimesSecs(double* process_real_time,
double* process_user_time,
double* process_system_time) {
HANDLE h_process = GetCurrentProcess();
FILETIME create_time, exit_time, kernel_time, user_time;
BOOL result = GetProcessTimes(h_process,
&create_time,
&exit_time,
&kernel_time,
&user_time);
if (result != 0) {
FILETIME wt;
GetSystemTimeAsFileTime(&wt);
jlong rtc_millis = windows_to_java_time(wt);
jlong user_millis = windows_to_java_time(user_time);
jlong system_millis = windows_to_java_time(kernel_time);
*process_real_time = ((double) rtc_millis) / ((double) MILLIUNITS);
*process_user_time = ((double) user_millis) / ((double) MILLIUNITS);
*process_system_time = ((double) system_millis) / ((double) MILLIUNITS);
return true;
} else {
return false;
}
}
void os::shutdown() {
// allow PerfMemory to attempt cleanup of any persistent resources
perfMemory_exit();
// flush buffered output, finish log files
ostream_abort();
// Check for abort hook
abort_hook_t abort_hook = Arguments::abort_hook();
if (abort_hook != NULL) {
abort_hook();
}
}
static BOOL (WINAPI *_MiniDumpWriteDump) ( HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION,
PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION);
void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize) {
HINSTANCE dbghelp;
EXCEPTION_POINTERS ep;
MINIDUMP_EXCEPTION_INFORMATION mei;
MINIDUMP_EXCEPTION_INFORMATION* pmei;
HANDLE hProcess = GetCurrentProcess();
DWORD processId = GetCurrentProcessId();
HANDLE dumpFile;
MINIDUMP_TYPE dumpType;
static const char* cwd;
// Default is to always create dump for debug builds, on product builds only dump on server versions of Windows.
#ifndef ASSERT
// If running on a client version of Windows and user has not explicitly enabled dumping
if (!os::win32::is_windows_server() && !CreateMinidumpOnCrash) {
VMError::report_coredump_status("Minidumps are not enabled by default on client versions of Windows", false);
return;
// If running on a server version of Windows and user has explictly disabled dumping