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