1 /* 2 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 // Must be at least Windows 2000 or XP to use VectoredExceptions and IsDebuggerPresent 26 #define _WIN32_WINNT 0x500 27 28 // no precompiled headers 29 #include "classfile/classLoader.hpp" 30 #include "classfile/systemDictionary.hpp" 31 #include "classfile/vmSymbols.hpp" 32 #include "code/icBuffer.hpp" 33 #include "code/vtableStubs.hpp" 34 #include "compiler/compileBroker.hpp" 35 #include "interpreter/interpreter.hpp" 36 #include "jvm_windows.h" 37 #include "memory/allocation.inline.hpp" 38 #include "memory/filemap.hpp" 39 #include "mutex_windows.inline.hpp" 40 #include "oops/oop.inline.hpp" 41 #include "os_share_windows.hpp" 42 #include "prims/jniFastGetField.hpp" 43 #include "prims/jvm.h" 44 #include "prims/jvm_misc.hpp" 45 #include "runtime/arguments.hpp" 46 #include "runtime/extendedPC.hpp" 47 #include "runtime/globals.hpp" 48 #include "runtime/interfaceSupport.hpp" 49 #include "runtime/java.hpp" 50 #include "runtime/javaCalls.hpp" 51 #include "runtime/mutexLocker.hpp" 52 #include "runtime/objectMonitor.hpp" 53 #include "runtime/osThread.hpp" 54 #include "runtime/perfMemory.hpp" 55 #include "runtime/sharedRuntime.hpp" 56 #include "runtime/statSampler.hpp" 57 #include "runtime/stubRoutines.hpp" 58 #include "runtime/threadCritical.hpp" 59 #include "runtime/timer.hpp" 60 #include "services/attachListener.hpp" 61 #include "services/runtimeService.hpp" 62 #include "thread_windows.inline.hpp" 63 #include "utilities/decoder.hpp" 64 #include "utilities/defaultStream.hpp" 65 #include "utilities/events.hpp" 66 #include "utilities/growableArray.hpp" 67 #include "utilities/vmError.hpp" 68 #ifdef TARGET_ARCH_x86 69 # include "assembler_x86.inline.hpp" 70 # include "nativeInst_x86.hpp" 71 #endif 72 #ifdef COMPILER1 73 #include "c1/c1_Runtime1.hpp" 74 #endif 75 #ifdef COMPILER2 76 #include "opto/runtime.hpp" 77 #endif 78 79 #ifdef _DEBUG 80 #include <crtdbg.h> 81 #endif 82 83 84 #include <windows.h> 85 #include <sys/types.h> 86 #include <sys/stat.h> 87 #include <sys/timeb.h> 88 #include <objidl.h> 89 #include <shlobj.h> 90 91 #include <malloc.h> 92 #include <signal.h> 93 #include <direct.h> 94 #include <errno.h> 95 #include <fcntl.h> 96 #include <io.h> 97 #include <process.h> // For _beginthreadex(), _endthreadex() 98 #include <imagehlp.h> // For os::dll_address_to_function_name 99 100 /* for enumerating dll libraries */ 101 #include <vdmdbg.h> 102 103 // for timer info max values which include all bits 104 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 105 106 // For DLL loading/load error detection 107 // Values of PE COFF 108 #define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c 109 #define IMAGE_FILE_SIGNATURE_LENGTH 4 110 111 static HANDLE main_process; 112 static HANDLE main_thread; 113 static int main_thread_id; 114 115 static FILETIME process_creation_time; 116 static FILETIME process_exit_time; 117 static FILETIME process_user_time; 118 static FILETIME process_kernel_time; 119 120 #ifdef _WIN64 121 PVOID topLevelVectoredExceptionHandler = NULL; 122 #endif 123 124 #ifdef _M_IA64 125 #define __CPU__ ia64 126 #elif _M_AMD64 127 #define __CPU__ amd64 128 #else 129 #define __CPU__ i486 130 #endif 131 132 // save DLL module handle, used by GetModuleFileName 133 134 HINSTANCE vm_lib_handle; 135 136 BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) { 137 switch (reason) { 138 case DLL_PROCESS_ATTACH: 139 vm_lib_handle = hinst; 140 if(ForceTimeHighResolution) 141 timeBeginPeriod(1L); 142 break; 143 case DLL_PROCESS_DETACH: 144 if(ForceTimeHighResolution) 145 timeEndPeriod(1L); 146 #ifdef _WIN64 147 if (topLevelVectoredExceptionHandler != NULL) { 148 RemoveVectoredExceptionHandler(topLevelVectoredExceptionHandler); 149 topLevelVectoredExceptionHandler = NULL; 150 } 151 #endif 152 break; 153 default: 154 break; 155 } 156 return true; 157 } 158 159 static inline double fileTimeAsDouble(FILETIME* time) { 160 const double high = (double) ((unsigned int) ~0); 161 const double split = 10000000.0; 162 double result = (time->dwLowDateTime / split) + 163 time->dwHighDateTime * (high/split); 164 return result; 165 } 166 167 // Implementation of os 168 169 bool os::getenv(const char* name, char* buffer, int len) { 170 int result = GetEnvironmentVariable(name, buffer, len); 171 return result > 0 && result < len; 172 } 173 174 175 // No setuid programs under Windows. 176 bool os::have_special_privileges() { 177 return false; 178 } 179 180 181 // This method is a periodic task to check for misbehaving JNI applications 182 // under CheckJNI, we can add any periodic checks here. 183 // For Windows at the moment does nothing 184 void os::run_periodic_checks() { 185 return; 186 } 187 188 #ifndef _WIN64 189 // previous UnhandledExceptionFilter, if there is one 190 static LPTOP_LEVEL_EXCEPTION_FILTER prev_uef_handler = NULL; 191 192 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo); 193 #endif 194 void os::init_system_properties_values() { 195 /* sysclasspath, java_home, dll_dir */ 196 { 197 char *home_path; 198 char *dll_path; 199 char *pslash; 200 char *bin = "\\bin"; 201 char home_dir[MAX_PATH]; 202 203 if (!getenv("_ALT_JAVA_HOME_DIR", home_dir, MAX_PATH)) { 204 os::jvm_path(home_dir, sizeof(home_dir)); 205 // Found the full path to jvm[_g].dll. 206 // Now cut the path to <java_home>/jre if we can. 207 *(strrchr(home_dir, '\\')) = '\0'; /* get rid of \jvm.dll */ 208 pslash = strrchr(home_dir, '\\'); 209 if (pslash != NULL) { 210 *pslash = '\0'; /* get rid of \{client|server} */ 211 pslash = strrchr(home_dir, '\\'); 212 if (pslash != NULL) 213 *pslash = '\0'; /* get rid of \bin */ 214 } 215 } 216 217 home_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + 1); 218 if (home_path == NULL) 219 return; 220 strcpy(home_path, home_dir); 221 Arguments::set_java_home(home_path); 222 223 dll_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + strlen(bin) + 1); 224 if (dll_path == NULL) 225 return; 226 strcpy(dll_path, home_dir); 227 strcat(dll_path, bin); 228 Arguments::set_dll_dir(dll_path); 229 230 if (!set_boot_path('\\', ';')) 231 return; 232 } 233 234 /* library_path */ 235 #define EXT_DIR "\\lib\\ext" 236 #define BIN_DIR "\\bin" 237 #define PACKAGE_DIR "\\Sun\\Java" 238 { 239 /* Win32 library search order (See the documentation for LoadLibrary): 240 * 241 * 1. The directory from which application is loaded. 242 * 2. The system wide Java Extensions directory (Java only) 243 * 3. System directory (GetSystemDirectory) 244 * 4. Windows directory (GetWindowsDirectory) 245 * 5. The PATH environment variable 246 * 6. The current directory 247 */ 248 249 char *library_path; 250 char tmp[MAX_PATH]; 251 char *path_str = ::getenv("PATH"); 252 253 library_path = NEW_C_HEAP_ARRAY(char, MAX_PATH * 5 + sizeof(PACKAGE_DIR) + 254 sizeof(BIN_DIR) + (path_str ? strlen(path_str) : 0) + 10); 255 256 library_path[0] = '\0'; 257 258 GetModuleFileName(NULL, tmp, sizeof(tmp)); 259 *(strrchr(tmp, '\\')) = '\0'; 260 strcat(library_path, tmp); 261 262 GetWindowsDirectory(tmp, sizeof(tmp)); 263 strcat(library_path, ";"); 264 strcat(library_path, tmp); 265 strcat(library_path, PACKAGE_DIR BIN_DIR); 266 267 GetSystemDirectory(tmp, sizeof(tmp)); 268 strcat(library_path, ";"); 269 strcat(library_path, tmp); 270 271 GetWindowsDirectory(tmp, sizeof(tmp)); 272 strcat(library_path, ";"); 273 strcat(library_path, tmp); 274 275 if (path_str) { 276 strcat(library_path, ";"); 277 strcat(library_path, path_str); 278 } 279 280 strcat(library_path, ";."); 281 282 Arguments::set_library_path(library_path); 283 FREE_C_HEAP_ARRAY(char, library_path); 284 } 285 286 /* Default extensions directory */ 287 { 288 char path[MAX_PATH]; 289 char buf[2 * MAX_PATH + 2 * sizeof(EXT_DIR) + sizeof(PACKAGE_DIR) + 1]; 290 GetWindowsDirectory(path, MAX_PATH); 291 sprintf(buf, "%s%s;%s%s%s", Arguments::get_java_home(), EXT_DIR, 292 path, PACKAGE_DIR, EXT_DIR); 293 Arguments::set_ext_dirs(buf); 294 } 295 #undef EXT_DIR 296 #undef BIN_DIR 297 #undef PACKAGE_DIR 298 299 /* Default endorsed standards directory. */ 300 { 301 #define ENDORSED_DIR "\\lib\\endorsed" 302 size_t len = strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR); 303 char * buf = NEW_C_HEAP_ARRAY(char, len); 304 sprintf(buf, "%s%s", Arguments::get_java_home(), ENDORSED_DIR); 305 Arguments::set_endorsed_dirs(buf); 306 #undef ENDORSED_DIR 307 } 308 309 #ifndef _WIN64 310 // set our UnhandledExceptionFilter and save any previous one 311 prev_uef_handler = SetUnhandledExceptionFilter(Handle_FLT_Exception); 312 #endif 313 314 // Done 315 return; 316 } 317 318 void os::breakpoint() { 319 DebugBreak(); 320 } 321 322 // Invoked from the BREAKPOINT Macro 323 extern "C" void breakpoint() { 324 os::breakpoint(); 325 } 326 327 // os::current_stack_base() 328 // 329 // Returns the base of the stack, which is the stack's 330 // starting address. This function must be called 331 // while running on the stack of the thread being queried. 332 333 address os::current_stack_base() { 334 MEMORY_BASIC_INFORMATION minfo; 335 address stack_bottom; 336 size_t stack_size; 337 338 VirtualQuery(&minfo, &minfo, sizeof(minfo)); 339 stack_bottom = (address)minfo.AllocationBase; 340 stack_size = minfo.RegionSize; 341 342 // Add up the sizes of all the regions with the same 343 // AllocationBase. 344 while( 1 ) 345 { 346 VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo)); 347 if ( stack_bottom == (address)minfo.AllocationBase ) 348 stack_size += minfo.RegionSize; 349 else 350 break; 351 } 352 353 #ifdef _M_IA64 354 // IA64 has memory and register stacks 355 stack_size = stack_size / 2; 356 #endif 357 return stack_bottom + stack_size; 358 } 359 360 size_t os::current_stack_size() { 361 size_t sz; 362 MEMORY_BASIC_INFORMATION minfo; 363 VirtualQuery(&minfo, &minfo, sizeof(minfo)); 364 sz = (size_t)os::current_stack_base() - (size_t)minfo.AllocationBase; 365 return sz; 366 } 367 368 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 369 const struct tm* time_struct_ptr = localtime(clock); 370 if (time_struct_ptr != NULL) { 371 *res = *time_struct_ptr; 372 return res; 373 } 374 return NULL; 375 } 376 377 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo); 378 379 // Thread start routine for all new Java threads 380 static unsigned __stdcall java_start(Thread* thread) { 381 // Try to randomize the cache line index of hot stack frames. 382 // This helps when threads of the same stack traces evict each other's 383 // cache lines. The threads can be either from the same JVM instance, or 384 // from different JVM instances. The benefit is especially true for 385 // processors with hyperthreading technology. 386 static int counter = 0; 387 int pid = os::current_process_id(); 388 _alloca(((pid ^ counter++) & 7) * 128); 389 390 OSThread* osthr = thread->osthread(); 391 assert(osthr->get_state() == RUNNABLE, "invalid os thread state"); 392 393 if (UseNUMA) { 394 int lgrp_id = os::numa_get_group_id(); 395 if (lgrp_id != -1) { 396 thread->set_lgrp_id(lgrp_id); 397 } 398 } 399 400 401 if (UseVectoredExceptions) { 402 // If we are using vectored exception we don't need to set a SEH 403 thread->run(); 404 } 405 else { 406 // Install a win32 structured exception handler around every thread created 407 // by VM, so VM can genrate error dump when an exception occurred in non- 408 // Java thread (e.g. VM thread). 409 __try { 410 thread->run(); 411 } __except(topLevelExceptionFilter( 412 (_EXCEPTION_POINTERS*)_exception_info())) { 413 // Nothing to do. 414 } 415 } 416 417 // One less thread is executing 418 // When the VMThread gets here, the main thread may have already exited 419 // which frees the CodeHeap containing the Atomic::add code 420 if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) { 421 Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count); 422 } 423 424 return 0; 425 } 426 427 static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle, int thread_id) { 428 // Allocate the OSThread object 429 OSThread* osthread = new OSThread(NULL, NULL); 430 if (osthread == NULL) return NULL; 431 432 // Initialize support for Java interrupts 433 HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL); 434 if (interrupt_event == NULL) { 435 delete osthread; 436 return NULL; 437 } 438 osthread->set_interrupt_event(interrupt_event); 439 440 // Store info on the Win32 thread into the OSThread 441 osthread->set_thread_handle(thread_handle); 442 osthread->set_thread_id(thread_id); 443 444 if (UseNUMA) { 445 int lgrp_id = os::numa_get_group_id(); 446 if (lgrp_id != -1) { 447 thread->set_lgrp_id(lgrp_id); 448 } 449 } 450 451 // Initial thread state is INITIALIZED, not SUSPENDED 452 osthread->set_state(INITIALIZED); 453 454 return osthread; 455 } 456 457 458 bool os::create_attached_thread(JavaThread* thread) { 459 #ifdef ASSERT 460 thread->verify_not_published(); 461 #endif 462 HANDLE thread_h; 463 if (!DuplicateHandle(main_process, GetCurrentThread(), GetCurrentProcess(), 464 &thread_h, THREAD_ALL_ACCESS, false, 0)) { 465 fatal("DuplicateHandle failed\n"); 466 } 467 OSThread* osthread = create_os_thread(thread, thread_h, 468 (int)current_thread_id()); 469 if (osthread == NULL) { 470 return false; 471 } 472 473 // Initial thread state is RUNNABLE 474 osthread->set_state(RUNNABLE); 475 476 thread->set_osthread(osthread); 477 return true; 478 } 479 480 bool os::create_main_thread(JavaThread* thread) { 481 #ifdef ASSERT 482 thread->verify_not_published(); 483 #endif 484 if (_starting_thread == NULL) { 485 _starting_thread = create_os_thread(thread, main_thread, main_thread_id); 486 if (_starting_thread == NULL) { 487 return false; 488 } 489 } 490 491 // The primordial thread is runnable from the start) 492 _starting_thread->set_state(RUNNABLE); 493 494 thread->set_osthread(_starting_thread); 495 return true; 496 } 497 498 // Allocate and initialize a new OSThread 499 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 500 unsigned thread_id; 501 502 // Allocate the OSThread object 503 OSThread* osthread = new OSThread(NULL, NULL); 504 if (osthread == NULL) { 505 return false; 506 } 507 508 // Initialize support for Java interrupts 509 HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL); 510 if (interrupt_event == NULL) { 511 delete osthread; 512 return NULL; 513 } 514 osthread->set_interrupt_event(interrupt_event); 515 osthread->set_interrupted(false); 516 517 thread->set_osthread(osthread); 518 519 if (stack_size == 0) { 520 switch (thr_type) { 521 case os::java_thread: 522 // Java threads use ThreadStackSize which default value can be changed with the flag -Xss 523 if (JavaThread::stack_size_at_create() > 0) 524 stack_size = JavaThread::stack_size_at_create(); 525 break; 526 case os::compiler_thread: 527 if (CompilerThreadStackSize > 0) { 528 stack_size = (size_t)(CompilerThreadStackSize * K); 529 break; 530 } // else fall through: 531 // use VMThreadStackSize if CompilerThreadStackSize is not defined 532 case os::vm_thread: 533 case os::pgc_thread: 534 case os::cgc_thread: 535 case os::watcher_thread: 536 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 537 break; 538 } 539 } 540 541 // Create the Win32 thread 542 // 543 // Contrary to what MSDN document says, "stack_size" in _beginthreadex() 544 // does not specify stack size. Instead, it specifies the size of 545 // initially committed space. The stack size is determined by 546 // PE header in the executable. If the committed "stack_size" is larger 547 // than default value in the PE header, the stack is rounded up to the 548 // nearest multiple of 1MB. For example if the launcher has default 549 // stack size of 320k, specifying any size less than 320k does not 550 // affect the actual stack size at all, it only affects the initial 551 // commitment. On the other hand, specifying 'stack_size' larger than 552 // default value may cause significant increase in memory usage, because 553 // not only the stack space will be rounded up to MB, but also the 554 // entire space is committed upfront. 555 // 556 // Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION' 557 // for CreateThread() that can treat 'stack_size' as stack size. However we 558 // are not supposed to call CreateThread() directly according to MSDN 559 // document because JVM uses C runtime library. The good news is that the 560 // flag appears to work with _beginthredex() as well. 561 562 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION 563 #define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000) 564 #endif 565 566 HANDLE thread_handle = 567 (HANDLE)_beginthreadex(NULL, 568 (unsigned)stack_size, 569 (unsigned (__stdcall *)(void*)) java_start, 570 thread, 571 CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, 572 &thread_id); 573 if (thread_handle == NULL) { 574 // perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again 575 // without the flag. 576 thread_handle = 577 (HANDLE)_beginthreadex(NULL, 578 (unsigned)stack_size, 579 (unsigned (__stdcall *)(void*)) java_start, 580 thread, 581 CREATE_SUSPENDED, 582 &thread_id); 583 } 584 if (thread_handle == NULL) { 585 // Need to clean up stuff we've allocated so far 586 CloseHandle(osthread->interrupt_event()); 587 thread->set_osthread(NULL); 588 delete osthread; 589 return NULL; 590 } 591 592 Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count); 593 594 // Store info on the Win32 thread into the OSThread 595 osthread->set_thread_handle(thread_handle); 596 osthread->set_thread_id(thread_id); 597 598 // Initial thread state is INITIALIZED, not SUSPENDED 599 osthread->set_state(INITIALIZED); 600 601 // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain 602 return true; 603 } 604 605 606 // Free Win32 resources related to the OSThread 607 void os::free_thread(OSThread* osthread) { 608 assert(osthread != NULL, "osthread not set"); 609 CloseHandle(osthread->thread_handle()); 610 CloseHandle(osthread->interrupt_event()); 611 delete osthread; 612 } 613 614 615 static int has_performance_count = 0; 616 static jlong first_filetime; 617 static jlong initial_performance_count; 618 static jlong performance_frequency; 619 620 621 jlong as_long(LARGE_INTEGER x) { 622 jlong result = 0; // initialization to avoid warning 623 set_high(&result, x.HighPart); 624 set_low(&result, x.LowPart); 625 return result; 626 } 627 628 629 jlong os::elapsed_counter() { 630 LARGE_INTEGER count; 631 if (has_performance_count) { 632 QueryPerformanceCounter(&count); 633 return as_long(count) - initial_performance_count; 634 } else { 635 FILETIME wt; 636 GetSystemTimeAsFileTime(&wt); 637 return (jlong_from(wt.dwHighDateTime, wt.dwLowDateTime) - first_filetime); 638 } 639 } 640 641 642 jlong os::elapsed_frequency() { 643 if (has_performance_count) { 644 return performance_frequency; 645 } else { 646 // the FILETIME time is the number of 100-nanosecond intervals since January 1,1601. 647 return 10000000; 648 } 649 } 650 651 652 julong os::available_memory() { 653 return win32::available_memory(); 654 } 655 656 julong os::win32::available_memory() { 657 // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect 658 // value if total memory is larger than 4GB 659 MEMORYSTATUSEX ms; 660 ms.dwLength = sizeof(ms); 661 GlobalMemoryStatusEx(&ms); 662 663 return (julong)ms.ullAvailPhys; 664 } 665 666 julong os::physical_memory() { 667 return win32::physical_memory(); 668 } 669 670 julong os::allocatable_physical_memory(julong size) { 671 #ifdef _LP64 672 return size; 673 #else 674 // Limit to 1400m because of the 2gb address space wall 675 return MIN2(size, (julong)1400*M); 676 #endif 677 } 678 679 // VC6 lacks DWORD_PTR 680 #if _MSC_VER < 1300 681 typedef UINT_PTR DWORD_PTR; 682 #endif 683 684 int os::active_processor_count() { 685 DWORD_PTR lpProcessAffinityMask = 0; 686 DWORD_PTR lpSystemAffinityMask = 0; 687 int proc_count = processor_count(); 688 if (proc_count <= sizeof(UINT_PTR) * BitsPerByte && 689 GetProcessAffinityMask(GetCurrentProcess(), &lpProcessAffinityMask, &lpSystemAffinityMask)) { 690 // Nof active processors is number of bits in process affinity mask 691 int bitcount = 0; 692 while (lpProcessAffinityMask != 0) { 693 lpProcessAffinityMask = lpProcessAffinityMask & (lpProcessAffinityMask-1); 694 bitcount++; 695 } 696 return bitcount; 697 } else { 698 return proc_count; 699 } 700 } 701 702 void os::set_native_thread_name(const char *name) { 703 // Not yet implemented. 704 return; 705 } 706 707 bool os::distribute_processes(uint length, uint* distribution) { 708 // Not yet implemented. 709 return false; 710 } 711 712 bool os::bind_to_processor(uint processor_id) { 713 // Not yet implemented. 714 return false; 715 } 716 717 static void initialize_performance_counter() { 718 LARGE_INTEGER count; 719 if (QueryPerformanceFrequency(&count)) { 720 has_performance_count = 1; 721 performance_frequency = as_long(count); 722 QueryPerformanceCounter(&count); 723 initial_performance_count = as_long(count); 724 } else { 725 has_performance_count = 0; 726 FILETIME wt; 727 GetSystemTimeAsFileTime(&wt); 728 first_filetime = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime); 729 } 730 } 731 732 733 double os::elapsedTime() { 734 return (double) elapsed_counter() / (double) elapsed_frequency(); 735 } 736 737 738 // Windows format: 739 // The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601. 740 // Java format: 741 // Java standards require the number of milliseconds since 1/1/1970 742 743 // Constant offset - calculated using offset() 744 static jlong _offset = 116444736000000000; 745 // Fake time counter for reproducible results when debugging 746 static jlong fake_time = 0; 747 748 #ifdef ASSERT 749 // Just to be safe, recalculate the offset in debug mode 750 static jlong _calculated_offset = 0; 751 static int _has_calculated_offset = 0; 752 753 jlong offset() { 754 if (_has_calculated_offset) return _calculated_offset; 755 SYSTEMTIME java_origin; 756 java_origin.wYear = 1970; 757 java_origin.wMonth = 1; 758 java_origin.wDayOfWeek = 0; // ignored 759 java_origin.wDay = 1; 760 java_origin.wHour = 0; 761 java_origin.wMinute = 0; 762 java_origin.wSecond = 0; 763 java_origin.wMilliseconds = 0; 764 FILETIME jot; 765 if (!SystemTimeToFileTime(&java_origin, &jot)) { 766 fatal(err_msg("Error = %d\nWindows error", GetLastError())); 767 } 768 _calculated_offset = jlong_from(jot.dwHighDateTime, jot.dwLowDateTime); 769 _has_calculated_offset = 1; 770 assert(_calculated_offset == _offset, "Calculated and constant time offsets must be equal"); 771 return _calculated_offset; 772 } 773 #else 774 jlong offset() { 775 return _offset; 776 } 777 #endif 778 779 jlong windows_to_java_time(FILETIME wt) { 780 jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime); 781 return (a - offset()) / 10000; 782 } 783 784 FILETIME java_to_windows_time(jlong l) { 785 jlong a = (l * 10000) + offset(); 786 FILETIME result; 787 result.dwHighDateTime = high(a); 788 result.dwLowDateTime = low(a); 789 return result; 790 } 791 792 // For now, we say that Windows does not support vtime. I have no idea 793 // whether it can actually be made to (DLD, 9/13/05). 794 795 bool os::supports_vtime() { return false; } 796 bool os::enable_vtime() { return false; } 797 bool os::vtime_enabled() { return false; } 798 double os::elapsedVTime() { 799 // better than nothing, but not much 800 return elapsedTime(); 801 } 802 803 jlong os::javaTimeMillis() { 804 if (UseFakeTimers) { 805 return fake_time++; 806 } else { 807 FILETIME wt; 808 GetSystemTimeAsFileTime(&wt); 809 return windows_to_java_time(wt); 810 } 811 } 812 813 jlong os::javaTimeNanos() { 814 if (!has_performance_count) { 815 return javaTimeMillis() * NANOSECS_PER_MILLISEC; // the best we can do. 816 } else { 817 LARGE_INTEGER current_count; 818 QueryPerformanceCounter(¤t_count); 819 double current = as_long(current_count); 820 double freq = performance_frequency; 821 jlong time = (jlong)((current/freq) * NANOSECS_PER_SEC); 822 return time; 823 } 824 } 825 826 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 827 if (!has_performance_count) { 828 // javaTimeMillis() doesn't have much percision, 829 // but it is not going to wrap -- so all 64 bits 830 info_ptr->max_value = ALL_64_BITS; 831 832 // this is a wall clock timer, so may skip 833 info_ptr->may_skip_backward = true; 834 info_ptr->may_skip_forward = true; 835 } else { 836 jlong freq = performance_frequency; 837 if (freq < NANOSECS_PER_SEC) { 838 // the performance counter is 64 bits and we will 839 // be multiplying it -- so no wrap in 64 bits 840 info_ptr->max_value = ALL_64_BITS; 841 } else if (freq > NANOSECS_PER_SEC) { 842 // use the max value the counter can reach to 843 // determine the max value which could be returned 844 julong max_counter = (julong)ALL_64_BITS; 845 info_ptr->max_value = (jlong)(max_counter / (freq / NANOSECS_PER_SEC)); 846 } else { 847 // the performance counter is 64 bits and we will 848 // be using it directly -- so no wrap in 64 bits 849 info_ptr->max_value = ALL_64_BITS; 850 } 851 852 // using a counter, so no skipping 853 info_ptr->may_skip_backward = false; 854 info_ptr->may_skip_forward = false; 855 } 856 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 857 } 858 859 char* os::local_time_string(char *buf, size_t buflen) { 860 SYSTEMTIME st; 861 GetLocalTime(&st); 862 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 863 st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); 864 return buf; 865 } 866 867 bool os::getTimesSecs(double* process_real_time, 868 double* process_user_time, 869 double* process_system_time) { 870 HANDLE h_process = GetCurrentProcess(); 871 FILETIME create_time, exit_time, kernel_time, user_time; 872 BOOL result = GetProcessTimes(h_process, 873 &create_time, 874 &exit_time, 875 &kernel_time, 876 &user_time); 877 if (result != 0) { 878 FILETIME wt; 879 GetSystemTimeAsFileTime(&wt); 880 jlong rtc_millis = windows_to_java_time(wt); 881 jlong user_millis = windows_to_java_time(user_time); 882 jlong system_millis = windows_to_java_time(kernel_time); 883 *process_real_time = ((double) rtc_millis) / ((double) MILLIUNITS); 884 *process_user_time = ((double) user_millis) / ((double) MILLIUNITS); 885 *process_system_time = ((double) system_millis) / ((double) MILLIUNITS); 886 return true; 887 } else { 888 return false; 889 } 890 } 891 892 void os::shutdown() { 893 894 // allow PerfMemory to attempt cleanup of any persistent resources 895 perfMemory_exit(); 896 897 // flush buffered output, finish log files 898 ostream_abort(); 899 900 // Check for abort hook 901 abort_hook_t abort_hook = Arguments::abort_hook(); 902 if (abort_hook != NULL) { 903 abort_hook(); 904 } 905 } 906 907 908 static BOOL (WINAPI *_MiniDumpWriteDump) ( HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION, 909 PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION); 910 911 void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize) { 912 HINSTANCE dbghelp; 913 EXCEPTION_POINTERS ep; 914 MINIDUMP_EXCEPTION_INFORMATION mei; 915 MINIDUMP_EXCEPTION_INFORMATION* pmei; 916 917 HANDLE hProcess = GetCurrentProcess(); 918 DWORD processId = GetCurrentProcessId(); 919 HANDLE dumpFile; 920 MINIDUMP_TYPE dumpType; 921 static const char* cwd; 922 923 // If running on a client version of Windows and user has not explicitly enabled dumping 924 if (!os::win32::is_windows_server() && !CreateMinidumpOnCrash) { 925 VMError::report_coredump_status("Minidumps are not enabled by default on client versions of Windows", false); 926 return; 927 // If running on a server version of Windows and user has explictly disabled dumping 928 } else if (os::win32::is_windows_server() && !FLAG_IS_DEFAULT(CreateMinidumpOnCrash) && !CreateMinidumpOnCrash) { 929 VMError::report_coredump_status("Minidump has been disabled from the command line", false); 930 return; 931 } 932 933 dbghelp = os::win32::load_Windows_dll("DBGHELP.DLL", NULL, 0); 934 935 if (dbghelp == NULL) { 936 VMError::report_coredump_status("Failed to load dbghelp.dll", false); 937 return; 938 } 939 940 _MiniDumpWriteDump = CAST_TO_FN_PTR( 941 BOOL(WINAPI *)( HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION, 942 PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION), 943 GetProcAddress(dbghelp, "MiniDumpWriteDump")); 944 945 if (_MiniDumpWriteDump == NULL) { 946 VMError::report_coredump_status("Failed to find MiniDumpWriteDump() in module dbghelp.dll", false); 947 return; 948 } 949 950 dumpType = (MINIDUMP_TYPE)(MiniDumpWithFullMemory | MiniDumpWithHandleData); 951 952 // Older versions of dbghelp.h doesn't contain all the dumptypes we want, dbghelp.h with 953 // API_VERSION_NUMBER 11 or higher contains the ones we want though 954 #if API_VERSION_NUMBER >= 11 955 dumpType = (MINIDUMP_TYPE)(dumpType | MiniDumpWithFullMemoryInfo | MiniDumpWithThreadInfo | 956 MiniDumpWithUnloadedModules); 957 #endif 958 959 cwd = get_current_directory(NULL, 0); 960 jio_snprintf(buffer, bufferSize, "%s\\hs_err_pid%u.mdmp",cwd, current_process_id()); 961 dumpFile = CreateFile(buffer, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 962 963 if (dumpFile == INVALID_HANDLE_VALUE) { 964 VMError::report_coredump_status("Failed to create file for dumping", false); 965 return; 966 } 967 if (exceptionRecord != NULL && contextRecord != NULL) { 968 ep.ContextRecord = (PCONTEXT) contextRecord; 969 ep.ExceptionRecord = (PEXCEPTION_RECORD) exceptionRecord; 970 971 mei.ThreadId = GetCurrentThreadId(); 972 mei.ExceptionPointers = &ep; 973 pmei = &mei; 974 } else { 975 pmei = NULL; 976 } 977 978 979 // Older versions of dbghelp.dll (the one shipped with Win2003 for example) may not support all 980 // the dump types we really want. If first call fails, lets fall back to just use MiniDumpWithFullMemory then. 981 if (_MiniDumpWriteDump(hProcess, processId, dumpFile, dumpType, pmei, NULL, NULL) == false && 982 _MiniDumpWriteDump(hProcess, processId, dumpFile, (MINIDUMP_TYPE)MiniDumpWithFullMemory, pmei, NULL, NULL) == false) { 983 VMError::report_coredump_status("Call to MiniDumpWriteDump() failed", false); 984 } else { 985 VMError::report_coredump_status(buffer, true); 986 } 987 988 CloseHandle(dumpFile); 989 } 990 991 992 993 void os::abort(bool dump_core) 994 { 995 os::shutdown(); 996 // no core dump on Windows 997 ::exit(1); 998 } 999 1000 // Die immediately, no exit hook, no abort hook, no cleanup. 1001 void os::die() { 1002 _exit(-1); 1003 } 1004 1005 // Directory routines copied from src/win32/native/java/io/dirent_md.c 1006 // * dirent_md.c 1.15 00/02/02 1007 // 1008 // The declarations for DIR and struct dirent are in jvm_win32.h. 1009 1010 /* Caller must have already run dirname through JVM_NativePath, which removes 1011 duplicate slashes and converts all instances of '/' into '\\'. */ 1012 1013 DIR * 1014 os::opendir(const char *dirname) 1015 { 1016 assert(dirname != NULL, "just checking"); // hotspot change 1017 DIR *dirp = (DIR *)malloc(sizeof(DIR)); 1018 DWORD fattr; // hotspot change 1019 char alt_dirname[4] = { 0, 0, 0, 0 }; 1020 1021 if (dirp == 0) { 1022 errno = ENOMEM; 1023 return 0; 1024 } 1025 1026 /* 1027 * Win32 accepts "\" in its POSIX stat(), but refuses to treat it 1028 * as a directory in FindFirstFile(). We detect this case here and 1029 * prepend the current drive name. 1030 */ 1031 if (dirname[1] == '\0' && dirname[0] == '\\') { 1032 alt_dirname[0] = _getdrive() + 'A' - 1; 1033 alt_dirname[1] = ':'; 1034 alt_dirname[2] = '\\'; 1035 alt_dirname[3] = '\0'; 1036 dirname = alt_dirname; 1037 } 1038 1039 dirp->path = (char *)malloc(strlen(dirname) + 5); 1040 if (dirp->path == 0) { 1041 free(dirp); 1042 errno = ENOMEM; 1043 return 0; 1044 } 1045 strcpy(dirp->path, dirname); 1046 1047 fattr = GetFileAttributes(dirp->path); 1048 if (fattr == 0xffffffff) { 1049 free(dirp->path); 1050 free(dirp); 1051 errno = ENOENT; 1052 return 0; 1053 } else if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) { 1054 free(dirp->path); 1055 free(dirp); 1056 errno = ENOTDIR; 1057 return 0; 1058 } 1059 1060 /* Append "*.*", or possibly "\\*.*", to path */ 1061 if (dirp->path[1] == ':' 1062 && (dirp->path[2] == '\0' 1063 || (dirp->path[2] == '\\' && dirp->path[3] == '\0'))) { 1064 /* No '\\' needed for cases like "Z:" or "Z:\" */ 1065 strcat(dirp->path, "*.*"); 1066 } else { 1067 strcat(dirp->path, "\\*.*"); 1068 } 1069 1070 dirp->handle = FindFirstFile(dirp->path, &dirp->find_data); 1071 if (dirp->handle == INVALID_HANDLE_VALUE) { 1072 if (GetLastError() != ERROR_FILE_NOT_FOUND) { 1073 free(dirp->path); 1074 free(dirp); 1075 errno = EACCES; 1076 return 0; 1077 } 1078 } 1079 return dirp; 1080 } 1081 1082 /* parameter dbuf unused on Windows */ 1083 1084 struct dirent * 1085 os::readdir(DIR *dirp, dirent *dbuf) 1086 { 1087 assert(dirp != NULL, "just checking"); // hotspot change 1088 if (dirp->handle == INVALID_HANDLE_VALUE) { 1089 return 0; 1090 } 1091 1092 strcpy(dirp->dirent.d_name, dirp->find_data.cFileName); 1093 1094 if (!FindNextFile(dirp->handle, &dirp->find_data)) { 1095 if (GetLastError() == ERROR_INVALID_HANDLE) { 1096 errno = EBADF; 1097 return 0; 1098 } 1099 FindClose(dirp->handle); 1100 dirp->handle = INVALID_HANDLE_VALUE; 1101 } 1102 1103 return &dirp->dirent; 1104 } 1105 1106 int 1107 os::closedir(DIR *dirp) 1108 { 1109 assert(dirp != NULL, "just checking"); // hotspot change 1110 if (dirp->handle != INVALID_HANDLE_VALUE) { 1111 if (!FindClose(dirp->handle)) { 1112 errno = EBADF; 1113 return -1; 1114 } 1115 dirp->handle = INVALID_HANDLE_VALUE; 1116 } 1117 free(dirp->path); 1118 free(dirp); 1119 return 0; 1120 } 1121 1122 // This must be hard coded because it's the system's temporary 1123 // directory not the java application's temp directory, ala java.io.tmpdir. 1124 const char* os::get_temp_directory() { 1125 static char path_buf[MAX_PATH]; 1126 if (GetTempPath(MAX_PATH, path_buf)>0) 1127 return path_buf; 1128 else{ 1129 path_buf[0]='\0'; 1130 return path_buf; 1131 } 1132 } 1133 1134 static bool file_exists(const char* filename) { 1135 if (filename == NULL || strlen(filename) == 0) { 1136 return false; 1137 } 1138 return GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES; 1139 } 1140 1141 void os::dll_build_name(char *buffer, size_t buflen, 1142 const char* pname, const char* fname) { 1143 const size_t pnamelen = pname ? strlen(pname) : 0; 1144 const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0; 1145 1146 // Quietly truncates on buffer overflow. Should be an error. 1147 if (pnamelen + strlen(fname) + 10 > buflen) { 1148 *buffer = '\0'; 1149 return; 1150 } 1151 1152 if (pnamelen == 0) { 1153 jio_snprintf(buffer, buflen, "%s.dll", fname); 1154 } else if (c == ':' || c == '\\') { 1155 jio_snprintf(buffer, buflen, "%s%s.dll", pname, fname); 1156 } else if (strchr(pname, *os::path_separator()) != NULL) { 1157 int n; 1158 char** pelements = split_path(pname, &n); 1159 for (int i = 0 ; i < n ; i++) { 1160 char* path = pelements[i]; 1161 // Really shouldn't be NULL, but check can't hurt 1162 size_t plen = (path == NULL) ? 0 : strlen(path); 1163 if (plen == 0) { 1164 continue; // skip the empty path values 1165 } 1166 const char lastchar = path[plen - 1]; 1167 if (lastchar == ':' || lastchar == '\\') { 1168 jio_snprintf(buffer, buflen, "%s%s.dll", path, fname); 1169 } else { 1170 jio_snprintf(buffer, buflen, "%s\\%s.dll", path, fname); 1171 } 1172 if (file_exists(buffer)) { 1173 break; 1174 } 1175 } 1176 // release the storage 1177 for (int i = 0 ; i < n ; i++) { 1178 if (pelements[i] != NULL) { 1179 FREE_C_HEAP_ARRAY(char, pelements[i]); 1180 } 1181 } 1182 if (pelements != NULL) { 1183 FREE_C_HEAP_ARRAY(char*, pelements); 1184 } 1185 } else { 1186 jio_snprintf(buffer, buflen, "%s\\%s.dll", pname, fname); 1187 } 1188 } 1189 1190 // Needs to be in os specific directory because windows requires another 1191 // header file <direct.h> 1192 const char* os::get_current_directory(char *buf, int buflen) { 1193 return _getcwd(buf, buflen); 1194 } 1195 1196 //----------------------------------------------------------- 1197 // Helper functions for fatal error handler 1198 #ifdef _WIN64 1199 // Helper routine which returns true if address in 1200 // within the NTDLL address space. 1201 // 1202 static bool _addr_in_ntdll( address addr ) 1203 { 1204 HMODULE hmod; 1205 MODULEINFO minfo; 1206 1207 hmod = GetModuleHandle("NTDLL.DLL"); 1208 if ( hmod == NULL ) return false; 1209 if ( !os::PSApiDll::GetModuleInformation( GetCurrentProcess(), hmod, 1210 &minfo, sizeof(MODULEINFO)) ) 1211 return false; 1212 1213 if ( (addr >= minfo.lpBaseOfDll) && 1214 (addr < (address)((uintptr_t)minfo.lpBaseOfDll + (uintptr_t)minfo.SizeOfImage))) 1215 return true; 1216 else 1217 return false; 1218 } 1219 #endif 1220 1221 1222 // Enumerate all modules for a given process ID 1223 // 1224 // Notice that Windows 95/98/Me and Windows NT/2000/XP have 1225 // different API for doing this. We use PSAPI.DLL on NT based 1226 // Windows and ToolHelp on 95/98/Me. 1227 1228 // Callback function that is called by enumerate_modules() on 1229 // every DLL module. 1230 // Input parameters: 1231 // int pid, 1232 // char* module_file_name, 1233 // address module_base_addr, 1234 // unsigned module_size, 1235 // void* param 1236 typedef int (*EnumModulesCallbackFunc)(int, char *, address, unsigned, void *); 1237 1238 // enumerate_modules for Windows NT, using PSAPI 1239 static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void * param) 1240 { 1241 HANDLE hProcess ; 1242 1243 # define MAX_NUM_MODULES 128 1244 HMODULE modules[MAX_NUM_MODULES]; 1245 static char filename[ MAX_PATH ]; 1246 int result = 0; 1247 1248 if (!os::PSApiDll::PSApiAvailable()) { 1249 return 0; 1250 } 1251 1252 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 1253 FALSE, pid ) ; 1254 if (hProcess == NULL) return 0; 1255 1256 DWORD size_needed; 1257 if (!os::PSApiDll::EnumProcessModules(hProcess, modules, 1258 sizeof(modules), &size_needed)) { 1259 CloseHandle( hProcess ); 1260 return 0; 1261 } 1262 1263 // number of modules that are currently loaded 1264 int num_modules = size_needed / sizeof(HMODULE); 1265 1266 for (int i = 0; i < MIN2(num_modules, MAX_NUM_MODULES); i++) { 1267 // Get Full pathname: 1268 if(!os::PSApiDll::GetModuleFileNameEx(hProcess, modules[i], 1269 filename, sizeof(filename))) { 1270 filename[0] = '\0'; 1271 } 1272 1273 MODULEINFO modinfo; 1274 if (!os::PSApiDll::GetModuleInformation(hProcess, modules[i], 1275 &modinfo, sizeof(modinfo))) { 1276 modinfo.lpBaseOfDll = NULL; 1277 modinfo.SizeOfImage = 0; 1278 } 1279 1280 // Invoke callback function 1281 result = func(pid, filename, (address)modinfo.lpBaseOfDll, 1282 modinfo.SizeOfImage, param); 1283 if (result) break; 1284 } 1285 1286 CloseHandle( hProcess ) ; 1287 return result; 1288 } 1289 1290 1291 // enumerate_modules for Windows 95/98/ME, using TOOLHELP 1292 static int _enumerate_modules_windows( int pid, EnumModulesCallbackFunc func, void *param) 1293 { 1294 HANDLE hSnapShot ; 1295 static MODULEENTRY32 modentry ; 1296 int result = 0; 1297 1298 if (!os::Kernel32Dll::HelpToolsAvailable()) { 1299 return 0; 1300 } 1301 1302 // Get a handle to a Toolhelp snapshot of the system 1303 hSnapShot = os::Kernel32Dll::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid ) ; 1304 if( hSnapShot == INVALID_HANDLE_VALUE ) { 1305 return FALSE ; 1306 } 1307 1308 // iterate through all modules 1309 modentry.dwSize = sizeof(MODULEENTRY32) ; 1310 bool not_done = os::Kernel32Dll::Module32First( hSnapShot, &modentry ) != 0; 1311 1312 while( not_done ) { 1313 // invoke the callback 1314 result=func(pid, modentry.szExePath, (address)modentry.modBaseAddr, 1315 modentry.modBaseSize, param); 1316 if (result) break; 1317 1318 modentry.dwSize = sizeof(MODULEENTRY32) ; 1319 not_done = os::Kernel32Dll::Module32Next( hSnapShot, &modentry ) != 0; 1320 } 1321 1322 CloseHandle(hSnapShot); 1323 return result; 1324 } 1325 1326 int enumerate_modules( int pid, EnumModulesCallbackFunc func, void * param ) 1327 { 1328 // Get current process ID if caller doesn't provide it. 1329 if (!pid) pid = os::current_process_id(); 1330 1331 if (os::win32::is_nt()) return _enumerate_modules_winnt (pid, func, param); 1332 else return _enumerate_modules_windows(pid, func, param); 1333 } 1334 1335 struct _modinfo { 1336 address addr; 1337 char* full_path; // point to a char buffer 1338 int buflen; // size of the buffer 1339 address base_addr; 1340 }; 1341 1342 static int _locate_module_by_addr(int pid, char * mod_fname, address base_addr, 1343 unsigned size, void * param) { 1344 struct _modinfo *pmod = (struct _modinfo *)param; 1345 if (!pmod) return -1; 1346 1347 if (base_addr <= pmod->addr && 1348 base_addr+size > pmod->addr) { 1349 // if a buffer is provided, copy path name to the buffer 1350 if (pmod->full_path) { 1351 jio_snprintf(pmod->full_path, pmod->buflen, "%s", mod_fname); 1352 } 1353 pmod->base_addr = base_addr; 1354 return 1; 1355 } 1356 return 0; 1357 } 1358 1359 bool os::dll_address_to_library_name(address addr, char* buf, 1360 int buflen, int* offset) { 1361 // NOTE: the reason we don't use SymGetModuleInfo() is it doesn't always 1362 // return the full path to the DLL file, sometimes it returns path 1363 // to the corresponding PDB file (debug info); sometimes it only 1364 // returns partial path, which makes life painful. 1365 1366 struct _modinfo mi; 1367 mi.addr = addr; 1368 mi.full_path = buf; 1369 mi.buflen = buflen; 1370 int pid = os::current_process_id(); 1371 if (enumerate_modules(pid, _locate_module_by_addr, (void *)&mi)) { 1372 // buf already contains path name 1373 if (offset) *offset = addr - mi.base_addr; 1374 return true; 1375 } else { 1376 if (buf) buf[0] = '\0'; 1377 if (offset) *offset = -1; 1378 return false; 1379 } 1380 } 1381 1382 bool os::dll_address_to_function_name(address addr, char *buf, 1383 int buflen, int *offset) { 1384 if (Decoder::decode(addr, buf, buflen, offset)) { 1385 return true; 1386 } 1387 if (offset != NULL) *offset = -1; 1388 if (buf != NULL) buf[0] = '\0'; 1389 return false; 1390 } 1391 1392 // save the start and end address of jvm.dll into param[0] and param[1] 1393 static int _locate_jvm_dll(int pid, char* mod_fname, address base_addr, 1394 unsigned size, void * param) { 1395 if (!param) return -1; 1396 1397 if (base_addr <= (address)_locate_jvm_dll && 1398 base_addr+size > (address)_locate_jvm_dll) { 1399 ((address*)param)[0] = base_addr; 1400 ((address*)param)[1] = base_addr + size; 1401 return 1; 1402 } 1403 return 0; 1404 } 1405 1406 address vm_lib_location[2]; // start and end address of jvm.dll 1407 1408 // check if addr is inside jvm.dll 1409 bool os::address_is_in_vm(address addr) { 1410 if (!vm_lib_location[0] || !vm_lib_location[1]) { 1411 int pid = os::current_process_id(); 1412 if (!enumerate_modules(pid, _locate_jvm_dll, (void *)vm_lib_location)) { 1413 assert(false, "Can't find jvm module."); 1414 return false; 1415 } 1416 } 1417 1418 return (vm_lib_location[0] <= addr) && (addr < vm_lib_location[1]); 1419 } 1420 1421 // print module info; param is outputStream* 1422 static int _print_module(int pid, char* fname, address base, 1423 unsigned size, void* param) { 1424 if (!param) return -1; 1425 1426 outputStream* st = (outputStream*)param; 1427 1428 address end_addr = base + size; 1429 st->print(PTR_FORMAT " - " PTR_FORMAT " \t%s\n", base, end_addr, fname); 1430 return 0; 1431 } 1432 1433 // Loads .dll/.so and 1434 // in case of error it checks if .dll/.so was built for the 1435 // same architecture as Hotspot is running on 1436 void * os::dll_load(const char *name, char *ebuf, int ebuflen) 1437 { 1438 void * result = LoadLibrary(name); 1439 if (result != NULL) 1440 { 1441 return result; 1442 } 1443 1444 DWORD errcode = GetLastError(); 1445 if (errcode == ERROR_MOD_NOT_FOUND) { 1446 strncpy(ebuf, "Can't find dependent libraries", ebuflen-1); 1447 ebuf[ebuflen-1]='\0'; 1448 return NULL; 1449 } 1450 1451 // Parsing dll below 1452 // If we can read dll-info and find that dll was built 1453 // for an architecture other than Hotspot is running in 1454 // - then print to buffer "DLL was built for a different architecture" 1455 // else call os::lasterror to obtain system error message 1456 1457 // Read system error message into ebuf 1458 // It may or may not be overwritten below (in the for loop and just above) 1459 lasterror(ebuf, (size_t) ebuflen); 1460 ebuf[ebuflen-1]='\0'; 1461 int file_descriptor=::open(name, O_RDONLY | O_BINARY, 0); 1462 if (file_descriptor<0) 1463 { 1464 return NULL; 1465 } 1466 1467 uint32_t signature_offset; 1468 uint16_t lib_arch=0; 1469 bool failed_to_get_lib_arch= 1470 ( 1471 //Go to position 3c in the dll 1472 (os::seek_to_file_offset(file_descriptor,IMAGE_FILE_PTR_TO_SIGNATURE)<0) 1473 || 1474 // Read loacation of signature 1475 (sizeof(signature_offset)!= 1476 (os::read(file_descriptor, (void*)&signature_offset,sizeof(signature_offset)))) 1477 || 1478 //Go to COFF File Header in dll 1479 //that is located after"signature" (4 bytes long) 1480 (os::seek_to_file_offset(file_descriptor, 1481 signature_offset+IMAGE_FILE_SIGNATURE_LENGTH)<0) 1482 || 1483 //Read field that contains code of architecture 1484 // that dll was build for 1485 (sizeof(lib_arch)!= 1486 (os::read(file_descriptor, (void*)&lib_arch,sizeof(lib_arch)))) 1487 ); 1488 1489 ::close(file_descriptor); 1490 if (failed_to_get_lib_arch) 1491 { 1492 // file i/o error - report os::lasterror(...) msg 1493 return NULL; 1494 } 1495 1496 typedef struct 1497 { 1498 uint16_t arch_code; 1499 char* arch_name; 1500 } arch_t; 1501 1502 static const arch_t arch_array[]={ 1503 {IMAGE_FILE_MACHINE_I386, (char*)"IA 32"}, 1504 {IMAGE_FILE_MACHINE_AMD64, (char*)"AMD 64"}, 1505 {IMAGE_FILE_MACHINE_IA64, (char*)"IA 64"} 1506 }; 1507 #if (defined _M_IA64) 1508 static const uint16_t running_arch=IMAGE_FILE_MACHINE_IA64; 1509 #elif (defined _M_AMD64) 1510 static const uint16_t running_arch=IMAGE_FILE_MACHINE_AMD64; 1511 #elif (defined _M_IX86) 1512 static const uint16_t running_arch=IMAGE_FILE_MACHINE_I386; 1513 #else 1514 #error Method os::dll_load requires that one of following \ 1515 is defined :_M_IA64,_M_AMD64 or _M_IX86 1516 #endif 1517 1518 1519 // Obtain a string for printf operation 1520 // lib_arch_str shall contain string what platform this .dll was built for 1521 // running_arch_str shall string contain what platform Hotspot was built for 1522 char *running_arch_str=NULL,*lib_arch_str=NULL; 1523 for (unsigned int i=0;i<ARRAY_SIZE(arch_array);i++) 1524 { 1525 if (lib_arch==arch_array[i].arch_code) 1526 lib_arch_str=arch_array[i].arch_name; 1527 if (running_arch==arch_array[i].arch_code) 1528 running_arch_str=arch_array[i].arch_name; 1529 } 1530 1531 assert(running_arch_str, 1532 "Didn't find runing architecture code in arch_array"); 1533 1534 // If the architure is right 1535 // but some other error took place - report os::lasterror(...) msg 1536 if (lib_arch == running_arch) 1537 { 1538 return NULL; 1539 } 1540 1541 if (lib_arch_str!=NULL) 1542 { 1543 ::_snprintf(ebuf, ebuflen-1, 1544 "Can't load %s-bit .dll on a %s-bit platform", 1545 lib_arch_str,running_arch_str); 1546 } 1547 else 1548 { 1549 // don't know what architecture this dll was build for 1550 ::_snprintf(ebuf, ebuflen-1, 1551 "Can't load this .dll (machine code=0x%x) on a %s-bit platform", 1552 lib_arch,running_arch_str); 1553 } 1554 1555 return NULL; 1556 } 1557 1558 1559 void os::print_dll_info(outputStream *st) { 1560 int pid = os::current_process_id(); 1561 st->print_cr("Dynamic libraries:"); 1562 enumerate_modules(pid, _print_module, (void *)st); 1563 } 1564 1565 void os::print_os_info_brief(outputStream* st) { 1566 os::print_os_info(st); 1567 } 1568 1569 void os::print_os_info(outputStream* st) { 1570 st->print("OS:"); 1571 1572 os::win32::print_windows_version(st); 1573 } 1574 1575 void os::win32::print_windows_version(outputStream* st) { 1576 OSVERSIONINFOEX osvi; 1577 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); 1578 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); 1579 1580 if (!GetVersionEx((OSVERSIONINFO *)&osvi)) { 1581 st->print_cr("N/A"); 1582 return; 1583 } 1584 1585 int os_vers = osvi.dwMajorVersion * 1000 + osvi.dwMinorVersion; 1586 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) { 1587 switch (os_vers) { 1588 case 3051: st->print(" Windows NT 3.51"); break; 1589 case 4000: st->print(" Windows NT 4.0"); break; 1590 case 5000: st->print(" Windows 2000"); break; 1591 case 5001: st->print(" Windows XP"); break; 1592 case 5002: 1593 case 6000: 1594 case 6001: 1595 case 6002: { 1596 // Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could 1597 // find out whether we are running on 64 bit processor or not. 1598 SYSTEM_INFO si; 1599 ZeroMemory(&si, sizeof(SYSTEM_INFO)); 1600 if (!os::Kernel32Dll::GetNativeSystemInfoAvailable()){ 1601 GetSystemInfo(&si); 1602 } else { 1603 os::Kernel32Dll::GetNativeSystemInfo(&si); 1604 } 1605 if (os_vers == 5002) { 1606 if (osvi.wProductType == VER_NT_WORKSTATION && 1607 si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1608 st->print(" Windows XP x64 Edition"); 1609 else 1610 st->print(" Windows Server 2003 family"); 1611 } else if (os_vers == 6000) { 1612 if (osvi.wProductType == VER_NT_WORKSTATION) 1613 st->print(" Windows Vista"); 1614 else 1615 st->print(" Windows Server 2008"); 1616 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1617 st->print(" , 64 bit"); 1618 } else if (os_vers == 6001) { 1619 if (osvi.wProductType == VER_NT_WORKSTATION) { 1620 st->print(" Windows 7"); 1621 } else { 1622 // Unrecognized windows, print out its major and minor versions 1623 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1624 } 1625 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1626 st->print(" , 64 bit"); 1627 } else if (os_vers == 6002) { 1628 if (osvi.wProductType == VER_NT_WORKSTATION) { 1629 st->print(" Windows 8"); 1630 } else { 1631 // Unrecognized windows, print out its major and minor versions 1632 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1633 } 1634 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1635 st->print(" , 64 bit"); 1636 } else { // future os 1637 // Unrecognized windows, print out its major and minor versions 1638 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1639 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1640 st->print(" , 64 bit"); 1641 } 1642 break; 1643 } 1644 default: // future windows, print out its major and minor versions 1645 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1646 } 1647 } else { 1648 switch (os_vers) { 1649 case 4000: st->print(" Windows 95"); break; 1650 case 4010: st->print(" Windows 98"); break; 1651 case 4090: st->print(" Windows Me"); break; 1652 default: // future windows, print out its major and minor versions 1653 st->print(" Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1654 } 1655 } 1656 st->print(" Build %d", osvi.dwBuildNumber); 1657 st->print(" %s", osvi.szCSDVersion); // service pack 1658 st->cr(); 1659 } 1660 1661 void os::pd_print_cpu_info(outputStream* st) { 1662 // Nothing to do for now. 1663 } 1664 1665 void os::print_memory_info(outputStream* st) { 1666 st->print("Memory:"); 1667 st->print(" %dk page", os::vm_page_size()>>10); 1668 1669 // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect 1670 // value if total memory is larger than 4GB 1671 MEMORYSTATUSEX ms; 1672 ms.dwLength = sizeof(ms); 1673 GlobalMemoryStatusEx(&ms); 1674 1675 st->print(", physical %uk", os::physical_memory() >> 10); 1676 st->print("(%uk free)", os::available_memory() >> 10); 1677 1678 st->print(", swap %uk", ms.ullTotalPageFile >> 10); 1679 st->print("(%uk free)", ms.ullAvailPageFile >> 10); 1680 st->cr(); 1681 } 1682 1683 void os::print_siginfo(outputStream *st, void *siginfo) { 1684 EXCEPTION_RECORD* er = (EXCEPTION_RECORD*)siginfo; 1685 st->print("siginfo:"); 1686 st->print(" ExceptionCode=0x%x", er->ExceptionCode); 1687 1688 if (er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && 1689 er->NumberParameters >= 2) { 1690 switch (er->ExceptionInformation[0]) { 1691 case 0: st->print(", reading address"); break; 1692 case 1: st->print(", writing address"); break; 1693 default: st->print(", ExceptionInformation=" INTPTR_FORMAT, 1694 er->ExceptionInformation[0]); 1695 } 1696 st->print(" " INTPTR_FORMAT, er->ExceptionInformation[1]); 1697 } else if (er->ExceptionCode == EXCEPTION_IN_PAGE_ERROR && 1698 er->NumberParameters >= 2 && UseSharedSpaces) { 1699 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1700 if (mapinfo->is_in_shared_space((void*)er->ExceptionInformation[1])) { 1701 st->print("\n\nError accessing class data sharing archive." \ 1702 " Mapped file inaccessible during execution, " \ 1703 " possible disk/network problem."); 1704 } 1705 } else { 1706 int num = er->NumberParameters; 1707 if (num > 0) { 1708 st->print(", ExceptionInformation="); 1709 for (int i = 0; i < num; i++) { 1710 st->print(INTPTR_FORMAT " ", er->ExceptionInformation[i]); 1711 } 1712 } 1713 } 1714 st->cr(); 1715 } 1716 1717 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 1718 // do nothing 1719 } 1720 1721 static char saved_jvm_path[MAX_PATH] = {0}; 1722 1723 // Find the full path to the current module, jvm.dll or jvm_g.dll 1724 void os::jvm_path(char *buf, jint buflen) { 1725 // Error checking. 1726 if (buflen < MAX_PATH) { 1727 assert(false, "must use a large-enough buffer"); 1728 buf[0] = '\0'; 1729 return; 1730 } 1731 // Lazy resolve the path to current module. 1732 if (saved_jvm_path[0] != 0) { 1733 strcpy(buf, saved_jvm_path); 1734 return; 1735 } 1736 1737 buf[0] = '\0'; 1738 if (Arguments::created_by_gamma_launcher()) { 1739 // Support for the gamma launcher. Check for an 1740 // JAVA_HOME environment variable 1741 // and fix up the path so it looks like 1742 // libjvm.so is installed there (append a fake suffix 1743 // hotspot/libjvm.so). 1744 char* java_home_var = ::getenv("JAVA_HOME"); 1745 if (java_home_var != NULL && java_home_var[0] != 0) { 1746 1747 strncpy(buf, java_home_var, buflen); 1748 1749 // determine if this is a legacy image or modules image 1750 // modules image doesn't have "jre" subdirectory 1751 size_t len = strlen(buf); 1752 char* jrebin_p = buf + len; 1753 jio_snprintf(jrebin_p, buflen-len, "\\jre\\bin\\"); 1754 if (0 != _access(buf, 0)) { 1755 jio_snprintf(jrebin_p, buflen-len, "\\bin\\"); 1756 } 1757 len = strlen(buf); 1758 jio_snprintf(buf + len, buflen-len, "hotspot\\jvm.dll"); 1759 } 1760 } 1761 1762 if(buf[0] == '\0') { 1763 GetModuleFileName(vm_lib_handle, buf, buflen); 1764 } 1765 strcpy(saved_jvm_path, buf); 1766 } 1767 1768 1769 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 1770 #ifndef _WIN64 1771 st->print("_"); 1772 #endif 1773 } 1774 1775 1776 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 1777 #ifndef _WIN64 1778 st->print("@%d", args_size * sizeof(int)); 1779 #endif 1780 } 1781 1782 // This method is a copy of JDK's sysGetLastErrorString 1783 // from src/windows/hpi/src/system_md.c 1784 1785 size_t os::lasterror(char* buf, size_t len) { 1786 DWORD errval; 1787 1788 if ((errval = GetLastError()) != 0) { 1789 // DOS error 1790 size_t n = (size_t)FormatMessage( 1791 FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 1792 NULL, 1793 errval, 1794 0, 1795 buf, 1796 (DWORD)len, 1797 NULL); 1798 if (n > 3) { 1799 // Drop final '.', CR, LF 1800 if (buf[n - 1] == '\n') n--; 1801 if (buf[n - 1] == '\r') n--; 1802 if (buf[n - 1] == '.') n--; 1803 buf[n] = '\0'; 1804 } 1805 return n; 1806 } 1807 1808 if (errno != 0) { 1809 // C runtime error that has no corresponding DOS error code 1810 const char* s = strerror(errno); 1811 size_t n = strlen(s); 1812 if (n >= len) n = len - 1; 1813 strncpy(buf, s, n); 1814 buf[n] = '\0'; 1815 return n; 1816 } 1817 1818 return 0; 1819 } 1820 1821 int os::get_last_error() { 1822 DWORD error = GetLastError(); 1823 if (error == 0) 1824 error = errno; 1825 return (int)error; 1826 } 1827 1828 // sun.misc.Signal 1829 // NOTE that this is a workaround for an apparent kernel bug where if 1830 // a signal handler for SIGBREAK is installed then that signal handler 1831 // takes priority over the console control handler for CTRL_CLOSE_EVENT. 1832 // See bug 4416763. 1833 static void (*sigbreakHandler)(int) = NULL; 1834 1835 static void UserHandler(int sig, void *siginfo, void *context) { 1836 os::signal_notify(sig); 1837 // We need to reinstate the signal handler each time... 1838 os::signal(sig, (void*)UserHandler); 1839 } 1840 1841 void* os::user_handler() { 1842 return (void*) UserHandler; 1843 } 1844 1845 void* os::signal(int signal_number, void* handler) { 1846 if ((signal_number == SIGBREAK) && (!ReduceSignalUsage)) { 1847 void (*oldHandler)(int) = sigbreakHandler; 1848 sigbreakHandler = (void (*)(int)) handler; 1849 return (void*) oldHandler; 1850 } else { 1851 return (void*)::signal(signal_number, (void (*)(int))handler); 1852 } 1853 } 1854 1855 void os::signal_raise(int signal_number) { 1856 raise(signal_number); 1857 } 1858 1859 // The Win32 C runtime library maps all console control events other than ^C 1860 // into SIGBREAK, which makes it impossible to distinguish ^BREAK from close, 1861 // logoff, and shutdown events. We therefore install our own console handler 1862 // that raises SIGTERM for the latter cases. 1863 // 1864 static BOOL WINAPI consoleHandler(DWORD event) { 1865 switch(event) { 1866 case CTRL_C_EVENT: 1867 if (is_error_reported()) { 1868 // Ctrl-C is pressed during error reporting, likely because the error 1869 // handler fails to abort. Let VM die immediately. 1870 os::die(); 1871 } 1872 1873 os::signal_raise(SIGINT); 1874 return TRUE; 1875 break; 1876 case CTRL_BREAK_EVENT: 1877 if (sigbreakHandler != NULL) { 1878 (*sigbreakHandler)(SIGBREAK); 1879 } 1880 return TRUE; 1881 break; 1882 case CTRL_CLOSE_EVENT: 1883 case CTRL_LOGOFF_EVENT: 1884 case CTRL_SHUTDOWN_EVENT: 1885 os::signal_raise(SIGTERM); 1886 return TRUE; 1887 break; 1888 default: 1889 break; 1890 } 1891 return FALSE; 1892 } 1893 1894 /* 1895 * The following code is moved from os.cpp for making this 1896 * code platform specific, which it is by its very nature. 1897 */ 1898 1899 // Return maximum OS signal used + 1 for internal use only 1900 // Used as exit signal for signal_thread 1901 int os::sigexitnum_pd(){ 1902 return NSIG; 1903 } 1904 1905 // a counter for each possible signal value, including signal_thread exit signal 1906 static volatile jint pending_signals[NSIG+1] = { 0 }; 1907 static HANDLE sig_sem; 1908 1909 void os::signal_init_pd() { 1910 // Initialize signal structures 1911 memset((void*)pending_signals, 0, sizeof(pending_signals)); 1912 1913 sig_sem = ::CreateSemaphore(NULL, 0, NSIG+1, NULL); 1914 1915 // Programs embedding the VM do not want it to attempt to receive 1916 // events like CTRL_LOGOFF_EVENT, which are used to implement the 1917 // shutdown hooks mechanism introduced in 1.3. For example, when 1918 // the VM is run as part of a Windows NT service (i.e., a servlet 1919 // engine in a web server), the correct behavior is for any console 1920 // control handler to return FALSE, not TRUE, because the OS's 1921 // "final" handler for such events allows the process to continue if 1922 // it is a service (while terminating it if it is not a service). 1923 // To make this behavior uniform and the mechanism simpler, we 1924 // completely disable the VM's usage of these console events if -Xrs 1925 // (=ReduceSignalUsage) is specified. This means, for example, that 1926 // the CTRL-BREAK thread dump mechanism is also disabled in this 1927 // case. See bugs 4323062, 4345157, and related bugs. 1928 1929 if (!ReduceSignalUsage) { 1930 // Add a CTRL-C handler 1931 SetConsoleCtrlHandler(consoleHandler, TRUE); 1932 } 1933 } 1934 1935 void os::signal_notify(int signal_number) { 1936 BOOL ret; 1937 1938 Atomic::inc(&pending_signals[signal_number]); 1939 ret = ::ReleaseSemaphore(sig_sem, 1, NULL); 1940 assert(ret != 0, "ReleaseSemaphore() failed"); 1941 } 1942 1943 static int check_pending_signals(bool wait_for_signal) { 1944 DWORD ret; 1945 while (true) { 1946 for (int i = 0; i < NSIG + 1; i++) { 1947 jint n = pending_signals[i]; 1948 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 1949 return i; 1950 } 1951 } 1952 if (!wait_for_signal) { 1953 return -1; 1954 } 1955 1956 JavaThread *thread = JavaThread::current(); 1957 1958 ThreadBlockInVM tbivm(thread); 1959 1960 bool threadIsSuspended; 1961 do { 1962 thread->set_suspend_equivalent(); 1963 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 1964 ret = ::WaitForSingleObject(sig_sem, INFINITE); 1965 assert(ret == WAIT_OBJECT_0, "WaitForSingleObject() failed"); 1966 1967 // were we externally suspended while we were waiting? 1968 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 1969 if (threadIsSuspended) { 1970 // 1971 // The semaphore has been incremented, but while we were waiting 1972 // another thread suspended us. We don't want to continue running 1973 // while suspended because that would surprise the thread that 1974 // suspended us. 1975 // 1976 ret = ::ReleaseSemaphore(sig_sem, 1, NULL); 1977 assert(ret != 0, "ReleaseSemaphore() failed"); 1978 1979 thread->java_suspend_self(); 1980 } 1981 } while (threadIsSuspended); 1982 } 1983 } 1984 1985 int os::signal_lookup() { 1986 return check_pending_signals(false); 1987 } 1988 1989 int os::signal_wait() { 1990 return check_pending_signals(true); 1991 } 1992 1993 // Implicit OS exception handling 1994 1995 LONG Handle_Exception(struct _EXCEPTION_POINTERS* exceptionInfo, address handler) { 1996 JavaThread* thread = JavaThread::current(); 1997 // Save pc in thread 1998 #ifdef _M_IA64 1999 thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->StIIP); 2000 // Set pc to handler 2001 exceptionInfo->ContextRecord->StIIP = (DWORD64)handler; 2002 #elif _M_AMD64 2003 thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Rip); 2004 // Set pc to handler 2005 exceptionInfo->ContextRecord->Rip = (DWORD64)handler; 2006 #else 2007 thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Eip); 2008 // Set pc to handler 2009 exceptionInfo->ContextRecord->Eip = (LONG)handler; 2010 #endif 2011 2012 // Continue the execution 2013 return EXCEPTION_CONTINUE_EXECUTION; 2014 } 2015 2016 2017 // Used for PostMortemDump 2018 extern "C" void safepoints(); 2019 extern "C" void find(int x); 2020 extern "C" void events(); 2021 2022 // According to Windows API documentation, an illegal instruction sequence should generate 2023 // the 0xC000001C exception code. However, real world experience shows that occasionnaly 2024 // the execution of an illegal instruction can generate the exception code 0xC000001E. This 2025 // seems to be an undocumented feature of Win NT 4.0 (and probably other Windows systems). 2026 2027 #define EXCEPTION_ILLEGAL_INSTRUCTION_2 0xC000001E 2028 2029 // From "Execution Protection in the Windows Operating System" draft 0.35 2030 // Once a system header becomes available, the "real" define should be 2031 // included or copied here. 2032 #define EXCEPTION_INFO_EXEC_VIOLATION 0x08 2033 2034 #define def_excpt(val) #val, val 2035 2036 struct siglabel { 2037 char *name; 2038 int number; 2039 }; 2040 2041 // All Visual C++ exceptions thrown from code generated by the Microsoft Visual 2042 // C++ compiler contain this error code. Because this is a compiler-generated 2043 // error, the code is not listed in the Win32 API header files. 2044 // The code is actually a cryptic mnemonic device, with the initial "E" 2045 // standing for "exception" and the final 3 bytes (0x6D7363) representing the 2046 // ASCII values of "msc". 2047 2048 #define EXCEPTION_UNCAUGHT_CXX_EXCEPTION 0xE06D7363 2049 2050 2051 struct siglabel exceptlabels[] = { 2052 def_excpt(EXCEPTION_ACCESS_VIOLATION), 2053 def_excpt(EXCEPTION_DATATYPE_MISALIGNMENT), 2054 def_excpt(EXCEPTION_BREAKPOINT), 2055 def_excpt(EXCEPTION_SINGLE_STEP), 2056 def_excpt(EXCEPTION_ARRAY_BOUNDS_EXCEEDED), 2057 def_excpt(EXCEPTION_FLT_DENORMAL_OPERAND), 2058 def_excpt(EXCEPTION_FLT_DIVIDE_BY_ZERO), 2059 def_excpt(EXCEPTION_FLT_INEXACT_RESULT), 2060 def_excpt(EXCEPTION_FLT_INVALID_OPERATION), 2061 def_excpt(EXCEPTION_FLT_OVERFLOW), 2062 def_excpt(EXCEPTION_FLT_STACK_CHECK), 2063 def_excpt(EXCEPTION_FLT_UNDERFLOW), 2064 def_excpt(EXCEPTION_INT_DIVIDE_BY_ZERO), 2065 def_excpt(EXCEPTION_INT_OVERFLOW), 2066 def_excpt(EXCEPTION_PRIV_INSTRUCTION), 2067 def_excpt(EXCEPTION_IN_PAGE_ERROR), 2068 def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION), 2069 def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION_2), 2070 def_excpt(EXCEPTION_NONCONTINUABLE_EXCEPTION), 2071 def_excpt(EXCEPTION_STACK_OVERFLOW), 2072 def_excpt(EXCEPTION_INVALID_DISPOSITION), 2073 def_excpt(EXCEPTION_GUARD_PAGE), 2074 def_excpt(EXCEPTION_INVALID_HANDLE), 2075 def_excpt(EXCEPTION_UNCAUGHT_CXX_EXCEPTION), 2076 NULL, 0 2077 }; 2078 2079 const char* os::exception_name(int exception_code, char *buf, size_t size) { 2080 for (int i = 0; exceptlabels[i].name != NULL; i++) { 2081 if (exceptlabels[i].number == exception_code) { 2082 jio_snprintf(buf, size, "%s", exceptlabels[i].name); 2083 return buf; 2084 } 2085 } 2086 2087 return NULL; 2088 } 2089 2090 //----------------------------------------------------------------------------- 2091 LONG Handle_IDiv_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) { 2092 // handle exception caused by idiv; should only happen for -MinInt/-1 2093 // (division by zero is handled explicitly) 2094 #ifdef _M_IA64 2095 assert(0, "Fix Handle_IDiv_Exception"); 2096 #elif _M_AMD64 2097 PCONTEXT ctx = exceptionInfo->ContextRecord; 2098 address pc = (address)ctx->Rip; 2099 assert(pc[0] == 0xF7, "not an idiv opcode"); 2100 assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands"); 2101 assert(ctx->Rax == min_jint, "unexpected idiv exception"); 2102 // set correct result values and continue after idiv instruction 2103 ctx->Rip = (DWORD)pc + 2; // idiv reg, reg is 2 bytes 2104 ctx->Rax = (DWORD)min_jint; // result 2105 ctx->Rdx = (DWORD)0; // remainder 2106 // Continue the execution 2107 #else 2108 PCONTEXT ctx = exceptionInfo->ContextRecord; 2109 address pc = (address)ctx->Eip; 2110 assert(pc[0] == 0xF7, "not an idiv opcode"); 2111 assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands"); 2112 assert(ctx->Eax == min_jint, "unexpected idiv exception"); 2113 // set correct result values and continue after idiv instruction 2114 ctx->Eip = (DWORD)pc + 2; // idiv reg, reg is 2 bytes 2115 ctx->Eax = (DWORD)min_jint; // result 2116 ctx->Edx = (DWORD)0; // remainder 2117 // Continue the execution 2118 #endif 2119 return EXCEPTION_CONTINUE_EXECUTION; 2120 } 2121 2122 #ifndef _WIN64 2123 //----------------------------------------------------------------------------- 2124 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) { 2125 // handle exception caused by native method modifying control word 2126 PCONTEXT ctx = exceptionInfo->ContextRecord; 2127 DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode; 2128 2129 switch (exception_code) { 2130 case EXCEPTION_FLT_DENORMAL_OPERAND: 2131 case EXCEPTION_FLT_DIVIDE_BY_ZERO: 2132 case EXCEPTION_FLT_INEXACT_RESULT: 2133 case EXCEPTION_FLT_INVALID_OPERATION: 2134 case EXCEPTION_FLT_OVERFLOW: 2135 case EXCEPTION_FLT_STACK_CHECK: 2136 case EXCEPTION_FLT_UNDERFLOW: 2137 jint fp_control_word = (* (jint*) StubRoutines::addr_fpu_cntrl_wrd_std()); 2138 if (fp_control_word != ctx->FloatSave.ControlWord) { 2139 // Restore FPCW and mask out FLT exceptions 2140 ctx->FloatSave.ControlWord = fp_control_word | 0xffffffc0; 2141 // Mask out pending FLT exceptions 2142 ctx->FloatSave.StatusWord &= 0xffffff00; 2143 return EXCEPTION_CONTINUE_EXECUTION; 2144 } 2145 } 2146 2147 if (prev_uef_handler != NULL) { 2148 // We didn't handle this exception so pass it to the previous 2149 // UnhandledExceptionFilter. 2150 return (prev_uef_handler)(exceptionInfo); 2151 } 2152 2153 return EXCEPTION_CONTINUE_SEARCH; 2154 } 2155 #else //_WIN64 2156 /* 2157 On Windows, the mxcsr control bits are non-volatile across calls 2158 See also CR 6192333 2159 If EXCEPTION_FLT_* happened after some native method modified 2160 mxcsr - it is not a jvm fault. 2161 However should we decide to restore of mxcsr after a faulty 2162 native method we can uncomment following code 2163 jint MxCsr = INITIAL_MXCSR; 2164 // we can't use StubRoutines::addr_mxcsr_std() 2165 // because in Win64 mxcsr is not saved there 2166 if (MxCsr != ctx->MxCsr) { 2167 ctx->MxCsr = MxCsr; 2168 return EXCEPTION_CONTINUE_EXECUTION; 2169 } 2170 2171 */ 2172 #endif //_WIN64 2173 2174 2175 // Fatal error reporting is single threaded so we can make this a 2176 // static and preallocated. If it's more than MAX_PATH silently ignore 2177 // it. 2178 static char saved_error_file[MAX_PATH] = {0}; 2179 2180 void os::set_error_file(const char *logfile) { 2181 if (strlen(logfile) <= MAX_PATH) { 2182 strncpy(saved_error_file, logfile, MAX_PATH); 2183 } 2184 } 2185 2186 static inline void report_error(Thread* t, DWORD exception_code, 2187 address addr, void* siginfo, void* context) { 2188 VMError err(t, exception_code, addr, siginfo, context); 2189 err.report_and_die(); 2190 2191 // If UseOsErrorReporting, this will return here and save the error file 2192 // somewhere where we can find it in the minidump. 2193 } 2194 2195 //----------------------------------------------------------------------------- 2196 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { 2197 if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH; 2198 DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode; 2199 #ifdef _M_IA64 2200 address pc = (address) exceptionInfo->ContextRecord->StIIP; 2201 #elif _M_AMD64 2202 address pc = (address) exceptionInfo->ContextRecord->Rip; 2203 #else 2204 address pc = (address) exceptionInfo->ContextRecord->Eip; 2205 #endif 2206 Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady 2207 2208 #ifndef _WIN64 2209 // Execution protection violation - win32 running on AMD64 only 2210 // Handled first to avoid misdiagnosis as a "normal" access violation; 2211 // This is safe to do because we have a new/unique ExceptionInformation 2212 // code for this condition. 2213 if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2214 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2215 int exception_subcode = (int) exceptionRecord->ExceptionInformation[0]; 2216 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2217 2218 if (exception_subcode == EXCEPTION_INFO_EXEC_VIOLATION) { 2219 int page_size = os::vm_page_size(); 2220 2221 // Make sure the pc and the faulting address are sane. 2222 // 2223 // If an instruction spans a page boundary, and the page containing 2224 // the beginning of the instruction is executable but the following 2225 // page is not, the pc and the faulting address might be slightly 2226 // different - we still want to unguard the 2nd page in this case. 2227 // 2228 // 15 bytes seems to be a (very) safe value for max instruction size. 2229 bool pc_is_near_addr = 2230 (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15); 2231 bool instr_spans_page_boundary = 2232 (align_size_down((intptr_t) pc ^ (intptr_t) addr, 2233 (intptr_t) page_size) > 0); 2234 2235 if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) { 2236 static volatile address last_addr = 2237 (address) os::non_memory_address_word(); 2238 2239 // In conservative mode, don't unguard unless the address is in the VM 2240 if (UnguardOnExecutionViolation > 0 && addr != last_addr && 2241 (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) { 2242 2243 // Set memory to RWX and retry 2244 address page_start = 2245 (address) align_size_down((intptr_t) addr, (intptr_t) page_size); 2246 bool res = os::protect_memory((char*) page_start, page_size, 2247 os::MEM_PROT_RWX); 2248 2249 if (PrintMiscellaneous && Verbose) { 2250 char buf[256]; 2251 jio_snprintf(buf, sizeof(buf), "Execution protection violation " 2252 "at " INTPTR_FORMAT 2253 ", unguarding " INTPTR_FORMAT ": %s", addr, 2254 page_start, (res ? "success" : strerror(errno))); 2255 tty->print_raw_cr(buf); 2256 } 2257 2258 // Set last_addr so if we fault again at the same address, we don't 2259 // end up in an endless loop. 2260 // 2261 // There are two potential complications here. Two threads trapping 2262 // at the same address at the same time could cause one of the 2263 // threads to think it already unguarded, and abort the VM. Likely 2264 // very rare. 2265 // 2266 // The other race involves two threads alternately trapping at 2267 // different addresses and failing to unguard the page, resulting in 2268 // an endless loop. This condition is probably even more unlikely 2269 // than the first. 2270 // 2271 // Although both cases could be avoided by using locks or thread 2272 // local last_addr, these solutions are unnecessary complication: 2273 // this handler is a best-effort safety net, not a complete solution. 2274 // It is disabled by default and should only be used as a workaround 2275 // in case we missed any no-execute-unsafe VM code. 2276 2277 last_addr = addr; 2278 2279 return EXCEPTION_CONTINUE_EXECUTION; 2280 } 2281 } 2282 2283 // Last unguard failed or not unguarding 2284 tty->print_raw_cr("Execution protection violation"); 2285 report_error(t, exception_code, addr, exceptionInfo->ExceptionRecord, 2286 exceptionInfo->ContextRecord); 2287 return EXCEPTION_CONTINUE_SEARCH; 2288 } 2289 } 2290 #endif // _WIN64 2291 2292 // Check to see if we caught the safepoint code in the 2293 // process of write protecting the memory serialization page. 2294 // It write enables the page immediately after protecting it 2295 // so just return. 2296 if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) { 2297 JavaThread* thread = (JavaThread*) t; 2298 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2299 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2300 if ( os::is_memory_serialize_page(thread, addr) ) { 2301 // Block current thread until the memory serialize page permission restored. 2302 os::block_on_serialize_page_trap(); 2303 return EXCEPTION_CONTINUE_EXECUTION; 2304 } 2305 } 2306 2307 if (t != NULL && t->is_Java_thread()) { 2308 JavaThread* thread = (JavaThread*) t; 2309 bool in_java = thread->thread_state() == _thread_in_Java; 2310 2311 // Handle potential stack overflows up front. 2312 if (exception_code == EXCEPTION_STACK_OVERFLOW) { 2313 if (os::uses_stack_guard_pages()) { 2314 #ifdef _M_IA64 2315 // 2316 // If it's a legal stack address continue, Windows will map it in. 2317 // 2318 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2319 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2320 if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) 2321 return EXCEPTION_CONTINUE_EXECUTION; 2322 2323 // The register save area is the same size as the memory stack 2324 // and starts at the page just above the start of the memory stack. 2325 // If we get a fault in this area, we've run out of register 2326 // stack. If we are in java, try throwing a stack overflow exception. 2327 if (addr > thread->stack_base() && 2328 addr <= (thread->stack_base()+thread->stack_size()) ) { 2329 char buf[256]; 2330 jio_snprintf(buf, sizeof(buf), 2331 "Register stack overflow, addr:%p, stack_base:%p\n", 2332 addr, thread->stack_base() ); 2333 tty->print_raw_cr(buf); 2334 // If not in java code, return and hope for the best. 2335 return in_java ? Handle_Exception(exceptionInfo, 2336 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)) 2337 : EXCEPTION_CONTINUE_EXECUTION; 2338 } 2339 #endif 2340 if (thread->stack_yellow_zone_enabled()) { 2341 // Yellow zone violation. The o/s has unprotected the first yellow 2342 // zone page for us. Note: must call disable_stack_yellow_zone to 2343 // update the enabled status, even if the zone contains only one page. 2344 thread->disable_stack_yellow_zone(); 2345 // If not in java code, return and hope for the best. 2346 return in_java ? Handle_Exception(exceptionInfo, 2347 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)) 2348 : EXCEPTION_CONTINUE_EXECUTION; 2349 } else { 2350 // Fatal red zone violation. 2351 thread->disable_stack_red_zone(); 2352 tty->print_raw_cr("An unrecoverable stack overflow has occurred."); 2353 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2354 exceptionInfo->ContextRecord); 2355 return EXCEPTION_CONTINUE_SEARCH; 2356 } 2357 } else if (in_java) { 2358 // JVM-managed guard pages cannot be used on win95/98. The o/s provides 2359 // a one-time-only guard page, which it has released to us. The next 2360 // stack overflow on this thread will result in an ACCESS_VIOLATION. 2361 return Handle_Exception(exceptionInfo, 2362 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)); 2363 } else { 2364 // Can only return and hope for the best. Further stack growth will 2365 // result in an ACCESS_VIOLATION. 2366 return EXCEPTION_CONTINUE_EXECUTION; 2367 } 2368 } else if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2369 // Either stack overflow or null pointer exception. 2370 if (in_java) { 2371 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2372 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2373 address stack_end = thread->stack_base() - thread->stack_size(); 2374 if (addr < stack_end && addr >= stack_end - os::vm_page_size()) { 2375 // Stack overflow. 2376 assert(!os::uses_stack_guard_pages(), 2377 "should be caught by red zone code above."); 2378 return Handle_Exception(exceptionInfo, 2379 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)); 2380 } 2381 // 2382 // Check for safepoint polling and implicit null 2383 // We only expect null pointers in the stubs (vtable) 2384 // the rest are checked explicitly now. 2385 // 2386 CodeBlob* cb = CodeCache::find_blob(pc); 2387 if (cb != NULL) { 2388 if (os::is_poll_address(addr)) { 2389 address stub = SharedRuntime::get_poll_stub(pc); 2390 return Handle_Exception(exceptionInfo, stub); 2391 } 2392 } 2393 { 2394 #ifdef _WIN64 2395 // 2396 // If it's a legal stack address map the entire region in 2397 // 2398 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2399 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2400 if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) { 2401 addr = (address)((uintptr_t)addr & 2402 (~((uintptr_t)os::vm_page_size() - (uintptr_t)1))); 2403 os::commit_memory((char *)addr, thread->stack_base() - addr, 2404 false ); 2405 return EXCEPTION_CONTINUE_EXECUTION; 2406 } 2407 else 2408 #endif 2409 { 2410 // Null pointer exception. 2411 #ifdef _M_IA64 2412 // We catch register stack overflows in compiled code by doing 2413 // an explicit compare and executing a st8(G0, G0) if the 2414 // BSP enters into our guard area. We test for the overflow 2415 // condition and fall into the normal null pointer exception 2416 // code if BSP hasn't overflowed. 2417 if ( in_java ) { 2418 if(thread->register_stack_overflow()) { 2419 assert((address)exceptionInfo->ContextRecord->IntS3 == 2420 thread->register_stack_limit(), 2421 "GR7 doesn't contain register_stack_limit"); 2422 // Disable the yellow zone which sets the state that 2423 // we've got a stack overflow problem. 2424 if (thread->stack_yellow_zone_enabled()) { 2425 thread->disable_stack_yellow_zone(); 2426 } 2427 // Give us some room to process the exception 2428 thread->disable_register_stack_guard(); 2429 // Update GR7 with the new limit so we can continue running 2430 // compiled code. 2431 exceptionInfo->ContextRecord->IntS3 = 2432 (ULONGLONG)thread->register_stack_limit(); 2433 return Handle_Exception(exceptionInfo, 2434 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)); 2435 } else { 2436 // 2437 // Check for implicit null 2438 // We only expect null pointers in the stubs (vtable) 2439 // the rest are checked explicitly now. 2440 // 2441 if (((uintptr_t)addr) < os::vm_page_size() ) { 2442 // an access to the first page of VM--assume it is a null pointer 2443 address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL); 2444 if (stub != NULL) return Handle_Exception(exceptionInfo, stub); 2445 } 2446 } 2447 } // in_java 2448 2449 // IA64 doesn't use implicit null checking yet. So we shouldn't 2450 // get here. 2451 tty->print_raw_cr("Access violation, possible null pointer exception"); 2452 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2453 exceptionInfo->ContextRecord); 2454 return EXCEPTION_CONTINUE_SEARCH; 2455 #else /* !IA64 */ 2456 2457 // Windows 98 reports faulting addresses incorrectly 2458 if (!MacroAssembler::needs_explicit_null_check((intptr_t)addr) || 2459 !os::win32::is_nt()) { 2460 address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL); 2461 if (stub != NULL) return Handle_Exception(exceptionInfo, stub); 2462 } 2463 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2464 exceptionInfo->ContextRecord); 2465 return EXCEPTION_CONTINUE_SEARCH; 2466 #endif 2467 } 2468 } 2469 } 2470 2471 #ifdef _WIN64 2472 // Special care for fast JNI field accessors. 2473 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks 2474 // in and the heap gets shrunk before the field access. 2475 if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2476 address addr = JNI_FastGetField::find_slowcase_pc(pc); 2477 if (addr != (address)-1) { 2478 return Handle_Exception(exceptionInfo, addr); 2479 } 2480 } 2481 #endif 2482 2483 #ifdef _WIN64 2484 // Windows will sometimes generate an access violation 2485 // when we call malloc. Since we use VectoredExceptions 2486 // on 64 bit platforms, we see this exception. We must 2487 // pass this exception on so Windows can recover. 2488 // We check to see if the pc of the fault is in NTDLL.DLL 2489 // if so, we pass control on to Windows for handling. 2490 if (UseVectoredExceptions && _addr_in_ntdll(pc)) return EXCEPTION_CONTINUE_SEARCH; 2491 #endif 2492 2493 // Stack overflow or null pointer exception in native code. 2494 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2495 exceptionInfo->ContextRecord); 2496 return EXCEPTION_CONTINUE_SEARCH; 2497 } 2498 2499 if (in_java) { 2500 switch (exception_code) { 2501 case EXCEPTION_INT_DIVIDE_BY_ZERO: 2502 return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO)); 2503 2504 case EXCEPTION_INT_OVERFLOW: 2505 return Handle_IDiv_Exception(exceptionInfo); 2506 2507 } // switch 2508 } 2509 #ifndef _WIN64 2510 if (((thread->thread_state() == _thread_in_Java) || 2511 (thread->thread_state() == _thread_in_native)) && 2512 exception_code != EXCEPTION_UNCAUGHT_CXX_EXCEPTION) 2513 { 2514 LONG result=Handle_FLT_Exception(exceptionInfo); 2515 if (result==EXCEPTION_CONTINUE_EXECUTION) return result; 2516 } 2517 #endif //_WIN64 2518 } 2519 2520 if (exception_code != EXCEPTION_BREAKPOINT) { 2521 #ifndef _WIN64 2522 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2523 exceptionInfo->ContextRecord); 2524 #else 2525 // Itanium Windows uses a VectoredExceptionHandler 2526 // Which means that C++ programatic exception handlers (try/except) 2527 // will get here. Continue the search for the right except block if 2528 // the exception code is not a fatal code. 2529 switch ( exception_code ) { 2530 case EXCEPTION_ACCESS_VIOLATION: 2531 case EXCEPTION_STACK_OVERFLOW: 2532 case EXCEPTION_ILLEGAL_INSTRUCTION: 2533 case EXCEPTION_ILLEGAL_INSTRUCTION_2: 2534 case EXCEPTION_INT_OVERFLOW: 2535 case EXCEPTION_INT_DIVIDE_BY_ZERO: 2536 case EXCEPTION_UNCAUGHT_CXX_EXCEPTION: 2537 { report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2538 exceptionInfo->ContextRecord); 2539 } 2540 break; 2541 default: 2542 break; 2543 } 2544 #endif 2545 } 2546 return EXCEPTION_CONTINUE_SEARCH; 2547 } 2548 2549 #ifndef _WIN64 2550 // Special care for fast JNI accessors. 2551 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and 2552 // the heap gets shrunk before the field access. 2553 // Need to install our own structured exception handler since native code may 2554 // install its own. 2555 LONG WINAPI fastJNIAccessorExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { 2556 DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode; 2557 if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2558 address pc = (address) exceptionInfo->ContextRecord->Eip; 2559 address addr = JNI_FastGetField::find_slowcase_pc(pc); 2560 if (addr != (address)-1) { 2561 return Handle_Exception(exceptionInfo, addr); 2562 } 2563 } 2564 return EXCEPTION_CONTINUE_SEARCH; 2565 } 2566 2567 #define DEFINE_FAST_GETFIELD(Return,Fieldname,Result) \ 2568 Return JNICALL jni_fast_Get##Result##Field_wrapper(JNIEnv *env, jobject obj, jfieldID fieldID) { \ 2569 __try { \ 2570 return (*JNI_FastGetField::jni_fast_Get##Result##Field_fp)(env, obj, fieldID); \ 2571 } __except(fastJNIAccessorExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) { \ 2572 } \ 2573 return 0; \ 2574 } 2575 2576 DEFINE_FAST_GETFIELD(jboolean, bool, Boolean) 2577 DEFINE_FAST_GETFIELD(jbyte, byte, Byte) 2578 DEFINE_FAST_GETFIELD(jchar, char, Char) 2579 DEFINE_FAST_GETFIELD(jshort, short, Short) 2580 DEFINE_FAST_GETFIELD(jint, int, Int) 2581 DEFINE_FAST_GETFIELD(jlong, long, Long) 2582 DEFINE_FAST_GETFIELD(jfloat, float, Float) 2583 DEFINE_FAST_GETFIELD(jdouble, double, Double) 2584 2585 address os::win32::fast_jni_accessor_wrapper(BasicType type) { 2586 switch (type) { 2587 case T_BOOLEAN: return (address)jni_fast_GetBooleanField_wrapper; 2588 case T_BYTE: return (address)jni_fast_GetByteField_wrapper; 2589 case T_CHAR: return (address)jni_fast_GetCharField_wrapper; 2590 case T_SHORT: return (address)jni_fast_GetShortField_wrapper; 2591 case T_INT: return (address)jni_fast_GetIntField_wrapper; 2592 case T_LONG: return (address)jni_fast_GetLongField_wrapper; 2593 case T_FLOAT: return (address)jni_fast_GetFloatField_wrapper; 2594 case T_DOUBLE: return (address)jni_fast_GetDoubleField_wrapper; 2595 default: ShouldNotReachHere(); 2596 } 2597 return (address)-1; 2598 } 2599 #endif 2600 2601 // Virtual Memory 2602 2603 int os::vm_page_size() { return os::win32::vm_page_size(); } 2604 int os::vm_allocation_granularity() { 2605 return os::win32::vm_allocation_granularity(); 2606 } 2607 2608 // Windows large page support is available on Windows 2003. In order to use 2609 // large page memory, the administrator must first assign additional privilege 2610 // to the user: 2611 // + select Control Panel -> Administrative Tools -> Local Security Policy 2612 // + select Local Policies -> User Rights Assignment 2613 // + double click "Lock pages in memory", add users and/or groups 2614 // + reboot 2615 // Note the above steps are needed for administrator as well, as administrators 2616 // by default do not have the privilege to lock pages in memory. 2617 // 2618 // Note about Windows 2003: although the API supports committing large page 2619 // memory on a page-by-page basis and VirtualAlloc() returns success under this 2620 // scenario, I found through experiment it only uses large page if the entire 2621 // memory region is reserved and committed in a single VirtualAlloc() call. 2622 // This makes Windows large page support more or less like Solaris ISM, in 2623 // that the entire heap must be committed upfront. This probably will change 2624 // in the future, if so the code below needs to be revisited. 2625 2626 #ifndef MEM_LARGE_PAGES 2627 #define MEM_LARGE_PAGES 0x20000000 2628 #endif 2629 2630 static HANDLE _hProcess; 2631 static HANDLE _hToken; 2632 2633 // Container for NUMA node list info 2634 class NUMANodeListHolder { 2635 private: 2636 int *_numa_used_node_list; // allocated below 2637 int _numa_used_node_count; 2638 2639 void free_node_list() { 2640 if (_numa_used_node_list != NULL) { 2641 FREE_C_HEAP_ARRAY(int, _numa_used_node_list); 2642 } 2643 } 2644 2645 public: 2646 NUMANodeListHolder() { 2647 _numa_used_node_count = 0; 2648 _numa_used_node_list = NULL; 2649 // do rest of initialization in build routine (after function pointers are set up) 2650 } 2651 2652 ~NUMANodeListHolder() { 2653 free_node_list(); 2654 } 2655 2656 bool build() { 2657 DWORD_PTR proc_aff_mask; 2658 DWORD_PTR sys_aff_mask; 2659 if (!GetProcessAffinityMask(GetCurrentProcess(), &proc_aff_mask, &sys_aff_mask)) return false; 2660 ULONG highest_node_number; 2661 if (!os::Kernel32Dll::GetNumaHighestNodeNumber(&highest_node_number)) return false; 2662 free_node_list(); 2663 _numa_used_node_list = NEW_C_HEAP_ARRAY(int, highest_node_number + 1); 2664 for (unsigned int i = 0; i <= highest_node_number; i++) { 2665 ULONGLONG proc_mask_numa_node; 2666 if (!os::Kernel32Dll::GetNumaNodeProcessorMask(i, &proc_mask_numa_node)) return false; 2667 if ((proc_aff_mask & proc_mask_numa_node)!=0) { 2668 _numa_used_node_list[_numa_used_node_count++] = i; 2669 } 2670 } 2671 return (_numa_used_node_count > 1); 2672 } 2673 2674 int get_count() {return _numa_used_node_count;} 2675 int get_node_list_entry(int n) { 2676 // for indexes out of range, returns -1 2677 return (n < _numa_used_node_count ? _numa_used_node_list[n] : -1); 2678 } 2679 2680 } numa_node_list_holder; 2681 2682 2683 2684 static size_t _large_page_size = 0; 2685 2686 static bool resolve_functions_for_large_page_init() { 2687 return os::Kernel32Dll::GetLargePageMinimumAvailable() && 2688 os::Advapi32Dll::AdvapiAvailable(); 2689 } 2690 2691 static bool request_lock_memory_privilege() { 2692 _hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 2693 os::current_process_id()); 2694 2695 LUID luid; 2696 if (_hProcess != NULL && 2697 os::Advapi32Dll::OpenProcessToken(_hProcess, TOKEN_ADJUST_PRIVILEGES, &_hToken) && 2698 os::Advapi32Dll::LookupPrivilegeValue(NULL, "SeLockMemoryPrivilege", &luid)) { 2699 2700 TOKEN_PRIVILEGES tp; 2701 tp.PrivilegeCount = 1; 2702 tp.Privileges[0].Luid = luid; 2703 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 2704 2705 // AdjustTokenPrivileges() may return TRUE even when it couldn't change the 2706 // privilege. Check GetLastError() too. See MSDN document. 2707 if (os::Advapi32Dll::AdjustTokenPrivileges(_hToken, false, &tp, sizeof(tp), NULL, NULL) && 2708 (GetLastError() == ERROR_SUCCESS)) { 2709 return true; 2710 } 2711 } 2712 2713 return false; 2714 } 2715 2716 static void cleanup_after_large_page_init() { 2717 if (_hProcess) CloseHandle(_hProcess); 2718 _hProcess = NULL; 2719 if (_hToken) CloseHandle(_hToken); 2720 _hToken = NULL; 2721 } 2722 2723 static bool numa_interleaving_init() { 2724 bool success = false; 2725 bool use_numa_interleaving_specified = !FLAG_IS_DEFAULT(UseNUMAInterleaving); 2726 2727 // print a warning if UseNUMAInterleaving flag is specified on command line 2728 bool warn_on_failure = use_numa_interleaving_specified; 2729 # define WARN(msg) if (warn_on_failure) { warning(msg); } 2730 2731 // NUMAInterleaveGranularity cannot be less than vm_allocation_granularity (or _large_page_size if using large pages) 2732 size_t min_interleave_granularity = UseLargePages ? _large_page_size : os::vm_allocation_granularity(); 2733 NUMAInterleaveGranularity = align_size_up(NUMAInterleaveGranularity, min_interleave_granularity); 2734 2735 if (os::Kernel32Dll::NumaCallsAvailable()) { 2736 if (numa_node_list_holder.build()) { 2737 if (PrintMiscellaneous && Verbose) { 2738 tty->print("NUMA UsedNodeCount=%d, namely ", numa_node_list_holder.get_count()); 2739 for (int i = 0; i < numa_node_list_holder.get_count(); i++) { 2740 tty->print("%d ", numa_node_list_holder.get_node_list_entry(i)); 2741 } 2742 tty->print("\n"); 2743 } 2744 success = true; 2745 } else { 2746 WARN("Process does not cover multiple NUMA nodes."); 2747 } 2748 } else { 2749 WARN("NUMA Interleaving is not supported by the operating system."); 2750 } 2751 if (!success) { 2752 if (use_numa_interleaving_specified) WARN("...Ignoring UseNUMAInterleaving flag."); 2753 } 2754 return success; 2755 #undef WARN 2756 } 2757 2758 // this routine is used whenever we need to reserve a contiguous VA range 2759 // but we need to make separate VirtualAlloc calls for each piece of the range 2760 // Reasons for doing this: 2761 // * UseLargePagesIndividualAllocation was set (normally only needed on WS2003 but possible to be set otherwise) 2762 // * UseNUMAInterleaving requires a separate node for each piece 2763 static char* allocate_pages_individually(size_t bytes, char* addr, DWORD flags, DWORD prot, 2764 bool should_inject_error=false) { 2765 char * p_buf; 2766 // note: at setup time we guaranteed that NUMAInterleaveGranularity was aligned up to a page size 2767 size_t page_size = UseLargePages ? _large_page_size : os::vm_allocation_granularity(); 2768 size_t chunk_size = UseNUMAInterleaving ? NUMAInterleaveGranularity : page_size; 2769 2770 // first reserve enough address space in advance since we want to be 2771 // able to break a single contiguous virtual address range into multiple 2772 // large page commits but WS2003 does not allow reserving large page space 2773 // so we just use 4K pages for reserve, this gives us a legal contiguous 2774 // address space. then we will deallocate that reservation, and re alloc 2775 // using large pages 2776 const size_t size_of_reserve = bytes + chunk_size; 2777 if (bytes > size_of_reserve) { 2778 // Overflowed. 2779 return NULL; 2780 } 2781 p_buf = (char *) VirtualAlloc(addr, 2782 size_of_reserve, // size of Reserve 2783 MEM_RESERVE, 2784 PAGE_READWRITE); 2785 // If reservation failed, return NULL 2786 if (p_buf == NULL) return NULL; 2787 2788 os::release_memory(p_buf, bytes + chunk_size); 2789 2790 // we still need to round up to a page boundary (in case we are using large pages) 2791 // but not to a chunk boundary (in case InterleavingGranularity doesn't align with page size) 2792 // instead we handle this in the bytes_to_rq computation below 2793 p_buf = (char *) align_size_up((size_t)p_buf, page_size); 2794 2795 // now go through and allocate one chunk at a time until all bytes are 2796 // allocated 2797 size_t bytes_remaining = bytes; 2798 // An overflow of align_size_up() would have been caught above 2799 // in the calculation of size_of_reserve. 2800 char * next_alloc_addr = p_buf; 2801 HANDLE hProc = GetCurrentProcess(); 2802 2803 #ifdef ASSERT 2804 // Variable for the failure injection 2805 long ran_num = os::random(); 2806 size_t fail_after = ran_num % bytes; 2807 #endif 2808 2809 int count=0; 2810 while (bytes_remaining) { 2811 // select bytes_to_rq to get to the next chunk_size boundary 2812 2813 size_t bytes_to_rq = MIN2(bytes_remaining, chunk_size - ((size_t)next_alloc_addr % chunk_size)); 2814 // Note allocate and commit 2815 char * p_new; 2816 2817 #ifdef ASSERT 2818 bool inject_error_now = should_inject_error && (bytes_remaining <= fail_after); 2819 #else 2820 const bool inject_error_now = false; 2821 #endif 2822 2823 if (inject_error_now) { 2824 p_new = NULL; 2825 } else { 2826 if (!UseNUMAInterleaving) { 2827 p_new = (char *) VirtualAlloc(next_alloc_addr, 2828 bytes_to_rq, 2829 flags, 2830 prot); 2831 } else { 2832 // get the next node to use from the used_node_list 2833 assert(numa_node_list_holder.get_count() > 0, "Multiple NUMA nodes expected"); 2834 DWORD node = numa_node_list_holder.get_node_list_entry(count % numa_node_list_holder.get_count()); 2835 p_new = (char *)os::Kernel32Dll::VirtualAllocExNuma(hProc, 2836 next_alloc_addr, 2837 bytes_to_rq, 2838 flags, 2839 prot, 2840 node); 2841 } 2842 } 2843 2844 if (p_new == NULL) { 2845 // Free any allocated pages 2846 if (next_alloc_addr > p_buf) { 2847 // Some memory was committed so release it. 2848 size_t bytes_to_release = bytes - bytes_remaining; 2849 os::release_memory(p_buf, bytes_to_release); 2850 } 2851 #ifdef ASSERT 2852 if (should_inject_error) { 2853 if (TracePageSizes && Verbose) { 2854 tty->print_cr("Reserving pages individually failed."); 2855 } 2856 } 2857 #endif 2858 return NULL; 2859 } 2860 bytes_remaining -= bytes_to_rq; 2861 next_alloc_addr += bytes_to_rq; 2862 count++; 2863 } 2864 // made it this far, success 2865 return p_buf; 2866 } 2867 2868 2869 2870 void os::large_page_init() { 2871 if (!UseLargePages) return; 2872 2873 // print a warning if any large page related flag is specified on command line 2874 bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) || 2875 !FLAG_IS_DEFAULT(LargePageSizeInBytes); 2876 bool success = false; 2877 2878 # define WARN(msg) if (warn_on_failure) { warning(msg); } 2879 if (resolve_functions_for_large_page_init()) { 2880 if (request_lock_memory_privilege()) { 2881 size_t s = os::Kernel32Dll::GetLargePageMinimum(); 2882 if (s) { 2883 #if defined(IA32) || defined(AMD64) 2884 if (s > 4*M || LargePageSizeInBytes > 4*M) { 2885 WARN("JVM cannot use large pages bigger than 4mb."); 2886 } else { 2887 #endif 2888 if (LargePageSizeInBytes && LargePageSizeInBytes % s == 0) { 2889 _large_page_size = LargePageSizeInBytes; 2890 } else { 2891 _large_page_size = s; 2892 } 2893 success = true; 2894 #if defined(IA32) || defined(AMD64) 2895 } 2896 #endif 2897 } else { 2898 WARN("Large page is not supported by the processor."); 2899 } 2900 } else { 2901 WARN("JVM cannot use large page memory because it does not have enough privilege to lock pages in memory."); 2902 } 2903 } else { 2904 WARN("Large page is not supported by the operating system."); 2905 } 2906 #undef WARN 2907 2908 const size_t default_page_size = (size_t) vm_page_size(); 2909 if (success && _large_page_size > default_page_size) { 2910 _page_sizes[0] = _large_page_size; 2911 _page_sizes[1] = default_page_size; 2912 _page_sizes[2] = 0; 2913 } 2914 2915 cleanup_after_large_page_init(); 2916 UseLargePages = success; 2917 } 2918 2919 // On win32, one cannot release just a part of reserved memory, it's an 2920 // all or nothing deal. When we split a reservation, we must break the 2921 // reservation into two reservations. 2922 void os::split_reserved_memory(char *base, size_t size, size_t split, 2923 bool realloc) { 2924 if (size > 0) { 2925 release_memory(base, size); 2926 if (realloc) { 2927 reserve_memory(split, base); 2928 } 2929 if (size != split) { 2930 reserve_memory(size - split, base + split); 2931 } 2932 } 2933 } 2934 2935 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) { 2936 assert((size_t)addr % os::vm_allocation_granularity() == 0, 2937 "reserve alignment"); 2938 assert(bytes % os::vm_allocation_granularity() == 0, "reserve block size"); 2939 char* res; 2940 // note that if UseLargePages is on, all the areas that require interleaving 2941 // will go thru reserve_memory_special rather than thru here. 2942 bool use_individual = (UseNUMAInterleaving && !UseLargePages); 2943 if (!use_individual) { 2944 res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE, PAGE_READWRITE); 2945 } else { 2946 elapsedTimer reserveTimer; 2947 if( Verbose && PrintMiscellaneous ) reserveTimer.start(); 2948 // in numa interleaving, we have to allocate pages individually 2949 // (well really chunks of NUMAInterleaveGranularity size) 2950 res = allocate_pages_individually(bytes, addr, MEM_RESERVE, PAGE_READWRITE); 2951 if (res == NULL) { 2952 warning("NUMA page allocation failed"); 2953 } 2954 if( Verbose && PrintMiscellaneous ) { 2955 reserveTimer.stop(); 2956 tty->print_cr("reserve_memory of %Ix bytes took %ld ms (%ld ticks)", bytes, 2957 reserveTimer.milliseconds(), reserveTimer.ticks()); 2958 } 2959 } 2960 assert(res == NULL || addr == NULL || addr == res, 2961 "Unexpected address from reserve."); 2962 2963 return res; 2964 } 2965 2966 // Reserve memory at an arbitrary address, only if that area is 2967 // available (and not reserved for something else). 2968 char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2969 // Windows os::reserve_memory() fails of the requested address range is 2970 // not avilable. 2971 return reserve_memory(bytes, requested_addr); 2972 } 2973 2974 size_t os::large_page_size() { 2975 return _large_page_size; 2976 } 2977 2978 bool os::can_commit_large_page_memory() { 2979 // Windows only uses large page memory when the entire region is reserved 2980 // and committed in a single VirtualAlloc() call. This may change in the 2981 // future, but with Windows 2003 it's not possible to commit on demand. 2982 return false; 2983 } 2984 2985 bool os::can_execute_large_page_memory() { 2986 return true; 2987 } 2988 2989 char* os::reserve_memory_special(size_t bytes, char* addr, bool exec) { 2990 2991 const DWORD prot = exec ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; 2992 const DWORD flags = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES; 2993 2994 // with large pages, there are two cases where we need to use Individual Allocation 2995 // 1) the UseLargePagesIndividualAllocation flag is set (set by default on WS2003) 2996 // 2) NUMA Interleaving is enabled, in which case we use a different node for each page 2997 if (UseLargePagesIndividualAllocation || UseNUMAInterleaving) { 2998 if (TracePageSizes && Verbose) { 2999 tty->print_cr("Reserving large pages individually."); 3000 } 3001 char * p_buf = allocate_pages_individually(bytes, addr, flags, prot, LargePagesIndividualAllocationInjectError); 3002 if (p_buf == NULL) { 3003 // give an appropriate warning message 3004 if (UseNUMAInterleaving) { 3005 warning("NUMA large page allocation failed, UseLargePages flag ignored"); 3006 } 3007 if (UseLargePagesIndividualAllocation) { 3008 warning("Individually allocated large pages failed, " 3009 "use -XX:-UseLargePagesIndividualAllocation to turn off"); 3010 } 3011 return NULL; 3012 } 3013 3014 return p_buf; 3015 3016 } else { 3017 // normal policy just allocate it all at once 3018 DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES; 3019 char * res = (char *)VirtualAlloc(NULL, bytes, flag, prot); 3020 return res; 3021 } 3022 } 3023 3024 bool os::release_memory_special(char* base, size_t bytes) { 3025 return release_memory(base, bytes); 3026 } 3027 3028 void os::print_statistics() { 3029 } 3030 3031 bool os::commit_memory(char* addr, size_t bytes, bool exec) { 3032 if (bytes == 0) { 3033 // Don't bother the OS with noops. 3034 return true; 3035 } 3036 assert((size_t) addr % os::vm_page_size() == 0, "commit on page boundaries"); 3037 assert(bytes % os::vm_page_size() == 0, "commit in page-sized chunks"); 3038 // Don't attempt to print anything if the OS call fails. We're 3039 // probably low on resources, so the print itself may cause crashes. 3040 3041 // unless we have NUMAInterleaving enabled, the range of a commit 3042 // is always within a reserve covered by a single VirtualAlloc 3043 // in that case we can just do a single commit for the requested size 3044 if (!UseNUMAInterleaving) { 3045 if (VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) == NULL) return false; 3046 if (exec) { 3047 DWORD oldprot; 3048 // Windows doc says to use VirtualProtect to get execute permissions 3049 if (!VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot)) return false; 3050 } 3051 return true; 3052 } else { 3053 3054 // when NUMAInterleaving is enabled, the commit might cover a range that 3055 // came from multiple VirtualAlloc reserves (using allocate_pages_individually). 3056 // VirtualQuery can help us determine that. The RegionSize that VirtualQuery 3057 // returns represents the number of bytes that can be committed in one step. 3058 size_t bytes_remaining = bytes; 3059 char * next_alloc_addr = addr; 3060 while (bytes_remaining > 0) { 3061 MEMORY_BASIC_INFORMATION alloc_info; 3062 VirtualQuery(next_alloc_addr, &alloc_info, sizeof(alloc_info)); 3063 size_t bytes_to_rq = MIN2(bytes_remaining, (size_t)alloc_info.RegionSize); 3064 if (VirtualAlloc(next_alloc_addr, bytes_to_rq, MEM_COMMIT, PAGE_READWRITE) == NULL) 3065 return false; 3066 if (exec) { 3067 DWORD oldprot; 3068 if (!VirtualProtect(next_alloc_addr, bytes_to_rq, PAGE_EXECUTE_READWRITE, &oldprot)) 3069 return false; 3070 } 3071 bytes_remaining -= bytes_to_rq; 3072 next_alloc_addr += bytes_to_rq; 3073 } 3074 } 3075 // if we made it this far, return true 3076 return true; 3077 } 3078 3079 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint, 3080 bool exec) { 3081 return commit_memory(addr, size, exec); 3082 } 3083 3084 bool os::uncommit_memory(char* addr, size_t bytes) { 3085 if (bytes == 0) { 3086 // Don't bother the OS with noops. 3087 return true; 3088 } 3089 assert((size_t) addr % os::vm_page_size() == 0, "uncommit on page boundaries"); 3090 assert(bytes % os::vm_page_size() == 0, "uncommit in page-sized chunks"); 3091 return VirtualFree(addr, bytes, MEM_DECOMMIT) != 0; 3092 } 3093 3094 bool os::release_memory(char* addr, size_t bytes) { 3095 return VirtualFree(addr, 0, MEM_RELEASE) != 0; 3096 } 3097 3098 bool os::create_stack_guard_pages(char* addr, size_t size) { 3099 return os::commit_memory(addr, size); 3100 } 3101 3102 bool os::remove_stack_guard_pages(char* addr, size_t size) { 3103 return os::uncommit_memory(addr, size); 3104 } 3105 3106 // Set protections specified 3107 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 3108 bool is_committed) { 3109 unsigned int p = 0; 3110 switch (prot) { 3111 case MEM_PROT_NONE: p = PAGE_NOACCESS; break; 3112 case MEM_PROT_READ: p = PAGE_READONLY; break; 3113 case MEM_PROT_RW: p = PAGE_READWRITE; break; 3114 case MEM_PROT_RWX: p = PAGE_EXECUTE_READWRITE; break; 3115 default: 3116 ShouldNotReachHere(); 3117 } 3118 3119 DWORD old_status; 3120 3121 // Strange enough, but on Win32 one can change protection only for committed 3122 // memory, not a big deal anyway, as bytes less or equal than 64K 3123 if (!is_committed && !commit_memory(addr, bytes, prot == MEM_PROT_RWX)) { 3124 fatal("cannot commit protection page"); 3125 } 3126 // One cannot use os::guard_memory() here, as on Win32 guard page 3127 // have different (one-shot) semantics, from MSDN on PAGE_GUARD: 3128 // 3129 // Pages in the region become guard pages. Any attempt to access a guard page 3130 // causes the system to raise a STATUS_GUARD_PAGE exception and turn off 3131 // the guard page status. Guard pages thus act as a one-time access alarm. 3132 return VirtualProtect(addr, bytes, p, &old_status) != 0; 3133 } 3134 3135 bool os::guard_memory(char* addr, size_t bytes) { 3136 DWORD old_status; 3137 return VirtualProtect(addr, bytes, PAGE_READWRITE | PAGE_GUARD, &old_status) != 0; 3138 } 3139 3140 bool os::unguard_memory(char* addr, size_t bytes) { 3141 DWORD old_status; 3142 return VirtualProtect(addr, bytes, PAGE_READWRITE, &old_status) != 0; 3143 } 3144 3145 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { } 3146 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) { } 3147 void os::numa_make_global(char *addr, size_t bytes) { } 3148 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { } 3149 bool os::numa_topology_changed() { return false; } 3150 size_t os::numa_get_groups_num() { return MAX2(numa_node_list_holder.get_count(), 1); } 3151 int os::numa_get_group_id() { return 0; } 3152 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 3153 if (numa_node_list_holder.get_count() == 0 && size > 0) { 3154 // Provide an answer for UMA systems 3155 ids[0] = 0; 3156 return 1; 3157 } else { 3158 // check for size bigger than actual groups_num 3159 size = MIN2(size, numa_get_groups_num()); 3160 for (int i = 0; i < (int)size; i++) { 3161 ids[i] = numa_node_list_holder.get_node_list_entry(i); 3162 } 3163 return size; 3164 } 3165 } 3166 3167 bool os::get_page_info(char *start, page_info* info) { 3168 return false; 3169 } 3170 3171 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { 3172 return end; 3173 } 3174 3175 char* os::non_memory_address_word() { 3176 // Must never look like an address returned by reserve_memory, 3177 // even in its subfields (as defined by the CPU immediate fields, 3178 // if the CPU splits constants across multiple instructions). 3179 return (char*)-1; 3180 } 3181 3182 #define MAX_ERROR_COUNT 100 3183 #define SYS_THREAD_ERROR 0xffffffffUL 3184 3185 void os::pd_start_thread(Thread* thread) { 3186 DWORD ret = ResumeThread(thread->osthread()->thread_handle()); 3187 // Returns previous suspend state: 3188 // 0: Thread was not suspended 3189 // 1: Thread is running now 3190 // >1: Thread is still suspended. 3191 assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back 3192 } 3193 3194 class HighResolutionInterval { 3195 // The default timer resolution seems to be 10 milliseconds. 3196 // (Where is this written down?) 3197 // If someone wants to sleep for only a fraction of the default, 3198 // then we set the timer resolution down to 1 millisecond for 3199 // the duration of their interval. 3200 // We carefully set the resolution back, since otherwise we 3201 // seem to incur an overhead (3%?) that we don't need. 3202 // CONSIDER: if ms is small, say 3, then we should run with a high resolution time. 3203 // Buf if ms is large, say 500, or 503, we should avoid the call to timeBeginPeriod(). 3204 // Alternatively, we could compute the relative error (503/500 = .6%) and only use 3205 // timeBeginPeriod() if the relative error exceeded some threshold. 3206 // timeBeginPeriod() has been linked to problems with clock drift on win32 systems and 3207 // to decreased efficiency related to increased timer "tick" rates. We want to minimize 3208 // (a) calls to timeBeginPeriod() and timeEndPeriod() and (b) time spent with high 3209 // resolution timers running. 3210 private: 3211 jlong resolution; 3212 public: 3213 HighResolutionInterval(jlong ms) { 3214 resolution = ms % 10L; 3215 if (resolution != 0) { 3216 MMRESULT result = timeBeginPeriod(1L); 3217 } 3218 } 3219 ~HighResolutionInterval() { 3220 if (resolution != 0) { 3221 MMRESULT result = timeEndPeriod(1L); 3222 } 3223 resolution = 0L; 3224 } 3225 }; 3226 3227 int os::sleep(Thread* thread, jlong ms, bool interruptable) { 3228 jlong limit = (jlong) MAXDWORD; 3229 3230 while(ms > limit) { 3231 int res; 3232 if ((res = sleep(thread, limit, interruptable)) != OS_TIMEOUT) 3233 return res; 3234 ms -= limit; 3235 } 3236 3237 assert(thread == Thread::current(), "thread consistency check"); 3238 OSThread* osthread = thread->osthread(); 3239 OSThreadWaitState osts(osthread, false /* not Object.wait() */); 3240 int result; 3241 if (interruptable) { 3242 assert(thread->is_Java_thread(), "must be java thread"); 3243 JavaThread *jt = (JavaThread *) thread; 3244 ThreadBlockInVM tbivm(jt); 3245 3246 jt->set_suspend_equivalent(); 3247 // cleared by handle_special_suspend_equivalent_condition() or 3248 // java_suspend_self() via check_and_wait_while_suspended() 3249 3250 HANDLE events[1]; 3251 events[0] = osthread->interrupt_event(); 3252 HighResolutionInterval *phri=NULL; 3253 if(!ForceTimeHighResolution) 3254 phri = new HighResolutionInterval( ms ); 3255 if (WaitForMultipleObjects(1, events, FALSE, (DWORD)ms) == WAIT_TIMEOUT) { 3256 result = OS_TIMEOUT; 3257 } else { 3258 ResetEvent(osthread->interrupt_event()); 3259 osthread->set_interrupted(false); 3260 result = OS_INTRPT; 3261 } 3262 delete phri; //if it is NULL, harmless 3263 3264 // were we externally suspended while we were waiting? 3265 jt->check_and_wait_while_suspended(); 3266 } else { 3267 assert(!thread->is_Java_thread(), "must not be java thread"); 3268 Sleep((long) ms); 3269 result = OS_TIMEOUT; 3270 } 3271 return result; 3272 } 3273 3274 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 3275 void os::infinite_sleep() { 3276 while (true) { // sleep forever ... 3277 Sleep(100000); // ... 100 seconds at a time 3278 } 3279 } 3280 3281 typedef BOOL (WINAPI * STTSignature)(void) ; 3282 3283 os::YieldResult os::NakedYield() { 3284 // Use either SwitchToThread() or Sleep(0) 3285 // Consider passing back the return value from SwitchToThread(). 3286 if (os::Kernel32Dll::SwitchToThreadAvailable()) { 3287 return SwitchToThread() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ; 3288 } else { 3289 Sleep(0); 3290 } 3291 return os::YIELD_UNKNOWN ; 3292 } 3293 3294 void os::yield() { os::NakedYield(); } 3295 3296 void os::yield_all(int attempts) { 3297 // Yields to all threads, including threads with lower priorities 3298 Sleep(1); 3299 } 3300 3301 // Win32 only gives you access to seven real priorities at a time, 3302 // so we compress Java's ten down to seven. It would be better 3303 // if we dynamically adjusted relative priorities. 3304 3305 int os::java_to_os_priority[CriticalPriority + 1] = { 3306 THREAD_PRIORITY_IDLE, // 0 Entry should never be used 3307 THREAD_PRIORITY_LOWEST, // 1 MinPriority 3308 THREAD_PRIORITY_LOWEST, // 2 3309 THREAD_PRIORITY_BELOW_NORMAL, // 3 3310 THREAD_PRIORITY_BELOW_NORMAL, // 4 3311 THREAD_PRIORITY_NORMAL, // 5 NormPriority 3312 THREAD_PRIORITY_NORMAL, // 6 3313 THREAD_PRIORITY_ABOVE_NORMAL, // 7 3314 THREAD_PRIORITY_ABOVE_NORMAL, // 8 3315 THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority 3316 THREAD_PRIORITY_HIGHEST, // 10 MaxPriority 3317 THREAD_PRIORITY_HIGHEST // 11 CriticalPriority 3318 }; 3319 3320 int prio_policy1[CriticalPriority + 1] = { 3321 THREAD_PRIORITY_IDLE, // 0 Entry should never be used 3322 THREAD_PRIORITY_LOWEST, // 1 MinPriority 3323 THREAD_PRIORITY_LOWEST, // 2 3324 THREAD_PRIORITY_BELOW_NORMAL, // 3 3325 THREAD_PRIORITY_BELOW_NORMAL, // 4 3326 THREAD_PRIORITY_NORMAL, // 5 NormPriority 3327 THREAD_PRIORITY_ABOVE_NORMAL, // 6 3328 THREAD_PRIORITY_ABOVE_NORMAL, // 7 3329 THREAD_PRIORITY_HIGHEST, // 8 3330 THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority 3331 THREAD_PRIORITY_TIME_CRITICAL, // 10 MaxPriority 3332 THREAD_PRIORITY_TIME_CRITICAL // 11 CriticalPriority 3333 }; 3334 3335 static int prio_init() { 3336 // If ThreadPriorityPolicy is 1, switch tables 3337 if (ThreadPriorityPolicy == 1) { 3338 int i; 3339 for (i = 0; i < CriticalPriority + 1; i++) { 3340 os::java_to_os_priority[i] = prio_policy1[i]; 3341 } 3342 } 3343 if (UseCriticalJavaThreadPriority) { 3344 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority] ; 3345 } 3346 return 0; 3347 } 3348 3349 OSReturn os::set_native_priority(Thread* thread, int priority) { 3350 if (!UseThreadPriorities) return OS_OK; 3351 bool ret = SetThreadPriority(thread->osthread()->thread_handle(), priority) != 0; 3352 return ret ? OS_OK : OS_ERR; 3353 } 3354 3355 OSReturn os::get_native_priority(const Thread* const thread, int* priority_ptr) { 3356 if ( !UseThreadPriorities ) { 3357 *priority_ptr = java_to_os_priority[NormPriority]; 3358 return OS_OK; 3359 } 3360 int os_prio = GetThreadPriority(thread->osthread()->thread_handle()); 3361 if (os_prio == THREAD_PRIORITY_ERROR_RETURN) { 3362 assert(false, "GetThreadPriority failed"); 3363 return OS_ERR; 3364 } 3365 *priority_ptr = os_prio; 3366 return OS_OK; 3367 } 3368 3369 3370 // Hint to the underlying OS that a task switch would not be good. 3371 // Void return because it's a hint and can fail. 3372 void os::hint_no_preempt() {} 3373 3374 void os::interrupt(Thread* thread) { 3375 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(), 3376 "possibility of dangling Thread pointer"); 3377 3378 OSThread* osthread = thread->osthread(); 3379 osthread->set_interrupted(true); 3380 // More than one thread can get here with the same value of osthread, 3381 // resulting in multiple notifications. We do, however, want the store 3382 // to interrupted() to be visible to other threads before we post 3383 // the interrupt event. 3384 OrderAccess::release(); 3385 SetEvent(osthread->interrupt_event()); 3386 // For JSR166: unpark after setting status 3387 if (thread->is_Java_thread()) 3388 ((JavaThread*)thread)->parker()->unpark(); 3389 3390 ParkEvent * ev = thread->_ParkEvent ; 3391 if (ev != NULL) ev->unpark() ; 3392 3393 } 3394 3395 3396 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 3397 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(), 3398 "possibility of dangling Thread pointer"); 3399 3400 OSThread* osthread = thread->osthread(); 3401 bool interrupted = osthread->interrupted(); 3402 // There is no synchronization between the setting of the interrupt 3403 // and it being cleared here. It is critical - see 6535709 - that 3404 // we only clear the interrupt state, and reset the interrupt event, 3405 // if we are going to report that we were indeed interrupted - else 3406 // an interrupt can be "lost", leading to spurious wakeups or lost wakeups 3407 // depending on the timing 3408 if (interrupted && clear_interrupted) { 3409 osthread->set_interrupted(false); 3410 ResetEvent(osthread->interrupt_event()); 3411 } // Otherwise leave the interrupted state alone 3412 3413 return interrupted; 3414 } 3415 3416 // Get's a pc (hint) for a running thread. Currently used only for profiling. 3417 ExtendedPC os::get_thread_pc(Thread* thread) { 3418 CONTEXT context; 3419 context.ContextFlags = CONTEXT_CONTROL; 3420 HANDLE handle = thread->osthread()->thread_handle(); 3421 #ifdef _M_IA64 3422 assert(0, "Fix get_thread_pc"); 3423 return ExtendedPC(NULL); 3424 #else 3425 if (GetThreadContext(handle, &context)) { 3426 #ifdef _M_AMD64 3427 return ExtendedPC((address) context.Rip); 3428 #else 3429 return ExtendedPC((address) context.Eip); 3430 #endif 3431 } else { 3432 return ExtendedPC(NULL); 3433 } 3434 #endif 3435 } 3436 3437 // GetCurrentThreadId() returns DWORD 3438 intx os::current_thread_id() { return GetCurrentThreadId(); } 3439 3440 static int _initial_pid = 0; 3441 3442 int os::current_process_id() 3443 { 3444 return (_initial_pid ? _initial_pid : _getpid()); 3445 } 3446 3447 int os::win32::_vm_page_size = 0; 3448 int os::win32::_vm_allocation_granularity = 0; 3449 int os::win32::_processor_type = 0; 3450 // Processor level is not available on non-NT systems, use vm_version instead 3451 int os::win32::_processor_level = 0; 3452 julong os::win32::_physical_memory = 0; 3453 size_t os::win32::_default_stack_size = 0; 3454 3455 intx os::win32::_os_thread_limit = 0; 3456 volatile intx os::win32::_os_thread_count = 0; 3457 3458 bool os::win32::_is_nt = false; 3459 bool os::win32::_is_windows_2003 = false; 3460 bool os::win32::_is_windows_server = false; 3461 3462 void os::win32::initialize_system_info() { 3463 SYSTEM_INFO si; 3464 GetSystemInfo(&si); 3465 _vm_page_size = si.dwPageSize; 3466 _vm_allocation_granularity = si.dwAllocationGranularity; 3467 _processor_type = si.dwProcessorType; 3468 _processor_level = si.wProcessorLevel; 3469 set_processor_count(si.dwNumberOfProcessors); 3470 3471 MEMORYSTATUSEX ms; 3472 ms.dwLength = sizeof(ms); 3473 3474 // also returns dwAvailPhys (free physical memory bytes), dwTotalVirtual, dwAvailVirtual, 3475 // dwMemoryLoad (% of memory in use) 3476 GlobalMemoryStatusEx(&ms); 3477 _physical_memory = ms.ullTotalPhys; 3478 3479 OSVERSIONINFOEX oi; 3480 oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); 3481 GetVersionEx((OSVERSIONINFO*)&oi); 3482 switch(oi.dwPlatformId) { 3483 case VER_PLATFORM_WIN32_WINDOWS: _is_nt = false; break; 3484 case VER_PLATFORM_WIN32_NT: 3485 _is_nt = true; 3486 { 3487 int os_vers = oi.dwMajorVersion * 1000 + oi.dwMinorVersion; 3488 if (os_vers == 5002) { 3489 _is_windows_2003 = true; 3490 } 3491 if (oi.wProductType == VER_NT_DOMAIN_CONTROLLER || 3492 oi.wProductType == VER_NT_SERVER) { 3493 _is_windows_server = true; 3494 } 3495 } 3496 break; 3497 default: fatal("Unknown platform"); 3498 } 3499 3500 _default_stack_size = os::current_stack_size(); 3501 assert(_default_stack_size > (size_t) _vm_page_size, "invalid stack size"); 3502 assert((_default_stack_size & (_vm_page_size - 1)) == 0, 3503 "stack size not a multiple of page size"); 3504 3505 initialize_performance_counter(); 3506 3507 // Win95/Win98 scheduler bug work-around. The Win95/98 scheduler is 3508 // known to deadlock the system, if the VM issues to thread operations with 3509 // a too high frequency, e.g., such as changing the priorities. 3510 // The 6000 seems to work well - no deadlocks has been notices on the test 3511 // programs that we have seen experience this problem. 3512 if (!os::win32::is_nt()) { 3513 StarvationMonitorInterval = 6000; 3514 } 3515 } 3516 3517 3518 HINSTANCE os::win32::load_Windows_dll(const char* name, char *ebuf, int ebuflen) { 3519 char path[MAX_PATH]; 3520 DWORD size; 3521 DWORD pathLen = (DWORD)sizeof(path); 3522 HINSTANCE result = NULL; 3523 3524 // only allow library name without path component 3525 assert(strchr(name, '\\') == NULL, "path not allowed"); 3526 assert(strchr(name, ':') == NULL, "path not allowed"); 3527 if (strchr(name, '\\') != NULL || strchr(name, ':') != NULL) { 3528 jio_snprintf(ebuf, ebuflen, 3529 "Invalid parameter while calling os::win32::load_windows_dll(): cannot take path: %s", name); 3530 return NULL; 3531 } 3532 3533 // search system directory 3534 if ((size = GetSystemDirectory(path, pathLen)) > 0) { 3535 strcat(path, "\\"); 3536 strcat(path, name); 3537 if ((result = (HINSTANCE)os::dll_load(path, ebuf, ebuflen)) != NULL) { 3538 return result; 3539 } 3540 } 3541 3542 // try Windows directory 3543 if ((size = GetWindowsDirectory(path, pathLen)) > 0) { 3544 strcat(path, "\\"); 3545 strcat(path, name); 3546 if ((result = (HINSTANCE)os::dll_load(path, ebuf, ebuflen)) != NULL) { 3547 return result; 3548 } 3549 } 3550 3551 jio_snprintf(ebuf, ebuflen, 3552 "os::win32::load_windows_dll() cannot load %s from system directories.", name); 3553 return NULL; 3554 } 3555 3556 void os::win32::setmode_streams() { 3557 _setmode(_fileno(stdin), _O_BINARY); 3558 _setmode(_fileno(stdout), _O_BINARY); 3559 _setmode(_fileno(stderr), _O_BINARY); 3560 } 3561 3562 3563 bool os::is_debugger_attached() { 3564 return IsDebuggerPresent() ? true : false; 3565 } 3566 3567 3568 void os::wait_for_keypress_at_exit(void) { 3569 if (PauseAtExit) { 3570 fprintf(stderr, "Press any key to continue...\n"); 3571 fgetc(stdin); 3572 } 3573 } 3574 3575 3576 int os::message_box(const char* title, const char* message) { 3577 int result = MessageBox(NULL, message, title, 3578 MB_YESNO | MB_ICONERROR | MB_SYSTEMMODAL | MB_DEFAULT_DESKTOP_ONLY); 3579 return result == IDYES; 3580 } 3581 3582 int os::allocate_thread_local_storage() { 3583 return TlsAlloc(); 3584 } 3585 3586 3587 void os::free_thread_local_storage(int index) { 3588 TlsFree(index); 3589 } 3590 3591 3592 void os::thread_local_storage_at_put(int index, void* value) { 3593 TlsSetValue(index, value); 3594 assert(thread_local_storage_at(index) == value, "Just checking"); 3595 } 3596 3597 3598 void* os::thread_local_storage_at(int index) { 3599 return TlsGetValue(index); 3600 } 3601 3602 3603 #ifndef PRODUCT 3604 #ifndef _WIN64 3605 // Helpers to check whether NX protection is enabled 3606 int nx_exception_filter(_EXCEPTION_POINTERS *pex) { 3607 if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && 3608 pex->ExceptionRecord->NumberParameters > 0 && 3609 pex->ExceptionRecord->ExceptionInformation[0] == 3610 EXCEPTION_INFO_EXEC_VIOLATION) { 3611 return EXCEPTION_EXECUTE_HANDLER; 3612 } 3613 return EXCEPTION_CONTINUE_SEARCH; 3614 } 3615 3616 void nx_check_protection() { 3617 // If NX is enabled we'll get an exception calling into code on the stack 3618 char code[] = { (char)0xC3 }; // ret 3619 void *code_ptr = (void *)code; 3620 __try { 3621 __asm call code_ptr 3622 } __except(nx_exception_filter((_EXCEPTION_POINTERS*)_exception_info())) { 3623 tty->print_raw_cr("NX protection detected."); 3624 } 3625 } 3626 #endif // _WIN64 3627 #endif // PRODUCT 3628 3629 // this is called _before_ the global arguments have been parsed 3630 void os::init(void) { 3631 _initial_pid = _getpid(); 3632 3633 init_random(1234567); 3634 3635 win32::initialize_system_info(); 3636 win32::setmode_streams(); 3637 init_page_sizes((size_t) win32::vm_page_size()); 3638 3639 // For better scalability on MP systems (must be called after initialize_system_info) 3640 #ifndef PRODUCT 3641 if (is_MP()) { 3642 NoYieldsInMicrolock = true; 3643 } 3644 #endif 3645 // This may be overridden later when argument processing is done. 3646 FLAG_SET_ERGO(bool, UseLargePagesIndividualAllocation, 3647 os::win32::is_windows_2003()); 3648 3649 // Initialize main_process and main_thread 3650 main_process = GetCurrentProcess(); // Remember main_process is a pseudo handle 3651 if (!DuplicateHandle(main_process, GetCurrentThread(), main_process, 3652 &main_thread, THREAD_ALL_ACCESS, false, 0)) { 3653 fatal("DuplicateHandle failed\n"); 3654 } 3655 main_thread_id = (int) GetCurrentThreadId(); 3656 } 3657 3658 // To install functions for atexit processing 3659 extern "C" { 3660 static void perfMemory_exit_helper() { 3661 perfMemory_exit(); 3662 } 3663 } 3664 3665 // this is called _after_ the global arguments have been parsed 3666 jint os::init_2(void) { 3667 // Allocate a single page and mark it as readable for safepoint polling 3668 address polling_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READONLY); 3669 guarantee( polling_page != NULL, "Reserve Failed for polling page"); 3670 3671 address return_page = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY); 3672 guarantee( return_page != NULL, "Commit Failed for polling page"); 3673 3674 os::set_polling_page( polling_page ); 3675 3676 #ifndef PRODUCT 3677 if( Verbose && PrintMiscellaneous ) 3678 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); 3679 #endif 3680 3681 if (!UseMembar) { 3682 address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE); 3683 guarantee( mem_serialize_page != NULL, "Reserve Failed for memory serialize page"); 3684 3685 return_page = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE); 3686 guarantee( return_page != NULL, "Commit Failed for memory serialize page"); 3687 3688 os::set_memory_serialize_page( mem_serialize_page ); 3689 3690 #ifndef PRODUCT 3691 if(Verbose && PrintMiscellaneous) 3692 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); 3693 #endif 3694 } 3695 3696 os::large_page_init(); 3697 3698 // Setup Windows Exceptions 3699 3700 // On Itanium systems, Structured Exception Handling does not 3701 // work since stack frames must be walkable by the OS. Since 3702 // much of our code is dynamically generated, and we do not have 3703 // proper unwind .xdata sections, the system simply exits 3704 // rather than delivering the exception. To work around 3705 // this we use VectorExceptions instead. 3706 #ifdef _WIN64 3707 if (UseVectoredExceptions) { 3708 topLevelVectoredExceptionHandler = AddVectoredExceptionHandler( 1, topLevelExceptionFilter); 3709 } 3710 #endif 3711 3712 // for debugging float code generation bugs 3713 if (ForceFloatExceptions) { 3714 #ifndef _WIN64 3715 static long fp_control_word = 0; 3716 __asm { fstcw fp_control_word } 3717 // see Intel PPro Manual, Vol. 2, p 7-16 3718 const long precision = 0x20; 3719 const long underflow = 0x10; 3720 const long overflow = 0x08; 3721 const long zero_div = 0x04; 3722 const long denorm = 0x02; 3723 const long invalid = 0x01; 3724 fp_control_word |= invalid; 3725 __asm { fldcw fp_control_word } 3726 #endif 3727 } 3728 3729 // If stack_commit_size is 0, windows will reserve the default size, 3730 // but only commit a small portion of it. 3731 size_t stack_commit_size = round_to(ThreadStackSize*K, os::vm_page_size()); 3732 size_t default_reserve_size = os::win32::default_stack_size(); 3733 size_t actual_reserve_size = stack_commit_size; 3734 if (stack_commit_size < default_reserve_size) { 3735 // If stack_commit_size == 0, we want this too 3736 actual_reserve_size = default_reserve_size; 3737 } 3738 3739 // Check minimum allowable stack size for thread creation and to initialize 3740 // the java system classes, including StackOverflowError - depends on page 3741 // size. Add a page for compiler2 recursion in main thread. 3742 // Add in 2*BytesPerWord times page size to account for VM stack during 3743 // class initialization depending on 32 or 64 bit VM. 3744 size_t min_stack_allowed = 3745 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+ 3746 2*BytesPerWord COMPILER2_PRESENT(+1)) * os::vm_page_size(); 3747 if (actual_reserve_size < min_stack_allowed) { 3748 tty->print_cr("\nThe stack size specified is too small, " 3749 "Specify at least %dk", 3750 min_stack_allowed / K); 3751 return JNI_ERR; 3752 } 3753 3754 JavaThread::set_stack_size_at_create(stack_commit_size); 3755 3756 // Calculate theoretical max. size of Threads to guard gainst artifical 3757 // out-of-memory situations, where all available address-space has been 3758 // reserved by thread stacks. 3759 assert(actual_reserve_size != 0, "Must have a stack"); 3760 3761 // Calculate the thread limit when we should start doing Virtual Memory 3762 // banging. Currently when the threads will have used all but 200Mb of space. 3763 // 3764 // TODO: consider performing a similar calculation for commit size instead 3765 // as reserve size, since on a 64-bit platform we'll run into that more 3766 // often than running out of virtual memory space. We can use the 3767 // lower value of the two calculations as the os_thread_limit. 3768 size_t max_address_space = ((size_t)1 << (BitsPerWord - 1)) - (200 * K * K); 3769 win32::_os_thread_limit = (intx)(max_address_space / actual_reserve_size); 3770 3771 // at exit methods are called in the reverse order of their registration. 3772 // there is no limit to the number of functions registered. atexit does 3773 // not set errno. 3774 3775 if (PerfAllowAtExitRegistration) { 3776 // only register atexit functions if PerfAllowAtExitRegistration is set. 3777 // atexit functions can be delayed until process exit time, which 3778 // can be problematic for embedded VM situations. Embedded VMs should 3779 // call DestroyJavaVM() to assure that VM resources are released. 3780 3781 // note: perfMemory_exit_helper atexit function may be removed in 3782 // the future if the appropriate cleanup code can be added to the 3783 // VM_Exit VMOperation's doit method. 3784 if (atexit(perfMemory_exit_helper) != 0) { 3785 warning("os::init_2 atexit(perfMemory_exit_helper) failed"); 3786 } 3787 } 3788 3789 #ifndef _WIN64 3790 // Print something if NX is enabled (win32 on AMD64) 3791 NOT_PRODUCT(if (PrintMiscellaneous && Verbose) nx_check_protection()); 3792 #endif 3793 3794 // initialize thread priority policy 3795 prio_init(); 3796 3797 if (UseNUMA && !ForceNUMA) { 3798 UseNUMA = false; // We don't fully support this yet 3799 } 3800 3801 if (UseNUMAInterleaving) { 3802 // first check whether this Windows OS supports VirtualAllocExNuma, if not ignore this flag 3803 bool success = numa_interleaving_init(); 3804 if (!success) UseNUMAInterleaving = false; 3805 } 3806 3807 return JNI_OK; 3808 } 3809 3810 void os::init_3(void) { 3811 return; 3812 } 3813 3814 // Mark the polling page as unreadable 3815 void os::make_polling_page_unreadable(void) { 3816 DWORD old_status; 3817 if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_NOACCESS, &old_status) ) 3818 fatal("Could not disable polling page"); 3819 }; 3820 3821 // Mark the polling page as readable 3822 void os::make_polling_page_readable(void) { 3823 DWORD old_status; 3824 if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_READONLY, &old_status) ) 3825 fatal("Could not enable polling page"); 3826 }; 3827 3828 3829 int os::stat(const char *path, struct stat *sbuf) { 3830 char pathbuf[MAX_PATH]; 3831 if (strlen(path) > MAX_PATH - 1) { 3832 errno = ENAMETOOLONG; 3833 return -1; 3834 } 3835 os::native_path(strcpy(pathbuf, path)); 3836 int ret = ::stat(pathbuf, sbuf); 3837 if (sbuf != NULL && UseUTCFileTimestamp) { 3838 // Fix for 6539723. st_mtime returned from stat() is dependent on 3839 // the system timezone and so can return different values for the 3840 // same file if/when daylight savings time changes. This adjustment 3841 // makes sure the same timestamp is returned regardless of the TZ. 3842 // 3843 // See: 3844 // http://msdn.microsoft.com/library/ 3845 // default.asp?url=/library/en-us/sysinfo/base/ 3846 // time_zone_information_str.asp 3847 // and 3848 // http://msdn.microsoft.com/library/default.asp?url= 3849 // /library/en-us/sysinfo/base/settimezoneinformation.asp 3850 // 3851 // NOTE: there is a insidious bug here: If the timezone is changed 3852 // after the call to stat() but before 'GetTimeZoneInformation()', then 3853 // the adjustment we do here will be wrong and we'll return the wrong 3854 // value (which will likely end up creating an invalid class data 3855 // archive). Absent a better API for this, or some time zone locking 3856 // mechanism, we'll have to live with this risk. 3857 TIME_ZONE_INFORMATION tz; 3858 DWORD tzid = GetTimeZoneInformation(&tz); 3859 int daylightBias = 3860 (tzid == TIME_ZONE_ID_DAYLIGHT) ? tz.DaylightBias : tz.StandardBias; 3861 sbuf->st_mtime += (tz.Bias + daylightBias) * 60; 3862 } 3863 return ret; 3864 } 3865 3866 3867 #define FT2INT64(ft) \ 3868 ((jlong)((jlong)(ft).dwHighDateTime << 32 | (julong)(ft).dwLowDateTime)) 3869 3870 3871 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 3872 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 3873 // of a thread. 3874 // 3875 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns 3876 // the fast estimate available on the platform. 3877 3878 // current_thread_cpu_time() is not optimized for Windows yet 3879 jlong os::current_thread_cpu_time() { 3880 // return user + sys since the cost is the same 3881 return os::thread_cpu_time(Thread::current(), true /* user+sys */); 3882 } 3883 3884 jlong os::thread_cpu_time(Thread* thread) { 3885 // consistent with what current_thread_cpu_time() returns. 3886 return os::thread_cpu_time(thread, true /* user+sys */); 3887 } 3888 3889 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 3890 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 3891 } 3892 3893 jlong os::thread_cpu_time(Thread* thread, bool user_sys_cpu_time) { 3894 // This code is copy from clasic VM -> hpi::sysThreadCPUTime 3895 // If this function changes, os::is_thread_cpu_time_supported() should too 3896 if (os::win32::is_nt()) { 3897 FILETIME CreationTime; 3898 FILETIME ExitTime; 3899 FILETIME KernelTime; 3900 FILETIME UserTime; 3901 3902 if ( GetThreadTimes(thread->osthread()->thread_handle(), 3903 &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0) 3904 return -1; 3905 else 3906 if (user_sys_cpu_time) { 3907 return (FT2INT64(UserTime) + FT2INT64(KernelTime)) * 100; 3908 } else { 3909 return FT2INT64(UserTime) * 100; 3910 } 3911 } else { 3912 return (jlong) timeGetTime() * 1000000; 3913 } 3914 } 3915 3916 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 3917 info_ptr->max_value = ALL_64_BITS; // the max value -- all 64 bits 3918 info_ptr->may_skip_backward = false; // GetThreadTimes returns absolute time 3919 info_ptr->may_skip_forward = false; // GetThreadTimes returns absolute time 3920 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 3921 } 3922 3923 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 3924 info_ptr->max_value = ALL_64_BITS; // the max value -- all 64 bits 3925 info_ptr->may_skip_backward = false; // GetThreadTimes returns absolute time 3926 info_ptr->may_skip_forward = false; // GetThreadTimes returns absolute time 3927 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 3928 } 3929 3930 bool os::is_thread_cpu_time_supported() { 3931 // see os::thread_cpu_time 3932 if (os::win32::is_nt()) { 3933 FILETIME CreationTime; 3934 FILETIME ExitTime; 3935 FILETIME KernelTime; 3936 FILETIME UserTime; 3937 3938 if ( GetThreadTimes(GetCurrentThread(), 3939 &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0) 3940 return false; 3941 else 3942 return true; 3943 } else { 3944 return false; 3945 } 3946 } 3947 3948 // Windows does't provide a loadavg primitive so this is stubbed out for now. 3949 // It does have primitives (PDH API) to get CPU usage and run queue length. 3950 // "\\Processor(_Total)\\% Processor Time", "\\System\\Processor Queue Length" 3951 // If we wanted to implement loadavg on Windows, we have a few options: 3952 // 3953 // a) Query CPU usage and run queue length and "fake" an answer by 3954 // returning the CPU usage if it's under 100%, and the run queue 3955 // length otherwise. It turns out that querying is pretty slow 3956 // on Windows, on the order of 200 microseconds on a fast machine. 3957 // Note that on the Windows the CPU usage value is the % usage 3958 // since the last time the API was called (and the first call 3959 // returns 100%), so we'd have to deal with that as well. 3960 // 3961 // b) Sample the "fake" answer using a sampling thread and store 3962 // the answer in a global variable. The call to loadavg would 3963 // just return the value of the global, avoiding the slow query. 3964 // 3965 // c) Sample a better answer using exponential decay to smooth the 3966 // value. This is basically the algorithm used by UNIX kernels. 3967 // 3968 // Note that sampling thread starvation could affect both (b) and (c). 3969 int os::loadavg(double loadavg[], int nelem) { 3970 return -1; 3971 } 3972 3973 3974 // DontYieldALot=false by default: dutifully perform all yields as requested by JVM_Yield() 3975 bool os::dont_yield() { 3976 return DontYieldALot; 3977 } 3978 3979 // This method is a slightly reworked copy of JDK's sysOpen 3980 // from src/windows/hpi/src/sys_api_md.c 3981 3982 int os::open(const char *path, int oflag, int mode) { 3983 char pathbuf[MAX_PATH]; 3984 3985 if (strlen(path) > MAX_PATH - 1) { 3986 errno = ENAMETOOLONG; 3987 return -1; 3988 } 3989 os::native_path(strcpy(pathbuf, path)); 3990 return ::open(pathbuf, oflag | O_BINARY | O_NOINHERIT, mode); 3991 } 3992 3993 // Is a (classpath) directory empty? 3994 bool os::dir_is_empty(const char* path) { 3995 WIN32_FIND_DATA fd; 3996 HANDLE f = FindFirstFile(path, &fd); 3997 if (f == INVALID_HANDLE_VALUE) { 3998 return true; 3999 } 4000 FindClose(f); 4001 return false; 4002 } 4003 4004 // create binary file, rewriting existing file if required 4005 int os::create_binary_file(const char* path, bool rewrite_existing) { 4006 int oflags = _O_CREAT | _O_WRONLY | _O_BINARY; 4007 if (!rewrite_existing) { 4008 oflags |= _O_EXCL; 4009 } 4010 return ::open(path, oflags, _S_IREAD | _S_IWRITE); 4011 } 4012 4013 // return current position of file pointer 4014 jlong os::current_file_offset(int fd) { 4015 return (jlong)::_lseeki64(fd, (__int64)0L, SEEK_CUR); 4016 } 4017 4018 // move file pointer to the specified offset 4019 jlong os::seek_to_file_offset(int fd, jlong offset) { 4020 return (jlong)::_lseeki64(fd, (__int64)offset, SEEK_SET); 4021 } 4022 4023 4024 jlong os::lseek(int fd, jlong offset, int whence) { 4025 return (jlong) ::_lseeki64(fd, offset, whence); 4026 } 4027 4028 // This method is a slightly reworked copy of JDK's sysNativePath 4029 // from src/windows/hpi/src/path_md.c 4030 4031 /* Convert a pathname to native format. On win32, this involves forcing all 4032 separators to be '\\' rather than '/' (both are legal inputs, but Win95 4033 sometimes rejects '/') and removing redundant separators. The input path is 4034 assumed to have been converted into the character encoding used by the local 4035 system. Because this might be a double-byte encoding, care is taken to 4036 treat double-byte lead characters correctly. 4037 4038 This procedure modifies the given path in place, as the result is never 4039 longer than the original. There is no error return; this operation always 4040 succeeds. */ 4041 char * os::native_path(char *path) { 4042 char *src = path, *dst = path, *end = path; 4043 char *colon = NULL; /* If a drive specifier is found, this will 4044 point to the colon following the drive 4045 letter */ 4046 4047 /* Assumption: '/', '\\', ':', and drive letters are never lead bytes */ 4048 assert(((!::IsDBCSLeadByte('/')) 4049 && (!::IsDBCSLeadByte('\\')) 4050 && (!::IsDBCSLeadByte(':'))), 4051 "Illegal lead byte"); 4052 4053 /* Check for leading separators */ 4054 #define isfilesep(c) ((c) == '/' || (c) == '\\') 4055 while (isfilesep(*src)) { 4056 src++; 4057 } 4058 4059 if (::isalpha(*src) && !::IsDBCSLeadByte(*src) && src[1] == ':') { 4060 /* Remove leading separators if followed by drive specifier. This 4061 hack is necessary to support file URLs containing drive 4062 specifiers (e.g., "file://c:/path"). As a side effect, 4063 "/c:/path" can be used as an alternative to "c:/path". */ 4064 *dst++ = *src++; 4065 colon = dst; 4066 *dst++ = ':'; 4067 src++; 4068 } else { 4069 src = path; 4070 if (isfilesep(src[0]) && isfilesep(src[1])) { 4071 /* UNC pathname: Retain first separator; leave src pointed at 4072 second separator so that further separators will be collapsed 4073 into the second separator. The result will be a pathname 4074 beginning with "\\\\" followed (most likely) by a host name. */ 4075 src = dst = path + 1; 4076 path[0] = '\\'; /* Force first separator to '\\' */ 4077 } 4078 } 4079 4080 end = dst; 4081 4082 /* Remove redundant separators from remainder of path, forcing all 4083 separators to be '\\' rather than '/'. Also, single byte space 4084 characters are removed from the end of the path because those 4085 are not legal ending characters on this operating system. 4086 */ 4087 while (*src != '\0') { 4088 if (isfilesep(*src)) { 4089 *dst++ = '\\'; src++; 4090 while (isfilesep(*src)) src++; 4091 if (*src == '\0') { 4092 /* Check for trailing separator */ 4093 end = dst; 4094 if (colon == dst - 2) break; /* "z:\\" */ 4095 if (dst == path + 1) break; /* "\\" */ 4096 if (dst == path + 2 && isfilesep(path[0])) { 4097 /* "\\\\" is not collapsed to "\\" because "\\\\" marks the 4098 beginning of a UNC pathname. Even though it is not, by 4099 itself, a valid UNC pathname, we leave it as is in order 4100 to be consistent with the path canonicalizer as well 4101 as the win32 APIs, which treat this case as an invalid 4102 UNC pathname rather than as an alias for the root 4103 directory of the current drive. */ 4104 break; 4105 } 4106 end = --dst; /* Path does not denote a root directory, so 4107 remove trailing separator */ 4108 break; 4109 } 4110 end = dst; 4111 } else { 4112 if (::IsDBCSLeadByte(*src)) { /* Copy a double-byte character */ 4113 *dst++ = *src++; 4114 if (*src) *dst++ = *src++; 4115 end = dst; 4116 } else { /* Copy a single-byte character */ 4117 char c = *src++; 4118 *dst++ = c; 4119 /* Space is not a legal ending character */ 4120 if (c != ' ') end = dst; 4121 } 4122 } 4123 } 4124 4125 *end = '\0'; 4126 4127 /* For "z:", add "." to work around a bug in the C runtime library */ 4128 if (colon == dst - 1) { 4129 path[2] = '.'; 4130 path[3] = '\0'; 4131 } 4132 4133 #ifdef DEBUG 4134 jio_fprintf(stderr, "sysNativePath: %s\n", path); 4135 #endif DEBUG 4136 return path; 4137 } 4138 4139 // This code is a copy of JDK's sysSetLength 4140 // from src/windows/hpi/src/sys_api_md.c 4141 4142 int os::ftruncate(int fd, jlong length) { 4143 HANDLE h = (HANDLE)::_get_osfhandle(fd); 4144 long high = (long)(length >> 32); 4145 DWORD ret; 4146 4147 if (h == (HANDLE)(-1)) { 4148 return -1; 4149 } 4150 4151 ret = ::SetFilePointer(h, (long)(length), &high, FILE_BEGIN); 4152 if ((ret == 0xFFFFFFFF) && (::GetLastError() != NO_ERROR)) { 4153 return -1; 4154 } 4155 4156 if (::SetEndOfFile(h) == FALSE) { 4157 return -1; 4158 } 4159 4160 return 0; 4161 } 4162 4163 4164 // This code is a copy of JDK's sysSync 4165 // from src/windows/hpi/src/sys_api_md.c 4166 // except for the legacy workaround for a bug in Win 98 4167 4168 int os::fsync(int fd) { 4169 HANDLE handle = (HANDLE)::_get_osfhandle(fd); 4170 4171 if ( (!::FlushFileBuffers(handle)) && 4172 (GetLastError() != ERROR_ACCESS_DENIED) ) { 4173 /* from winerror.h */ 4174 return -1; 4175 } 4176 return 0; 4177 } 4178 4179 static int nonSeekAvailable(int, long *); 4180 static int stdinAvailable(int, long *); 4181 4182 #define S_ISCHR(mode) (((mode) & _S_IFCHR) == _S_IFCHR) 4183 #define S_ISFIFO(mode) (((mode) & _S_IFIFO) == _S_IFIFO) 4184 4185 // This code is a copy of JDK's sysAvailable 4186 // from src/windows/hpi/src/sys_api_md.c 4187 4188 int os::available(int fd, jlong *bytes) { 4189 jlong cur, end; 4190 struct _stati64 stbuf64; 4191 4192 if (::_fstati64(fd, &stbuf64) >= 0) { 4193 int mode = stbuf64.st_mode; 4194 if (S_ISCHR(mode) || S_ISFIFO(mode)) { 4195 int ret; 4196 long lpbytes; 4197 if (fd == 0) { 4198 ret = stdinAvailable(fd, &lpbytes); 4199 } else { 4200 ret = nonSeekAvailable(fd, &lpbytes); 4201 } 4202 (*bytes) = (jlong)(lpbytes); 4203 return ret; 4204 } 4205 if ((cur = ::_lseeki64(fd, 0L, SEEK_CUR)) == -1) { 4206 return FALSE; 4207 } else if ((end = ::_lseeki64(fd, 0L, SEEK_END)) == -1) { 4208 return FALSE; 4209 } else if (::_lseeki64(fd, cur, SEEK_SET) == -1) { 4210 return FALSE; 4211 } 4212 *bytes = end - cur; 4213 return TRUE; 4214 } else { 4215 return FALSE; 4216 } 4217 } 4218 4219 // This code is a copy of JDK's nonSeekAvailable 4220 // from src/windows/hpi/src/sys_api_md.c 4221 4222 static int nonSeekAvailable(int fd, long *pbytes) { 4223 /* This is used for available on non-seekable devices 4224 * (like both named and anonymous pipes, such as pipes 4225 * connected to an exec'd process). 4226 * Standard Input is a special case. 4227 * 4228 */ 4229 HANDLE han; 4230 4231 if ((han = (HANDLE) ::_get_osfhandle(fd)) == (HANDLE)(-1)) { 4232 return FALSE; 4233 } 4234 4235 if (! ::PeekNamedPipe(han, NULL, 0, NULL, (LPDWORD)pbytes, NULL)) { 4236 /* PeekNamedPipe fails when at EOF. In that case we 4237 * simply make *pbytes = 0 which is consistent with the 4238 * behavior we get on Solaris when an fd is at EOF. 4239 * The only alternative is to raise an Exception, 4240 * which isn't really warranted. 4241 */ 4242 if (::GetLastError() != ERROR_BROKEN_PIPE) { 4243 return FALSE; 4244 } 4245 *pbytes = 0; 4246 } 4247 return TRUE; 4248 } 4249 4250 #define MAX_INPUT_EVENTS 2000 4251 4252 // This code is a copy of JDK's stdinAvailable 4253 // from src/windows/hpi/src/sys_api_md.c 4254 4255 static int stdinAvailable(int fd, long *pbytes) { 4256 HANDLE han; 4257 DWORD numEventsRead = 0; /* Number of events read from buffer */ 4258 DWORD numEvents = 0; /* Number of events in buffer */ 4259 DWORD i = 0; /* Loop index */ 4260 DWORD curLength = 0; /* Position marker */ 4261 DWORD actualLength = 0; /* Number of bytes readable */ 4262 BOOL error = FALSE; /* Error holder */ 4263 INPUT_RECORD *lpBuffer; /* Pointer to records of input events */ 4264 4265 if ((han = ::GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) { 4266 return FALSE; 4267 } 4268 4269 /* Construct an array of input records in the console buffer */ 4270 error = ::GetNumberOfConsoleInputEvents(han, &numEvents); 4271 if (error == 0) { 4272 return nonSeekAvailable(fd, pbytes); 4273 } 4274 4275 /* lpBuffer must fit into 64K or else PeekConsoleInput fails */ 4276 if (numEvents > MAX_INPUT_EVENTS) { 4277 numEvents = MAX_INPUT_EVENTS; 4278 } 4279 4280 lpBuffer = (INPUT_RECORD *)os::malloc(numEvents * sizeof(INPUT_RECORD)); 4281 if (lpBuffer == NULL) { 4282 return FALSE; 4283 } 4284 4285 error = ::PeekConsoleInput(han, lpBuffer, numEvents, &numEventsRead); 4286 if (error == 0) { 4287 os::free(lpBuffer); 4288 return FALSE; 4289 } 4290 4291 /* Examine input records for the number of bytes available */ 4292 for(i=0; i<numEvents; i++) { 4293 if (lpBuffer[i].EventType == KEY_EVENT) { 4294 4295 KEY_EVENT_RECORD *keyRecord = (KEY_EVENT_RECORD *) 4296 &(lpBuffer[i].Event); 4297 if (keyRecord->bKeyDown == TRUE) { 4298 CHAR *keyPressed = (CHAR *) &(keyRecord->uChar); 4299 curLength++; 4300 if (*keyPressed == '\r') { 4301 actualLength = curLength; 4302 } 4303 } 4304 } 4305 } 4306 4307 if(lpBuffer != NULL) { 4308 os::free(lpBuffer); 4309 } 4310 4311 *pbytes = (long) actualLength; 4312 return TRUE; 4313 } 4314 4315 // Map a block of memory. 4316 char* os::map_memory(int fd, const char* file_name, size_t file_offset, 4317 char *addr, size_t bytes, bool read_only, 4318 bool allow_exec) { 4319 HANDLE hFile; 4320 char* base; 4321 4322 hFile = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, 4323 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 4324 if (hFile == NULL) { 4325 if (PrintMiscellaneous && Verbose) { 4326 DWORD err = GetLastError(); 4327 tty->print_cr("CreateFile() failed: GetLastError->%ld."); 4328 } 4329 return NULL; 4330 } 4331 4332 if (allow_exec) { 4333 // CreateFileMapping/MapViewOfFileEx can't map executable memory 4334 // unless it comes from a PE image (which the shared archive is not.) 4335 // Even VirtualProtect refuses to give execute access to mapped memory 4336 // that was not previously executable. 4337 // 4338 // Instead, stick the executable region in anonymous memory. Yuck. 4339 // Penalty is that ~4 pages will not be shareable - in the future 4340 // we might consider DLLizing the shared archive with a proper PE 4341 // header so that mapping executable + sharing is possible. 4342 4343 base = (char*) VirtualAlloc(addr, bytes, MEM_COMMIT | MEM_RESERVE, 4344 PAGE_READWRITE); 4345 if (base == NULL) { 4346 if (PrintMiscellaneous && Verbose) { 4347 DWORD err = GetLastError(); 4348 tty->print_cr("VirtualAlloc() failed: GetLastError->%ld.", err); 4349 } 4350 CloseHandle(hFile); 4351 return NULL; 4352 } 4353 4354 DWORD bytes_read; 4355 OVERLAPPED overlapped; 4356 overlapped.Offset = (DWORD)file_offset; 4357 overlapped.OffsetHigh = 0; 4358 overlapped.hEvent = NULL; 4359 // ReadFile guarantees that if the return value is true, the requested 4360 // number of bytes were read before returning. 4361 bool res = ReadFile(hFile, base, (DWORD)bytes, &bytes_read, &overlapped) != 0; 4362 if (!res) { 4363 if (PrintMiscellaneous && Verbose) { 4364 DWORD err = GetLastError(); 4365 tty->print_cr("ReadFile() failed: GetLastError->%ld.", err); 4366 } 4367 release_memory(base, bytes); 4368 CloseHandle(hFile); 4369 return NULL; 4370 } 4371 } else { 4372 HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0, 4373 NULL /*file_name*/); 4374 if (hMap == NULL) { 4375 if (PrintMiscellaneous && Verbose) { 4376 DWORD err = GetLastError(); 4377 tty->print_cr("CreateFileMapping() failed: GetLastError->%ld."); 4378 } 4379 CloseHandle(hFile); 4380 return NULL; 4381 } 4382 4383 DWORD access = read_only ? FILE_MAP_READ : FILE_MAP_COPY; 4384 base = (char*)MapViewOfFileEx(hMap, access, 0, (DWORD)file_offset, 4385 (DWORD)bytes, addr); 4386 if (base == NULL) { 4387 if (PrintMiscellaneous && Verbose) { 4388 DWORD err = GetLastError(); 4389 tty->print_cr("MapViewOfFileEx() failed: GetLastError->%ld.", err); 4390 } 4391 CloseHandle(hMap); 4392 CloseHandle(hFile); 4393 return NULL; 4394 } 4395 4396 if (CloseHandle(hMap) == 0) { 4397 if (PrintMiscellaneous && Verbose) { 4398 DWORD err = GetLastError(); 4399 tty->print_cr("CloseHandle(hMap) failed: GetLastError->%ld.", err); 4400 } 4401 CloseHandle(hFile); 4402 return base; 4403 } 4404 } 4405 4406 if (allow_exec) { 4407 DWORD old_protect; 4408 DWORD exec_access = read_only ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE; 4409 bool res = VirtualProtect(base, bytes, exec_access, &old_protect) != 0; 4410 4411 if (!res) { 4412 if (PrintMiscellaneous && Verbose) { 4413 DWORD err = GetLastError(); 4414 tty->print_cr("VirtualProtect() failed: GetLastError->%ld.", err); 4415 } 4416 // Don't consider this a hard error, on IA32 even if the 4417 // VirtualProtect fails, we should still be able to execute 4418 CloseHandle(hFile); 4419 return base; 4420 } 4421 } 4422 4423 if (CloseHandle(hFile) == 0) { 4424 if (PrintMiscellaneous && Verbose) { 4425 DWORD err = GetLastError(); 4426 tty->print_cr("CloseHandle(hFile) failed: GetLastError->%ld.", err); 4427 } 4428 return base; 4429 } 4430 4431 return base; 4432 } 4433 4434 4435 // Remap a block of memory. 4436 char* os::remap_memory(int fd, const char* file_name, size_t file_offset, 4437 char *addr, size_t bytes, bool read_only, 4438 bool allow_exec) { 4439 // This OS does not allow existing memory maps to be remapped so we 4440 // have to unmap the memory before we remap it. 4441 if (!os::unmap_memory(addr, bytes)) { 4442 return NULL; 4443 } 4444 4445 // There is a very small theoretical window between the unmap_memory() 4446 // call above and the map_memory() call below where a thread in native 4447 // code may be able to access an address that is no longer mapped. 4448 4449 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 4450 allow_exec); 4451 } 4452 4453 4454 // Unmap a block of memory. 4455 // Returns true=success, otherwise false. 4456 4457 bool os::unmap_memory(char* addr, size_t bytes) { 4458 BOOL result = UnmapViewOfFile(addr); 4459 if (result == 0) { 4460 if (PrintMiscellaneous && Verbose) { 4461 DWORD err = GetLastError(); 4462 tty->print_cr("UnmapViewOfFile() failed: GetLastError->%ld.", err); 4463 } 4464 return false; 4465 } 4466 return true; 4467 } 4468 4469 void os::pause() { 4470 char filename[MAX_PATH]; 4471 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 4472 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 4473 } else { 4474 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 4475 } 4476 4477 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 4478 if (fd != -1) { 4479 struct stat buf; 4480 ::close(fd); 4481 while (::stat(filename, &buf) == 0) { 4482 Sleep(100); 4483 } 4484 } else { 4485 jio_fprintf(stderr, 4486 "Could not open pause file '%s', continuing immediately.\n", filename); 4487 } 4488 } 4489 4490 // An Event wraps a win32 "CreateEvent" kernel handle. 4491 // 4492 // We have a number of choices regarding "CreateEvent" win32 handle leakage: 4493 // 4494 // 1: When a thread dies return the Event to the EventFreeList, clear the ParkHandle 4495 // field, and call CloseHandle() on the win32 event handle. Unpark() would 4496 // need to be modified to tolerate finding a NULL (invalid) win32 event handle. 4497 // In addition, an unpark() operation might fetch the handle field, but the 4498 // event could recycle between the fetch and the SetEvent() operation. 4499 // SetEvent() would either fail because the handle was invalid, or inadvertently work, 4500 // as the win32 handle value had been recycled. In an ideal world calling SetEvent() 4501 // on an stale but recycled handle would be harmless, but in practice this might 4502 // confuse other non-Sun code, so it's not a viable approach. 4503 // 4504 // 2: Once a win32 event handle is associated with an Event, it remains associated 4505 // with the Event. The event handle is never closed. This could be construed 4506 // as handle leakage, but only up to the maximum # of threads that have been extant 4507 // at any one time. This shouldn't be an issue, as windows platforms typically 4508 // permit a process to have hundreds of thousands of open handles. 4509 // 4510 // 3: Same as (1), but periodically, at stop-the-world time, rundown the EventFreeList 4511 // and release unused handles. 4512 // 4513 // 4: Add a CRITICAL_SECTION to the Event to protect LD+SetEvent from LD;ST(null);CloseHandle. 4514 // It's not clear, however, that we wouldn't be trading one type of leak for another. 4515 // 4516 // 5. Use an RCU-like mechanism (Read-Copy Update). 4517 // Or perhaps something similar to Maged Michael's "Hazard pointers". 4518 // 4519 // We use (2). 4520 // 4521 // TODO-FIXME: 4522 // 1. Reconcile Doug's JSR166 j.u.c park-unpark with the objectmonitor implementation. 4523 // 2. Consider wrapping the WaitForSingleObject(Ex) calls in SEH try/finally blocks 4524 // to recover from (or at least detect) the dreaded Windows 841176 bug. 4525 // 3. Collapse the interrupt_event, the JSR166 parker event, and the objectmonitor ParkEvent 4526 // into a single win32 CreateEvent() handle. 4527 // 4528 // _Event transitions in park() 4529 // -1 => -1 : illegal 4530 // 1 => 0 : pass - return immediately 4531 // 0 => -1 : block 4532 // 4533 // _Event serves as a restricted-range semaphore : 4534 // -1 : thread is blocked 4535 // 0 : neutral - thread is running or ready 4536 // 1 : signaled - thread is running or ready 4537 // 4538 // Another possible encoding of _Event would be 4539 // with explicit "PARKED" and "SIGNALED" bits. 4540 4541 int os::PlatformEvent::park (jlong Millis) { 4542 guarantee (_ParkHandle != NULL , "Invariant") ; 4543 guarantee (Millis > 0 , "Invariant") ; 4544 int v ; 4545 4546 // CONSIDER: defer assigning a CreateEvent() handle to the Event until 4547 // the initial park() operation. 4548 4549 for (;;) { 4550 v = _Event ; 4551 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 4552 } 4553 guarantee ((v == 0) || (v == 1), "invariant") ; 4554 if (v != 0) return OS_OK ; 4555 4556 // Do this the hard way by blocking ... 4557 // TODO: consider a brief spin here, gated on the success of recent 4558 // spin attempts by this thread. 4559 // 4560 // We decompose long timeouts into series of shorter timed waits. 4561 // Evidently large timo values passed in WaitForSingleObject() are problematic on some 4562 // versions of Windows. See EventWait() for details. This may be superstition. Or not. 4563 // We trust the WAIT_TIMEOUT indication and don't track the elapsed wait time 4564 // with os::javaTimeNanos(). Furthermore, we assume that spurious returns from 4565 // ::WaitForSingleObject() caused by latent ::setEvent() operations will tend 4566 // to happen early in the wait interval. Specifically, after a spurious wakeup (rv == 4567 // WAIT_OBJECT_0 but _Event is still < 0) we don't bother to recompute Millis to compensate 4568 // for the already waited time. This policy does not admit any new outcomes. 4569 // In the future, however, we might want to track the accumulated wait time and 4570 // adjust Millis accordingly if we encounter a spurious wakeup. 4571 4572 const int MAXTIMEOUT = 0x10000000 ; 4573 DWORD rv = WAIT_TIMEOUT ; 4574 while (_Event < 0 && Millis > 0) { 4575 DWORD prd = Millis ; // set prd = MAX (Millis, MAXTIMEOUT) 4576 if (Millis > MAXTIMEOUT) { 4577 prd = MAXTIMEOUT ; 4578 } 4579 rv = ::WaitForSingleObject (_ParkHandle, prd) ; 4580 assert (rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed") ; 4581 if (rv == WAIT_TIMEOUT) { 4582 Millis -= prd ; 4583 } 4584 } 4585 v = _Event ; 4586 _Event = 0 ; 4587 OrderAccess::fence() ; 4588 // If we encounter a nearly simultanous timeout expiry and unpark() 4589 // we return OS_OK indicating we awoke via unpark(). 4590 // Implementor's license -- returning OS_TIMEOUT would be equally valid, however. 4591 return (v >= 0) ? OS_OK : OS_TIMEOUT ; 4592 } 4593 4594 void os::PlatformEvent::park () { 4595 guarantee (_ParkHandle != NULL, "Invariant") ; 4596 // Invariant: Only the thread associated with the Event/PlatformEvent 4597 // may call park(). 4598 int v ; 4599 for (;;) { 4600 v = _Event ; 4601 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 4602 } 4603 guarantee ((v == 0) || (v == 1), "invariant") ; 4604 if (v != 0) return ; 4605 4606 // Do this the hard way by blocking ... 4607 // TODO: consider a brief spin here, gated on the success of recent 4608 // spin attempts by this thread. 4609 while (_Event < 0) { 4610 DWORD rv = ::WaitForSingleObject (_ParkHandle, INFINITE) ; 4611 assert (rv == WAIT_OBJECT_0, "WaitForSingleObject failed") ; 4612 } 4613 4614 // Usually we'll find _Event == 0 at this point, but as 4615 // an optional optimization we clear it, just in case can 4616 // multiple unpark() operations drove _Event up to 1. 4617 _Event = 0 ; 4618 OrderAccess::fence() ; 4619 guarantee (_Event >= 0, "invariant") ; 4620 } 4621 4622 void os::PlatformEvent::unpark() { 4623 guarantee (_ParkHandle != NULL, "Invariant") ; 4624 int v ; 4625 for (;;) { 4626 v = _Event ; // Increment _Event if it's < 1. 4627 if (v > 0) { 4628 // If it's already signaled just return. 4629 // The LD of _Event could have reordered or be satisfied 4630 // by a read-aside from this processor's write buffer. 4631 // To avoid problems execute a barrier and then 4632 // ratify the value. A degenerate CAS() would also work. 4633 // Viz., CAS (v+0, &_Event, v) == v). 4634 OrderAccess::fence() ; 4635 if (_Event == v) return ; 4636 continue ; 4637 } 4638 if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ; 4639 } 4640 if (v < 0) { 4641 ::SetEvent (_ParkHandle) ; 4642 } 4643 } 4644 4645 4646 // JSR166 4647 // ------------------------------------------------------- 4648 4649 /* 4650 * The Windows implementation of Park is very straightforward: Basic 4651 * operations on Win32 Events turn out to have the right semantics to 4652 * use them directly. We opportunistically resuse the event inherited 4653 * from Monitor. 4654 */ 4655 4656 4657 void Parker::park(bool isAbsolute, jlong time) { 4658 guarantee (_ParkEvent != NULL, "invariant") ; 4659 // First, demultiplex/decode time arguments 4660 if (time < 0) { // don't wait 4661 return; 4662 } 4663 else if (time == 0 && !isAbsolute) { 4664 time = INFINITE; 4665 } 4666 else if (isAbsolute) { 4667 time -= os::javaTimeMillis(); // convert to relative time 4668 if (time <= 0) // already elapsed 4669 return; 4670 } 4671 else { // relative 4672 time /= 1000000; // Must coarsen from nanos to millis 4673 if (time == 0) // Wait for the minimal time unit if zero 4674 time = 1; 4675 } 4676 4677 JavaThread* thread = (JavaThread*)(Thread::current()); 4678 assert(thread->is_Java_thread(), "Must be JavaThread"); 4679 JavaThread *jt = (JavaThread *)thread; 4680 4681 // Don't wait if interrupted or already triggered 4682 if (Thread::is_interrupted(thread, false) || 4683 WaitForSingleObject(_ParkEvent, 0) == WAIT_OBJECT_0) { 4684 ResetEvent(_ParkEvent); 4685 return; 4686 } 4687 else { 4688 ThreadBlockInVM tbivm(jt); 4689 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 4690 jt->set_suspend_equivalent(); 4691 4692 WaitForSingleObject(_ParkEvent, time); 4693 ResetEvent(_ParkEvent); 4694 4695 // If externally suspended while waiting, re-suspend 4696 if (jt->handle_special_suspend_equivalent_condition()) { 4697 jt->java_suspend_self(); 4698 } 4699 } 4700 } 4701 4702 void Parker::unpark() { 4703 guarantee (_ParkEvent != NULL, "invariant") ; 4704 SetEvent(_ParkEvent); 4705 } 4706 4707 // Run the specified command in a separate process. Return its exit value, 4708 // or -1 on failure (e.g. can't create a new process). 4709 int os::fork_and_exec(char* cmd) { 4710 STARTUPINFO si; 4711 PROCESS_INFORMATION pi; 4712 4713 memset(&si, 0, sizeof(si)); 4714 si.cb = sizeof(si); 4715 memset(&pi, 0, sizeof(pi)); 4716 BOOL rslt = CreateProcess(NULL, // executable name - use command line 4717 cmd, // command line 4718 NULL, // process security attribute 4719 NULL, // thread security attribute 4720 TRUE, // inherits system handles 4721 0, // no creation flags 4722 NULL, // use parent's environment block 4723 NULL, // use parent's starting directory 4724 &si, // (in) startup information 4725 &pi); // (out) process information 4726 4727 if (rslt) { 4728 // Wait until child process exits. 4729 WaitForSingleObject(pi.hProcess, INFINITE); 4730 4731 DWORD exit_code; 4732 GetExitCodeProcess(pi.hProcess, &exit_code); 4733 4734 // Close process and thread handles. 4735 CloseHandle(pi.hProcess); 4736 CloseHandle(pi.hThread); 4737 4738 return (int)exit_code; 4739 } else { 4740 return -1; 4741 } 4742 } 4743 4744 //-------------------------------------------------------------------------------------------------- 4745 // Non-product code 4746 4747 static int mallocDebugIntervalCounter = 0; 4748 static int mallocDebugCounter = 0; 4749 bool os::check_heap(bool force) { 4750 if (++mallocDebugCounter < MallocVerifyStart && !force) return true; 4751 if (++mallocDebugIntervalCounter >= MallocVerifyInterval || force) { 4752 // Note: HeapValidate executes two hardware breakpoints when it finds something 4753 // wrong; at these points, eax contains the address of the offending block (I think). 4754 // To get to the exlicit error message(s) below, just continue twice. 4755 HANDLE heap = GetProcessHeap(); 4756 { HeapLock(heap); 4757 PROCESS_HEAP_ENTRY phe; 4758 phe.lpData = NULL; 4759 while (HeapWalk(heap, &phe) != 0) { 4760 if ((phe.wFlags & PROCESS_HEAP_ENTRY_BUSY) && 4761 !HeapValidate(heap, 0, phe.lpData)) { 4762 tty->print_cr("C heap has been corrupted (time: %d allocations)", mallocDebugCounter); 4763 tty->print_cr("corrupted block near address %#x, length %d", phe.lpData, phe.cbData); 4764 fatal("corrupted C heap"); 4765 } 4766 } 4767 DWORD err = GetLastError(); 4768 if (err != ERROR_NO_MORE_ITEMS && err != ERROR_CALL_NOT_IMPLEMENTED) { 4769 fatal(err_msg("heap walk aborted with error %d", err)); 4770 } 4771 HeapUnlock(heap); 4772 } 4773 mallocDebugIntervalCounter = 0; 4774 } 4775 return true; 4776 } 4777 4778 4779 bool os::find(address addr, outputStream* st) { 4780 // Nothing yet 4781 return false; 4782 } 4783 4784 LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) { 4785 DWORD exception_code = e->ExceptionRecord->ExceptionCode; 4786 4787 if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) { 4788 JavaThread* thread = (JavaThread*)ThreadLocalStorage::get_thread_slow(); 4789 PEXCEPTION_RECORD exceptionRecord = e->ExceptionRecord; 4790 address addr = (address) exceptionRecord->ExceptionInformation[1]; 4791 4792 if (os::is_memory_serialize_page(thread, addr)) 4793 return EXCEPTION_CONTINUE_EXECUTION; 4794 } 4795 4796 return EXCEPTION_CONTINUE_SEARCH; 4797 } 4798 4799 // We don't build a headless jre for Windows 4800 bool os::is_headless_jre() { return false; } 4801 4802 4803 typedef CRITICAL_SECTION mutex_t; 4804 #define mutexInit(m) InitializeCriticalSection(m) 4805 #define mutexDestroy(m) DeleteCriticalSection(m) 4806 #define mutexLock(m) EnterCriticalSection(m) 4807 #define mutexUnlock(m) LeaveCriticalSection(m) 4808 4809 static bool sock_initialized = FALSE; 4810 static mutex_t sockFnTableMutex; 4811 4812 static void initSock() { 4813 WSADATA wsadata; 4814 4815 if (!os::WinSock2Dll::WinSock2Available()) { 4816 jio_fprintf(stderr, "Could not load Winsock 2 (error: %d)\n", 4817 ::GetLastError()); 4818 return; 4819 } 4820 if (sock_initialized == TRUE) return; 4821 4822 ::mutexInit(&sockFnTableMutex); 4823 ::mutexLock(&sockFnTableMutex); 4824 if (os::WinSock2Dll::WSAStartup(MAKEWORD(1,1), &wsadata) != 0) { 4825 jio_fprintf(stderr, "Could not initialize Winsock\n"); 4826 } 4827 sock_initialized = TRUE; 4828 ::mutexUnlock(&sockFnTableMutex); 4829 } 4830 4831 struct hostent* os::get_host_by_name(char* name) { 4832 if (!sock_initialized) { 4833 initSock(); 4834 } 4835 if (!os::WinSock2Dll::WinSock2Available()) { 4836 return NULL; 4837 } 4838 return (struct hostent*)os::WinSock2Dll::gethostbyname(name); 4839 } 4840 4841 int os::socket_close(int fd) { 4842 return ::closesocket(fd); 4843 } 4844 4845 int os::socket_available(int fd, jint *pbytes) { 4846 int ret = ::ioctlsocket(fd, FIONREAD, (u_long*)pbytes); 4847 return (ret < 0) ? 0 : 1; 4848 } 4849 4850 int os::socket(int domain, int type, int protocol) { 4851 return ::socket(domain, type, protocol); 4852 } 4853 4854 int os::listen(int fd, int count) { 4855 return ::listen(fd, count); 4856 } 4857 4858 int os::connect(int fd, struct sockaddr* him, socklen_t len) { 4859 return ::connect(fd, him, len); 4860 } 4861 4862 int os::accept(int fd, struct sockaddr* him, socklen_t* len) { 4863 return ::accept(fd, him, len); 4864 } 4865 4866 int os::sendto(int fd, char* buf, size_t len, uint flags, 4867 struct sockaddr* to, socklen_t tolen) { 4868 4869 return ::sendto(fd, buf, (int)len, flags, to, tolen); 4870 } 4871 4872 int os::recvfrom(int fd, char *buf, size_t nBytes, uint flags, 4873 sockaddr* from, socklen_t* fromlen) { 4874 4875 return ::recvfrom(fd, buf, (int)nBytes, flags, from, fromlen); 4876 } 4877 4878 int os::recv(int fd, char* buf, size_t nBytes, uint flags) { 4879 return ::recv(fd, buf, (int)nBytes, flags); 4880 } 4881 4882 int os::send(int fd, char* buf, size_t nBytes, uint flags) { 4883 return ::send(fd, buf, (int)nBytes, flags); 4884 } 4885 4886 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) { 4887 return ::send(fd, buf, (int)nBytes, flags); 4888 } 4889 4890 int os::timeout(int fd, long timeout) { 4891 fd_set tbl; 4892 struct timeval t; 4893 4894 t.tv_sec = timeout / 1000; 4895 t.tv_usec = (timeout % 1000) * 1000; 4896 4897 tbl.fd_count = 1; 4898 tbl.fd_array[0] = fd; 4899 4900 return ::select(1, &tbl, 0, 0, &t); 4901 } 4902 4903 int os::get_host_name(char* name, int namelen) { 4904 return ::gethostname(name, namelen); 4905 } 4906 4907 int os::socket_shutdown(int fd, int howto) { 4908 return ::shutdown(fd, howto); 4909 } 4910 4911 int os::bind(int fd, struct sockaddr* him, socklen_t len) { 4912 return ::bind(fd, him, len); 4913 } 4914 4915 int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len) { 4916 return ::getsockname(fd, him, len); 4917 } 4918 4919 int os::get_sock_opt(int fd, int level, int optname, 4920 char* optval, socklen_t* optlen) { 4921 return ::getsockopt(fd, level, optname, optval, optlen); 4922 } 4923 4924 int os::set_sock_opt(int fd, int level, int optname, 4925 const char* optval, socklen_t optlen) { 4926 return ::setsockopt(fd, level, optname, optval, optlen); 4927 } 4928 4929 4930 // Kernel32 API 4931 typedef SIZE_T (WINAPI* GetLargePageMinimum_Fn)(void); 4932 typedef LPVOID (WINAPI *VirtualAllocExNuma_Fn) (HANDLE, LPVOID, SIZE_T, DWORD, DWORD, DWORD); 4933 typedef BOOL (WINAPI *GetNumaHighestNodeNumber_Fn) (PULONG); 4934 typedef BOOL (WINAPI *GetNumaNodeProcessorMask_Fn) (UCHAR, PULONGLONG); 4935 4936 GetLargePageMinimum_Fn os::Kernel32Dll::_GetLargePageMinimum = NULL; 4937 VirtualAllocExNuma_Fn os::Kernel32Dll::_VirtualAllocExNuma = NULL; 4938 GetNumaHighestNodeNumber_Fn os::Kernel32Dll::_GetNumaHighestNodeNumber = NULL; 4939 GetNumaNodeProcessorMask_Fn os::Kernel32Dll::_GetNumaNodeProcessorMask = NULL; 4940 BOOL os::Kernel32Dll::initialized = FALSE; 4941 SIZE_T os::Kernel32Dll::GetLargePageMinimum() { 4942 assert(initialized && _GetLargePageMinimum != NULL, 4943 "GetLargePageMinimumAvailable() not yet called"); 4944 return _GetLargePageMinimum(); 4945 } 4946 4947 BOOL os::Kernel32Dll::GetLargePageMinimumAvailable() { 4948 if (!initialized) { 4949 initialize(); 4950 } 4951 return _GetLargePageMinimum != NULL; 4952 } 4953 4954 BOOL os::Kernel32Dll::NumaCallsAvailable() { 4955 if (!initialized) { 4956 initialize(); 4957 } 4958 return _VirtualAllocExNuma != NULL; 4959 } 4960 4961 LPVOID os::Kernel32Dll::VirtualAllocExNuma(HANDLE hProc, LPVOID addr, SIZE_T bytes, DWORD flags, DWORD prot, DWORD node) { 4962 assert(initialized && _VirtualAllocExNuma != NULL, 4963 "NUMACallsAvailable() not yet called"); 4964 4965 return _VirtualAllocExNuma(hProc, addr, bytes, flags, prot, node); 4966 } 4967 4968 BOOL os::Kernel32Dll::GetNumaHighestNodeNumber(PULONG ptr_highest_node_number) { 4969 assert(initialized && _GetNumaHighestNodeNumber != NULL, 4970 "NUMACallsAvailable() not yet called"); 4971 4972 return _GetNumaHighestNodeNumber(ptr_highest_node_number); 4973 } 4974 4975 BOOL os::Kernel32Dll::GetNumaNodeProcessorMask(UCHAR node, PULONGLONG proc_mask) { 4976 assert(initialized && _GetNumaNodeProcessorMask != NULL, 4977 "NUMACallsAvailable() not yet called"); 4978 4979 return _GetNumaNodeProcessorMask(node, proc_mask); 4980 } 4981 4982 4983 void os::Kernel32Dll::initializeCommon() { 4984 if (!initialized) { 4985 HMODULE handle = ::GetModuleHandle("Kernel32.dll"); 4986 assert(handle != NULL, "Just check"); 4987 _GetLargePageMinimum = (GetLargePageMinimum_Fn)::GetProcAddress(handle, "GetLargePageMinimum"); 4988 _VirtualAllocExNuma = (VirtualAllocExNuma_Fn)::GetProcAddress(handle, "VirtualAllocExNuma"); 4989 _GetNumaHighestNodeNumber = (GetNumaHighestNodeNumber_Fn)::GetProcAddress(handle, "GetNumaHighestNodeNumber"); 4990 _GetNumaNodeProcessorMask = (GetNumaNodeProcessorMask_Fn)::GetProcAddress(handle, "GetNumaNodeProcessorMask"); 4991 initialized = TRUE; 4992 } 4993 } 4994 4995 4996 4997 #ifndef JDK6_OR_EARLIER 4998 4999 void os::Kernel32Dll::initialize() { 5000 initializeCommon(); 5001 } 5002 5003 5004 // Kernel32 API 5005 inline BOOL os::Kernel32Dll::SwitchToThread() { 5006 return ::SwitchToThread(); 5007 } 5008 5009 inline BOOL os::Kernel32Dll::SwitchToThreadAvailable() { 5010 return true; 5011 } 5012 5013 // Help tools 5014 inline BOOL os::Kernel32Dll::HelpToolsAvailable() { 5015 return true; 5016 } 5017 5018 inline HANDLE os::Kernel32Dll::CreateToolhelp32Snapshot(DWORD dwFlags,DWORD th32ProcessId) { 5019 return ::CreateToolhelp32Snapshot(dwFlags, th32ProcessId); 5020 } 5021 5022 inline BOOL os::Kernel32Dll::Module32First(HANDLE hSnapshot,LPMODULEENTRY32 lpme) { 5023 return ::Module32First(hSnapshot, lpme); 5024 } 5025 5026 inline BOOL os::Kernel32Dll::Module32Next(HANDLE hSnapshot,LPMODULEENTRY32 lpme) { 5027 return ::Module32Next(hSnapshot, lpme); 5028 } 5029 5030 5031 inline BOOL os::Kernel32Dll::GetNativeSystemInfoAvailable() { 5032 return true; 5033 } 5034 5035 inline void os::Kernel32Dll::GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo) { 5036 ::GetNativeSystemInfo(lpSystemInfo); 5037 } 5038 5039 // PSAPI API 5040 inline BOOL os::PSApiDll::EnumProcessModules(HANDLE hProcess, HMODULE *lpModule, DWORD cb, LPDWORD lpcbNeeded) { 5041 return ::EnumProcessModules(hProcess, lpModule, cb, lpcbNeeded); 5042 } 5043 5044 inline DWORD os::PSApiDll::GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize) { 5045 return ::GetModuleFileNameEx(hProcess, hModule, lpFilename, nSize); 5046 } 5047 5048 inline BOOL os::PSApiDll::GetModuleInformation(HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb) { 5049 return ::GetModuleInformation(hProcess, hModule, lpmodinfo, cb); 5050 } 5051 5052 inline BOOL os::PSApiDll::PSApiAvailable() { 5053 return true; 5054 } 5055 5056 5057 // WinSock2 API 5058 inline BOOL os::WinSock2Dll::WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData) { 5059 return ::WSAStartup(wVersionRequested, lpWSAData); 5060 } 5061 5062 inline struct hostent* os::WinSock2Dll::gethostbyname(const char *name) { 5063 return ::gethostbyname(name); 5064 } 5065 5066 inline BOOL os::WinSock2Dll::WinSock2Available() { 5067 return true; 5068 } 5069 5070 // Advapi API 5071 inline BOOL os::Advapi32Dll::AdjustTokenPrivileges(HANDLE TokenHandle, 5072 BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, 5073 PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength) { 5074 return ::AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, NewState, 5075 BufferLength, PreviousState, ReturnLength); 5076 } 5077 5078 inline BOOL os::Advapi32Dll::OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, 5079 PHANDLE TokenHandle) { 5080 return ::OpenProcessToken(ProcessHandle, DesiredAccess, TokenHandle); 5081 } 5082 5083 inline BOOL os::Advapi32Dll::LookupPrivilegeValue(LPCTSTR lpSystemName, LPCTSTR lpName, PLUID lpLuid) { 5084 return ::LookupPrivilegeValue(lpSystemName, lpName, lpLuid); 5085 } 5086 5087 inline BOOL os::Advapi32Dll::AdvapiAvailable() { 5088 return true; 5089 } 5090 5091 #else 5092 // Kernel32 API 5093 typedef BOOL (WINAPI* SwitchToThread_Fn)(void); 5094 typedef HANDLE (WINAPI* CreateToolhelp32Snapshot_Fn)(DWORD,DWORD); 5095 typedef BOOL (WINAPI* Module32First_Fn)(HANDLE,LPMODULEENTRY32); 5096 typedef BOOL (WINAPI* Module32Next_Fn)(HANDLE,LPMODULEENTRY32); 5097 typedef void (WINAPI* GetNativeSystemInfo_Fn)(LPSYSTEM_INFO); 5098 5099 SwitchToThread_Fn os::Kernel32Dll::_SwitchToThread = NULL; 5100 CreateToolhelp32Snapshot_Fn os::Kernel32Dll::_CreateToolhelp32Snapshot = NULL; 5101 Module32First_Fn os::Kernel32Dll::_Module32First = NULL; 5102 Module32Next_Fn os::Kernel32Dll::_Module32Next = NULL; 5103 GetNativeSystemInfo_Fn os::Kernel32Dll::_GetNativeSystemInfo = NULL; 5104 5105 5106 void os::Kernel32Dll::initialize() { 5107 if (!initialized) { 5108 HMODULE handle = ::GetModuleHandle("Kernel32.dll"); 5109 assert(handle != NULL, "Just check"); 5110 5111 _SwitchToThread = (SwitchToThread_Fn)::GetProcAddress(handle, "SwitchToThread"); 5112 _CreateToolhelp32Snapshot = (CreateToolhelp32Snapshot_Fn) 5113 ::GetProcAddress(handle, "CreateToolhelp32Snapshot"); 5114 _Module32First = (Module32First_Fn)::GetProcAddress(handle, "Module32First"); 5115 _Module32Next = (Module32Next_Fn)::GetProcAddress(handle, "Module32Next"); 5116 _GetNativeSystemInfo = (GetNativeSystemInfo_Fn)::GetProcAddress(handle, "GetNativeSystemInfo"); 5117 initializeCommon(); // resolve the functions that always need resolving 5118 5119 initialized = TRUE; 5120 } 5121 } 5122 5123 BOOL os::Kernel32Dll::SwitchToThread() { 5124 assert(initialized && _SwitchToThread != NULL, 5125 "SwitchToThreadAvailable() not yet called"); 5126 return _SwitchToThread(); 5127 } 5128 5129 5130 BOOL os::Kernel32Dll::SwitchToThreadAvailable() { 5131 if (!initialized) { 5132 initialize(); 5133 } 5134 return _SwitchToThread != NULL; 5135 } 5136 5137 // Help tools 5138 BOOL os::Kernel32Dll::HelpToolsAvailable() { 5139 if (!initialized) { 5140 initialize(); 5141 } 5142 return _CreateToolhelp32Snapshot != NULL && 5143 _Module32First != NULL && 5144 _Module32Next != NULL; 5145 } 5146 5147 HANDLE os::Kernel32Dll::CreateToolhelp32Snapshot(DWORD dwFlags,DWORD th32ProcessId) { 5148 assert(initialized && _CreateToolhelp32Snapshot != NULL, 5149 "HelpToolsAvailable() not yet called"); 5150 5151 return _CreateToolhelp32Snapshot(dwFlags, th32ProcessId); 5152 } 5153 5154 BOOL os::Kernel32Dll::Module32First(HANDLE hSnapshot,LPMODULEENTRY32 lpme) { 5155 assert(initialized && _Module32First != NULL, 5156 "HelpToolsAvailable() not yet called"); 5157 5158 return _Module32First(hSnapshot, lpme); 5159 } 5160 5161 inline BOOL os::Kernel32Dll::Module32Next(HANDLE hSnapshot,LPMODULEENTRY32 lpme) { 5162 assert(initialized && _Module32Next != NULL, 5163 "HelpToolsAvailable() not yet called"); 5164 5165 return _Module32Next(hSnapshot, lpme); 5166 } 5167 5168 5169 BOOL os::Kernel32Dll::GetNativeSystemInfoAvailable() { 5170 if (!initialized) { 5171 initialize(); 5172 } 5173 return _GetNativeSystemInfo != NULL; 5174 } 5175 5176 void os::Kernel32Dll::GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo) { 5177 assert(initialized && _GetNativeSystemInfo != NULL, 5178 "GetNativeSystemInfoAvailable() not yet called"); 5179 5180 _GetNativeSystemInfo(lpSystemInfo); 5181 } 5182 5183 5184 5185 // PSAPI API 5186 5187 5188 typedef BOOL (WINAPI *EnumProcessModules_Fn)(HANDLE, HMODULE *, DWORD, LPDWORD); 5189 typedef BOOL (WINAPI *GetModuleFileNameEx_Fn)(HANDLE, HMODULE, LPTSTR, DWORD);; 5190 typedef BOOL (WINAPI *GetModuleInformation_Fn)(HANDLE, HMODULE, LPMODULEINFO, DWORD); 5191 5192 EnumProcessModules_Fn os::PSApiDll::_EnumProcessModules = NULL; 5193 GetModuleFileNameEx_Fn os::PSApiDll::_GetModuleFileNameEx = NULL; 5194 GetModuleInformation_Fn os::PSApiDll::_GetModuleInformation = NULL; 5195 BOOL os::PSApiDll::initialized = FALSE; 5196 5197 void os::PSApiDll::initialize() { 5198 if (!initialized) { 5199 HMODULE handle = os::win32::load_Windows_dll("PSAPI.DLL", NULL, 0); 5200 if (handle != NULL) { 5201 _EnumProcessModules = (EnumProcessModules_Fn)::GetProcAddress(handle, 5202 "EnumProcessModules"); 5203 _GetModuleFileNameEx = (GetModuleFileNameEx_Fn)::GetProcAddress(handle, 5204 "GetModuleFileNameExA"); 5205 _GetModuleInformation = (GetModuleInformation_Fn)::GetProcAddress(handle, 5206 "GetModuleInformation"); 5207 } 5208 initialized = TRUE; 5209 } 5210 } 5211 5212 5213 5214 BOOL os::PSApiDll::EnumProcessModules(HANDLE hProcess, HMODULE *lpModule, DWORD cb, LPDWORD lpcbNeeded) { 5215 assert(initialized && _EnumProcessModules != NULL, 5216 "PSApiAvailable() not yet called"); 5217 return _EnumProcessModules(hProcess, lpModule, cb, lpcbNeeded); 5218 } 5219 5220 DWORD os::PSApiDll::GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize) { 5221 assert(initialized && _GetModuleFileNameEx != NULL, 5222 "PSApiAvailable() not yet called"); 5223 return _GetModuleFileNameEx(hProcess, hModule, lpFilename, nSize); 5224 } 5225 5226 BOOL os::PSApiDll::GetModuleInformation(HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb) { 5227 assert(initialized && _GetModuleInformation != NULL, 5228 "PSApiAvailable() not yet called"); 5229 return _GetModuleInformation(hProcess, hModule, lpmodinfo, cb); 5230 } 5231 5232 BOOL os::PSApiDll::PSApiAvailable() { 5233 if (!initialized) { 5234 initialize(); 5235 } 5236 return _EnumProcessModules != NULL && 5237 _GetModuleFileNameEx != NULL && 5238 _GetModuleInformation != NULL; 5239 } 5240 5241 5242 // WinSock2 API 5243 typedef int (PASCAL FAR* WSAStartup_Fn)(WORD, LPWSADATA); 5244 typedef struct hostent *(PASCAL FAR *gethostbyname_Fn)(...); 5245 5246 WSAStartup_Fn os::WinSock2Dll::_WSAStartup = NULL; 5247 gethostbyname_Fn os::WinSock2Dll::_gethostbyname = NULL; 5248 BOOL os::WinSock2Dll::initialized = FALSE; 5249 5250 void os::WinSock2Dll::initialize() { 5251 if (!initialized) { 5252 HMODULE handle = os::win32::load_Windows_dll("ws2_32.dll", NULL, 0); 5253 if (handle != NULL) { 5254 _WSAStartup = (WSAStartup_Fn)::GetProcAddress(handle, "WSAStartup"); 5255 _gethostbyname = (gethostbyname_Fn)::GetProcAddress(handle, "gethostbyname"); 5256 } 5257 initialized = TRUE; 5258 } 5259 } 5260 5261 5262 BOOL os::WinSock2Dll::WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData) { 5263 assert(initialized && _WSAStartup != NULL, 5264 "WinSock2Available() not yet called"); 5265 return _WSAStartup(wVersionRequested, lpWSAData); 5266 } 5267 5268 struct hostent* os::WinSock2Dll::gethostbyname(const char *name) { 5269 assert(initialized && _gethostbyname != NULL, 5270 "WinSock2Available() not yet called"); 5271 return _gethostbyname(name); 5272 } 5273 5274 BOOL os::WinSock2Dll::WinSock2Available() { 5275 if (!initialized) { 5276 initialize(); 5277 } 5278 return _WSAStartup != NULL && 5279 _gethostbyname != NULL; 5280 } 5281 5282 typedef BOOL (WINAPI *AdjustTokenPrivileges_Fn)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD); 5283 typedef BOOL (WINAPI *OpenProcessToken_Fn)(HANDLE, DWORD, PHANDLE); 5284 typedef BOOL (WINAPI *LookupPrivilegeValue_Fn)(LPCTSTR, LPCTSTR, PLUID); 5285 5286 AdjustTokenPrivileges_Fn os::Advapi32Dll::_AdjustTokenPrivileges = NULL; 5287 OpenProcessToken_Fn os::Advapi32Dll::_OpenProcessToken = NULL; 5288 LookupPrivilegeValue_Fn os::Advapi32Dll::_LookupPrivilegeValue = NULL; 5289 BOOL os::Advapi32Dll::initialized = FALSE; 5290 5291 void os::Advapi32Dll::initialize() { 5292 if (!initialized) { 5293 HMODULE handle = os::win32::load_Windows_dll("advapi32.dll", NULL, 0); 5294 if (handle != NULL) { 5295 _AdjustTokenPrivileges = (AdjustTokenPrivileges_Fn)::GetProcAddress(handle, 5296 "AdjustTokenPrivileges"); 5297 _OpenProcessToken = (OpenProcessToken_Fn)::GetProcAddress(handle, 5298 "OpenProcessToken"); 5299 _LookupPrivilegeValue = (LookupPrivilegeValue_Fn)::GetProcAddress(handle, 5300 "LookupPrivilegeValueA"); 5301 } 5302 initialized = TRUE; 5303 } 5304 } 5305 5306 BOOL os::Advapi32Dll::AdjustTokenPrivileges(HANDLE TokenHandle, 5307 BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, 5308 PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength) { 5309 assert(initialized && _AdjustTokenPrivileges != NULL, 5310 "AdvapiAvailable() not yet called"); 5311 return _AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, NewState, 5312 BufferLength, PreviousState, ReturnLength); 5313 } 5314 5315 BOOL os::Advapi32Dll::OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, 5316 PHANDLE TokenHandle) { 5317 assert(initialized && _OpenProcessToken != NULL, 5318 "AdvapiAvailable() not yet called"); 5319 return _OpenProcessToken(ProcessHandle, DesiredAccess, TokenHandle); 5320 } 5321 5322 BOOL os::Advapi32Dll::LookupPrivilegeValue(LPCTSTR lpSystemName, LPCTSTR lpName, PLUID lpLuid) { 5323 assert(initialized && _LookupPrivilegeValue != NULL, 5324 "AdvapiAvailable() not yet called"); 5325 return _LookupPrivilegeValue(lpSystemName, lpName, lpLuid); 5326 } 5327 5328 BOOL os::Advapi32Dll::AdvapiAvailable() { 5329 if (!initialized) { 5330 initialize(); 5331 } 5332 return _AdjustTokenPrivileges != NULL && 5333 _OpenProcessToken != NULL && 5334 _LookupPrivilegeValue != NULL; 5335 } 5336 5337 #endif