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