1 /* 2 * Copyright 1997-2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 20 * CA 95054 USA or visit www.sun.com if you need additional information or 21 * have any questions. 22 * 23 */ 24 25 #ifdef _WIN64 26 // Must be at least Windows 2000 or XP to use VectoredExceptions 27 #define _WIN32_WINNT 0x500 28 #endif 29 30 // do not include precompiled header file 31 # include "incls/_os_windows.cpp.incl" 32 33 #ifdef _DEBUG 34 #include <crtdbg.h> 35 #endif 36 37 38 #include <windows.h> 39 #include <sys/types.h> 40 #include <sys/stat.h> 41 #include <sys/timeb.h> 42 #include <objidl.h> 43 #include <shlobj.h> 44 45 #include <malloc.h> 46 #include <signal.h> 47 #include <direct.h> 48 #include <errno.h> 49 #include <fcntl.h> 50 #include <io.h> 51 #include <process.h> // For _beginthreadex(), _endthreadex() 52 #include <imagehlp.h> // For os::dll_address_to_function_name 53 54 /* for enumerating dll libraries */ 55 #include <tlhelp32.h> 56 #include <vdmdbg.h> 57 58 // for timer info max values which include all bits 59 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 60 61 // For DLL loading/load error detection 62 // Values of PE COFF 63 #define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c 64 #define IMAGE_FILE_SIGNATURE_LENGTH 4 65 66 static HANDLE main_process; 67 static HANDLE main_thread; 68 static int main_thread_id; 69 70 static FILETIME process_creation_time; 71 static FILETIME process_exit_time; 72 static FILETIME process_user_time; 73 static FILETIME process_kernel_time; 74 75 #ifdef _WIN64 76 PVOID topLevelVectoredExceptionHandler = NULL; 77 #endif 78 79 #ifdef _M_IA64 80 #define __CPU__ ia64 81 #elif _M_AMD64 82 #define __CPU__ amd64 83 #else 84 #define __CPU__ i486 85 #endif 86 87 // save DLL module handle, used by GetModuleFileName 88 89 HINSTANCE vm_lib_handle; 90 static int getLastErrorString(char *buf, size_t len); 91 92 BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) { 93 switch (reason) { 94 case DLL_PROCESS_ATTACH: 95 vm_lib_handle = hinst; 96 if(ForceTimeHighResolution) 97 timeBeginPeriod(1L); 98 break; 99 case DLL_PROCESS_DETACH: 100 if(ForceTimeHighResolution) 101 timeEndPeriod(1L); 102 #ifdef _WIN64 103 if (topLevelVectoredExceptionHandler != NULL) { 104 RemoveVectoredExceptionHandler(topLevelVectoredExceptionHandler); 105 topLevelVectoredExceptionHandler = NULL; 106 } 107 #endif 108 break; 109 default: 110 break; 111 } 112 return true; 113 } 114 115 static inline double fileTimeAsDouble(FILETIME* time) { 116 const double high = (double) ((unsigned int) ~0); 117 const double split = 10000000.0; 118 double result = (time->dwLowDateTime / split) + 119 time->dwHighDateTime * (high/split); 120 return result; 121 } 122 123 // Implementation of os 124 125 bool os::getenv(const char* name, char* buffer, int len) { 126 int result = GetEnvironmentVariable(name, buffer, len); 127 return result > 0 && result < len; 128 } 129 130 131 // No setuid programs under Windows. 132 bool os::have_special_privileges() { 133 return false; 134 } 135 136 137 // This method is a periodic task to check for misbehaving JNI applications 138 // under CheckJNI, we can add any periodic checks here. 139 // For Windows at the moment does nothing 140 void os::run_periodic_checks() { 141 return; 142 } 143 144 #ifndef _WIN64 145 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo); 146 #endif 147 void os::init_system_properties_values() { 148 /* sysclasspath, java_home, dll_dir */ 149 { 150 char *home_path; 151 char *dll_path; 152 char *pslash; 153 char *bin = "\\bin"; 154 char home_dir[MAX_PATH]; 155 156 if (!getenv("_ALT_JAVA_HOME_DIR", home_dir, MAX_PATH)) { 157 os::jvm_path(home_dir, sizeof(home_dir)); 158 // Found the full path to jvm[_g].dll. 159 // Now cut the path to <java_home>/jre if we can. 160 *(strrchr(home_dir, '\\')) = '\0'; /* get rid of \jvm.dll */ 161 pslash = strrchr(home_dir, '\\'); 162 if (pslash != NULL) { 163 *pslash = '\0'; /* get rid of \{client|server} */ 164 pslash = strrchr(home_dir, '\\'); 165 if (pslash != NULL) 166 *pslash = '\0'; /* get rid of \bin */ 167 } 168 } 169 170 home_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + 1); 171 if (home_path == NULL) 172 return; 173 strcpy(home_path, home_dir); 174 Arguments::set_java_home(home_path); 175 176 dll_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + strlen(bin) + 1); 177 if (dll_path == NULL) 178 return; 179 strcpy(dll_path, home_dir); 180 strcat(dll_path, bin); 181 Arguments::set_dll_dir(dll_path); 182 183 if (!set_boot_path('\\', ';')) 184 return; 185 } 186 187 /* library_path */ 188 #define EXT_DIR "\\lib\\ext" 189 #define BIN_DIR "\\bin" 190 #define PACKAGE_DIR "\\Sun\\Java" 191 { 192 /* Win32 library search order (See the documentation for LoadLibrary): 193 * 194 * 1. The directory from which application is loaded. 195 * 2. The current directory 196 * 3. The system wide Java Extensions directory (Java only) 197 * 4. System directory (GetSystemDirectory) 198 * 5. Windows directory (GetWindowsDirectory) 199 * 6. The PATH environment variable 200 */ 201 202 char *library_path; 203 char tmp[MAX_PATH]; 204 char *path_str = ::getenv("PATH"); 205 206 library_path = NEW_C_HEAP_ARRAY(char, MAX_PATH * 5 + sizeof(PACKAGE_DIR) + 207 sizeof(BIN_DIR) + (path_str ? strlen(path_str) : 0) + 10); 208 209 library_path[0] = '\0'; 210 211 GetModuleFileName(NULL, tmp, sizeof(tmp)); 212 *(strrchr(tmp, '\\')) = '\0'; 213 strcat(library_path, tmp); 214 215 strcat(library_path, ";."); 216 217 GetWindowsDirectory(tmp, sizeof(tmp)); 218 strcat(library_path, ";"); 219 strcat(library_path, tmp); 220 strcat(library_path, PACKAGE_DIR BIN_DIR); 221 222 GetSystemDirectory(tmp, sizeof(tmp)); 223 strcat(library_path, ";"); 224 strcat(library_path, tmp); 225 226 GetWindowsDirectory(tmp, sizeof(tmp)); 227 strcat(library_path, ";"); 228 strcat(library_path, tmp); 229 230 if (path_str) { 231 strcat(library_path, ";"); 232 strcat(library_path, path_str); 233 } 234 235 Arguments::set_library_path(library_path); 236 FREE_C_HEAP_ARRAY(char, library_path); 237 } 238 239 /* Default extensions directory */ 240 { 241 char path[MAX_PATH]; 242 char buf[2 * MAX_PATH + 2 * sizeof(EXT_DIR) + sizeof(PACKAGE_DIR) + 1]; 243 GetWindowsDirectory(path, MAX_PATH); 244 sprintf(buf, "%s%s;%s%s%s", Arguments::get_java_home(), EXT_DIR, 245 path, PACKAGE_DIR, EXT_DIR); 246 Arguments::set_ext_dirs(buf); 247 } 248 #undef EXT_DIR 249 #undef BIN_DIR 250 #undef PACKAGE_DIR 251 252 /* Default endorsed standards directory. */ 253 { 254 #define ENDORSED_DIR "\\lib\\endorsed" 255 size_t len = strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR); 256 char * buf = NEW_C_HEAP_ARRAY(char, len); 257 sprintf(buf, "%s%s", Arguments::get_java_home(), ENDORSED_DIR); 258 Arguments::set_endorsed_dirs(buf); 259 #undef ENDORSED_DIR 260 } 261 262 #ifndef _WIN64 263 SetUnhandledExceptionFilter(Handle_FLT_Exception); 264 #endif 265 266 // Done 267 return; 268 } 269 270 void os::breakpoint() { 271 DebugBreak(); 272 } 273 274 // Invoked from the BREAKPOINT Macro 275 extern "C" void breakpoint() { 276 os::breakpoint(); 277 } 278 279 // Returns an estimate of the current stack pointer. Result must be guaranteed 280 // to point into the calling threads stack, and be no lower than the current 281 // stack pointer. 282 283 address os::current_stack_pointer() { 284 int dummy; 285 address sp = (address)&dummy; 286 return sp; 287 } 288 289 // os::current_stack_base() 290 // 291 // Returns the base of the stack, which is the stack's 292 // starting address. This function must be called 293 // while running on the stack of the thread being queried. 294 295 address os::current_stack_base() { 296 MEMORY_BASIC_INFORMATION minfo; 297 address stack_bottom; 298 size_t stack_size; 299 300 VirtualQuery(&minfo, &minfo, sizeof(minfo)); 301 stack_bottom = (address)minfo.AllocationBase; 302 stack_size = minfo.RegionSize; 303 304 // Add up the sizes of all the regions with the same 305 // AllocationBase. 306 while( 1 ) 307 { 308 VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo)); 309 if ( stack_bottom == (address)minfo.AllocationBase ) 310 stack_size += minfo.RegionSize; 311 else 312 break; 313 } 314 315 #ifdef _M_IA64 316 // IA64 has memory and register stacks 317 stack_size = stack_size / 2; 318 #endif 319 return stack_bottom + stack_size; 320 } 321 322 size_t os::current_stack_size() { 323 size_t sz; 324 MEMORY_BASIC_INFORMATION minfo; 325 VirtualQuery(&minfo, &minfo, sizeof(minfo)); 326 sz = (size_t)os::current_stack_base() - (size_t)minfo.AllocationBase; 327 return sz; 328 } 329 330 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 331 const struct tm* time_struct_ptr = localtime(clock); 332 if (time_struct_ptr != NULL) { 333 *res = *time_struct_ptr; 334 return res; 335 } 336 return NULL; 337 } 338 339 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo); 340 341 // Thread start routine for all new Java threads 342 static unsigned __stdcall java_start(Thread* thread) { 343 // Try to randomize the cache line index of hot stack frames. 344 // This helps when threads of the same stack traces evict each other's 345 // cache lines. The threads can be either from the same JVM instance, or 346 // from different JVM instances. The benefit is especially true for 347 // processors with hyperthreading technology. 348 static int counter = 0; 349 int pid = os::current_process_id(); 350 _alloca(((pid ^ counter++) & 7) * 128); 351 352 OSThread* osthr = thread->osthread(); 353 assert(osthr->get_state() == RUNNABLE, "invalid os thread state"); 354 355 if (UseNUMA) { 356 int lgrp_id = os::numa_get_group_id(); 357 if (lgrp_id != -1) { 358 thread->set_lgrp_id(lgrp_id); 359 } 360 } 361 362 363 if (UseVectoredExceptions) { 364 // If we are using vectored exception we don't need to set a SEH 365 thread->run(); 366 } 367 else { 368 // Install a win32 structured exception handler around every thread created 369 // by VM, so VM can genrate error dump when an exception occurred in non- 370 // Java thread (e.g. VM thread). 371 __try { 372 thread->run(); 373 } __except(topLevelExceptionFilter( 374 (_EXCEPTION_POINTERS*)_exception_info())) { 375 // Nothing to do. 376 } 377 } 378 379 // One less thread is executing 380 // When the VMThread gets here, the main thread may have already exited 381 // which frees the CodeHeap containing the Atomic::add code 382 if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) { 383 Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count); 384 } 385 386 return 0; 387 } 388 389 static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle, int thread_id) { 390 // Allocate the OSThread object 391 OSThread* osthread = new OSThread(NULL, NULL); 392 if (osthread == NULL) return NULL; 393 394 // Initialize support for Java interrupts 395 HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL); 396 if (interrupt_event == NULL) { 397 delete osthread; 398 return NULL; 399 } 400 osthread->set_interrupt_event(interrupt_event); 401 402 // Store info on the Win32 thread into the OSThread 403 osthread->set_thread_handle(thread_handle); 404 osthread->set_thread_id(thread_id); 405 406 if (UseNUMA) { 407 int lgrp_id = os::numa_get_group_id(); 408 if (lgrp_id != -1) { 409 thread->set_lgrp_id(lgrp_id); 410 } 411 } 412 413 // Initial thread state is INITIALIZED, not SUSPENDED 414 osthread->set_state(INITIALIZED); 415 416 return osthread; 417 } 418 419 420 bool os::create_attached_thread(JavaThread* thread) { 421 #ifdef ASSERT 422 thread->verify_not_published(); 423 #endif 424 HANDLE thread_h; 425 if (!DuplicateHandle(main_process, GetCurrentThread(), GetCurrentProcess(), 426 &thread_h, THREAD_ALL_ACCESS, false, 0)) { 427 fatal("DuplicateHandle failed\n"); 428 } 429 OSThread* osthread = create_os_thread(thread, thread_h, 430 (int)current_thread_id()); 431 if (osthread == NULL) { 432 return false; 433 } 434 435 // Initial thread state is RUNNABLE 436 osthread->set_state(RUNNABLE); 437 438 thread->set_osthread(osthread); 439 return true; 440 } 441 442 bool os::create_main_thread(JavaThread* thread) { 443 #ifdef ASSERT 444 thread->verify_not_published(); 445 #endif 446 if (_starting_thread == NULL) { 447 _starting_thread = create_os_thread(thread, main_thread, main_thread_id); 448 if (_starting_thread == NULL) { 449 return false; 450 } 451 } 452 453 // The primordial thread is runnable from the start) 454 _starting_thread->set_state(RUNNABLE); 455 456 thread->set_osthread(_starting_thread); 457 return true; 458 } 459 460 // Allocate and initialize a new OSThread 461 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 462 unsigned thread_id; 463 464 // Allocate the OSThread object 465 OSThread* osthread = new OSThread(NULL, NULL); 466 if (osthread == NULL) { 467 return false; 468 } 469 470 // Initialize support for Java interrupts 471 HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL); 472 if (interrupt_event == NULL) { 473 delete osthread; 474 return NULL; 475 } 476 osthread->set_interrupt_event(interrupt_event); 477 osthread->set_interrupted(false); 478 479 thread->set_osthread(osthread); 480 481 if (stack_size == 0) { 482 switch (thr_type) { 483 case os::java_thread: 484 // Java threads use ThreadStackSize which default value can be changed with the flag -Xss 485 if (JavaThread::stack_size_at_create() > 0) 486 stack_size = JavaThread::stack_size_at_create(); 487 break; 488 case os::compiler_thread: 489 if (CompilerThreadStackSize > 0) { 490 stack_size = (size_t)(CompilerThreadStackSize * K); 491 break; 492 } // else fall through: 493 // use VMThreadStackSize if CompilerThreadStackSize is not defined 494 case os::vm_thread: 495 case os::pgc_thread: 496 case os::cgc_thread: 497 case os::watcher_thread: 498 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 499 break; 500 } 501 } 502 503 // Create the Win32 thread 504 // 505 // Contrary to what MSDN document says, "stack_size" in _beginthreadex() 506 // does not specify stack size. Instead, it specifies the size of 507 // initially committed space. The stack size is determined by 508 // PE header in the executable. If the committed "stack_size" is larger 509 // than default value in the PE header, the stack is rounded up to the 510 // nearest multiple of 1MB. For example if the launcher has default 511 // stack size of 320k, specifying any size less than 320k does not 512 // affect the actual stack size at all, it only affects the initial 513 // commitment. On the other hand, specifying 'stack_size' larger than 514 // default value may cause significant increase in memory usage, because 515 // not only the stack space will be rounded up to MB, but also the 516 // entire space is committed upfront. 517 // 518 // Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION' 519 // for CreateThread() that can treat 'stack_size' as stack size. However we 520 // are not supposed to call CreateThread() directly according to MSDN 521 // document because JVM uses C runtime library. The good news is that the 522 // flag appears to work with _beginthredex() as well. 523 524 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION 525 #define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000) 526 #endif 527 528 HANDLE thread_handle = 529 (HANDLE)_beginthreadex(NULL, 530 (unsigned)stack_size, 531 (unsigned (__stdcall *)(void*)) java_start, 532 thread, 533 CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, 534 &thread_id); 535 if (thread_handle == NULL) { 536 // perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again 537 // without the flag. 538 thread_handle = 539 (HANDLE)_beginthreadex(NULL, 540 (unsigned)stack_size, 541 (unsigned (__stdcall *)(void*)) java_start, 542 thread, 543 CREATE_SUSPENDED, 544 &thread_id); 545 } 546 if (thread_handle == NULL) { 547 // Need to clean up stuff we've allocated so far 548 CloseHandle(osthread->interrupt_event()); 549 thread->set_osthread(NULL); 550 delete osthread; 551 return NULL; 552 } 553 554 Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count); 555 556 // Store info on the Win32 thread into the OSThread 557 osthread->set_thread_handle(thread_handle); 558 osthread->set_thread_id(thread_id); 559 560 // Initial thread state is INITIALIZED, not SUSPENDED 561 osthread->set_state(INITIALIZED); 562 563 // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain 564 return true; 565 } 566 567 568 // Free Win32 resources related to the OSThread 569 void os::free_thread(OSThread* osthread) { 570 assert(osthread != NULL, "osthread not set"); 571 CloseHandle(osthread->thread_handle()); 572 CloseHandle(osthread->interrupt_event()); 573 delete osthread; 574 } 575 576 577 static int has_performance_count = 0; 578 static jlong first_filetime; 579 static jlong initial_performance_count; 580 static jlong performance_frequency; 581 582 583 jlong as_long(LARGE_INTEGER x) { 584 jlong result = 0; // initialization to avoid warning 585 set_high(&result, x.HighPart); 586 set_low(&result, x.LowPart); 587 return result; 588 } 589 590 591 jlong os::elapsed_counter() { 592 LARGE_INTEGER count; 593 if (has_performance_count) { 594 QueryPerformanceCounter(&count); 595 return as_long(count) - initial_performance_count; 596 } else { 597 FILETIME wt; 598 GetSystemTimeAsFileTime(&wt); 599 return (jlong_from(wt.dwHighDateTime, wt.dwLowDateTime) - first_filetime); 600 } 601 } 602 603 604 jlong os::elapsed_frequency() { 605 if (has_performance_count) { 606 return performance_frequency; 607 } else { 608 // the FILETIME time is the number of 100-nanosecond intervals since January 1,1601. 609 return 10000000; 610 } 611 } 612 613 614 julong os::available_memory() { 615 return win32::available_memory(); 616 } 617 618 julong os::win32::available_memory() { 619 // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect 620 // value if total memory is larger than 4GB 621 MEMORYSTATUSEX ms; 622 ms.dwLength = sizeof(ms); 623 GlobalMemoryStatusEx(&ms); 624 625 return (julong)ms.ullAvailPhys; 626 } 627 628 julong os::physical_memory() { 629 return win32::physical_memory(); 630 } 631 632 julong os::allocatable_physical_memory(julong size) { 633 #ifdef _LP64 634 return size; 635 #else 636 // Limit to 1400m because of the 2gb address space wall 637 return MIN2(size, (julong)1400*M); 638 #endif 639 } 640 641 // VC6 lacks DWORD_PTR 642 #if _MSC_VER < 1300 643 typedef UINT_PTR DWORD_PTR; 644 #endif 645 646 int os::active_processor_count() { 647 DWORD_PTR lpProcessAffinityMask = 0; 648 DWORD_PTR lpSystemAffinityMask = 0; 649 int proc_count = processor_count(); 650 if (proc_count <= sizeof(UINT_PTR) * BitsPerByte && 651 GetProcessAffinityMask(GetCurrentProcess(), &lpProcessAffinityMask, &lpSystemAffinityMask)) { 652 // Nof active processors is number of bits in process affinity mask 653 int bitcount = 0; 654 while (lpProcessAffinityMask != 0) { 655 lpProcessAffinityMask = lpProcessAffinityMask & (lpProcessAffinityMask-1); 656 bitcount++; 657 } 658 return bitcount; 659 } else { 660 return proc_count; 661 } 662 } 663 664 bool os::distribute_processes(uint length, uint* distribution) { 665 // Not yet implemented. 666 return false; 667 } 668 669 bool os::bind_to_processor(uint processor_id) { 670 // Not yet implemented. 671 return false; 672 } 673 674 static void initialize_performance_counter() { 675 LARGE_INTEGER count; 676 if (QueryPerformanceFrequency(&count)) { 677 has_performance_count = 1; 678 performance_frequency = as_long(count); 679 QueryPerformanceCounter(&count); 680 initial_performance_count = as_long(count); 681 } else { 682 has_performance_count = 0; 683 FILETIME wt; 684 GetSystemTimeAsFileTime(&wt); 685 first_filetime = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime); 686 } 687 } 688 689 690 double os::elapsedTime() { 691 return (double) elapsed_counter() / (double) elapsed_frequency(); 692 } 693 694 695 // Windows format: 696 // The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601. 697 // Java format: 698 // Java standards require the number of milliseconds since 1/1/1970 699 700 // Constant offset - calculated using offset() 701 static jlong _offset = 116444736000000000; 702 // Fake time counter for reproducible results when debugging 703 static jlong fake_time = 0; 704 705 #ifdef ASSERT 706 // Just to be safe, recalculate the offset in debug mode 707 static jlong _calculated_offset = 0; 708 static int _has_calculated_offset = 0; 709 710 jlong offset() { 711 if (_has_calculated_offset) return _calculated_offset; 712 SYSTEMTIME java_origin; 713 java_origin.wYear = 1970; 714 java_origin.wMonth = 1; 715 java_origin.wDayOfWeek = 0; // ignored 716 java_origin.wDay = 1; 717 java_origin.wHour = 0; 718 java_origin.wMinute = 0; 719 java_origin.wSecond = 0; 720 java_origin.wMilliseconds = 0; 721 FILETIME jot; 722 if (!SystemTimeToFileTime(&java_origin, &jot)) { 723 fatal1("Error = %d\nWindows error", GetLastError()); 724 } 725 _calculated_offset = jlong_from(jot.dwHighDateTime, jot.dwLowDateTime); 726 _has_calculated_offset = 1; 727 assert(_calculated_offset == _offset, "Calculated and constant time offsets must be equal"); 728 return _calculated_offset; 729 } 730 #else 731 jlong offset() { 732 return _offset; 733 } 734 #endif 735 736 jlong windows_to_java_time(FILETIME wt) { 737 jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime); 738 return (a - offset()) / 10000; 739 } 740 741 FILETIME java_to_windows_time(jlong l) { 742 jlong a = (l * 10000) + offset(); 743 FILETIME result; 744 result.dwHighDateTime = high(a); 745 result.dwLowDateTime = low(a); 746 return result; 747 } 748 749 // For now, we say that Windows does not support vtime. I have no idea 750 // whether it can actually be made to (DLD, 9/13/05). 751 752 bool os::supports_vtime() { return false; } 753 bool os::enable_vtime() { return false; } 754 bool os::vtime_enabled() { return false; } 755 double os::elapsedVTime() { 756 // better than nothing, but not much 757 return elapsedTime(); 758 } 759 760 jlong os::javaTimeMillis() { 761 if (UseFakeTimers) { 762 return fake_time++; 763 } else { 764 FILETIME wt; 765 GetSystemTimeAsFileTime(&wt); 766 return windows_to_java_time(wt); 767 } 768 } 769 770 #define NANOS_PER_SEC CONST64(1000000000) 771 #define NANOS_PER_MILLISEC 1000000 772 jlong os::javaTimeNanos() { 773 if (!has_performance_count) { 774 return javaTimeMillis() * NANOS_PER_MILLISEC; // the best we can do. 775 } else { 776 LARGE_INTEGER current_count; 777 QueryPerformanceCounter(¤t_count); 778 double current = as_long(current_count); 779 double freq = performance_frequency; 780 jlong time = (jlong)((current/freq) * NANOS_PER_SEC); 781 return time; 782 } 783 } 784 785 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 786 if (!has_performance_count) { 787 // javaTimeMillis() doesn't have much percision, 788 // but it is not going to wrap -- so all 64 bits 789 info_ptr->max_value = ALL_64_BITS; 790 791 // this is a wall clock timer, so may skip 792 info_ptr->may_skip_backward = true; 793 info_ptr->may_skip_forward = true; 794 } else { 795 jlong freq = performance_frequency; 796 if (freq < NANOS_PER_SEC) { 797 // the performance counter is 64 bits and we will 798 // be multiplying it -- so no wrap in 64 bits 799 info_ptr->max_value = ALL_64_BITS; 800 } else if (freq > NANOS_PER_SEC) { 801 // use the max value the counter can reach to 802 // determine the max value which could be returned 803 julong max_counter = (julong)ALL_64_BITS; 804 info_ptr->max_value = (jlong)(max_counter / (freq / NANOS_PER_SEC)); 805 } else { 806 // the performance counter is 64 bits and we will 807 // be using it directly -- so no wrap in 64 bits 808 info_ptr->max_value = ALL_64_BITS; 809 } 810 811 // using a counter, so no skipping 812 info_ptr->may_skip_backward = false; 813 info_ptr->may_skip_forward = false; 814 } 815 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 816 } 817 818 char* os::local_time_string(char *buf, size_t buflen) { 819 SYSTEMTIME st; 820 GetLocalTime(&st); 821 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 822 st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); 823 return buf; 824 } 825 826 bool os::getTimesSecs(double* process_real_time, 827 double* process_user_time, 828 double* process_system_time) { 829 HANDLE h_process = GetCurrentProcess(); 830 FILETIME create_time, exit_time, kernel_time, user_time; 831 BOOL result = GetProcessTimes(h_process, 832 &create_time, 833 &exit_time, 834 &kernel_time, 835 &user_time); 836 if (result != 0) { 837 FILETIME wt; 838 GetSystemTimeAsFileTime(&wt); 839 jlong rtc_millis = windows_to_java_time(wt); 840 jlong user_millis = windows_to_java_time(user_time); 841 jlong system_millis = windows_to_java_time(kernel_time); 842 *process_real_time = ((double) rtc_millis) / ((double) MILLIUNITS); 843 *process_user_time = ((double) user_millis) / ((double) MILLIUNITS); 844 *process_system_time = ((double) system_millis) / ((double) MILLIUNITS); 845 return true; 846 } else { 847 return false; 848 } 849 } 850 851 void os::shutdown() { 852 853 // allow PerfMemory to attempt cleanup of any persistent resources 854 perfMemory_exit(); 855 856 // flush buffered output, finish log files 857 ostream_abort(); 858 859 // Check for abort hook 860 abort_hook_t abort_hook = Arguments::abort_hook(); 861 if (abort_hook != NULL) { 862 abort_hook(); 863 } 864 } 865 866 void os::abort(bool dump_core) 867 { 868 os::shutdown(); 869 // no core dump on Windows 870 ::exit(1); 871 } 872 873 // Die immediately, no exit hook, no abort hook, no cleanup. 874 void os::die() { 875 _exit(-1); 876 } 877 878 // Directory routines copied from src/win32/native/java/io/dirent_md.c 879 // * dirent_md.c 1.15 00/02/02 880 // 881 // The declarations for DIR and struct dirent are in jvm_win32.h. 882 883 /* Caller must have already run dirname through JVM_NativePath, which removes 884 duplicate slashes and converts all instances of '/' into '\\'. */ 885 886 DIR * 887 os::opendir(const char *dirname) 888 { 889 assert(dirname != NULL, "just checking"); // hotspot change 890 DIR *dirp = (DIR *)malloc(sizeof(DIR)); 891 DWORD fattr; // hotspot change 892 char alt_dirname[4] = { 0, 0, 0, 0 }; 893 894 if (dirp == 0) { 895 errno = ENOMEM; 896 return 0; 897 } 898 899 /* 900 * Win32 accepts "\" in its POSIX stat(), but refuses to treat it 901 * as a directory in FindFirstFile(). We detect this case here and 902 * prepend the current drive name. 903 */ 904 if (dirname[1] == '\0' && dirname[0] == '\\') { 905 alt_dirname[0] = _getdrive() + 'A' - 1; 906 alt_dirname[1] = ':'; 907 alt_dirname[2] = '\\'; 908 alt_dirname[3] = '\0'; 909 dirname = alt_dirname; 910 } 911 912 dirp->path = (char *)malloc(strlen(dirname) + 5); 913 if (dirp->path == 0) { 914 free(dirp); 915 errno = ENOMEM; 916 return 0; 917 } 918 strcpy(dirp->path, dirname); 919 920 fattr = GetFileAttributes(dirp->path); 921 if (fattr == 0xffffffff) { 922 free(dirp->path); 923 free(dirp); 924 errno = ENOENT; 925 return 0; 926 } else if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) { 927 free(dirp->path); 928 free(dirp); 929 errno = ENOTDIR; 930 return 0; 931 } 932 933 /* Append "*.*", or possibly "\\*.*", to path */ 934 if (dirp->path[1] == ':' 935 && (dirp->path[2] == '\0' 936 || (dirp->path[2] == '\\' && dirp->path[3] == '\0'))) { 937 /* No '\\' needed for cases like "Z:" or "Z:\" */ 938 strcat(dirp->path, "*.*"); 939 } else { 940 strcat(dirp->path, "\\*.*"); 941 } 942 943 dirp->handle = FindFirstFile(dirp->path, &dirp->find_data); 944 if (dirp->handle == INVALID_HANDLE_VALUE) { 945 if (GetLastError() != ERROR_FILE_NOT_FOUND) { 946 free(dirp->path); 947 free(dirp); 948 errno = EACCES; 949 return 0; 950 } 951 } 952 return dirp; 953 } 954 955 /* parameter dbuf unused on Windows */ 956 957 struct dirent * 958 os::readdir(DIR *dirp, dirent *dbuf) 959 { 960 assert(dirp != NULL, "just checking"); // hotspot change 961 if (dirp->handle == INVALID_HANDLE_VALUE) { 962 return 0; 963 } 964 965 strcpy(dirp->dirent.d_name, dirp->find_data.cFileName); 966 967 if (!FindNextFile(dirp->handle, &dirp->find_data)) { 968 if (GetLastError() == ERROR_INVALID_HANDLE) { 969 errno = EBADF; 970 return 0; 971 } 972 FindClose(dirp->handle); 973 dirp->handle = INVALID_HANDLE_VALUE; 974 } 975 976 return &dirp->dirent; 977 } 978 979 int 980 os::closedir(DIR *dirp) 981 { 982 assert(dirp != NULL, "just checking"); // hotspot change 983 if (dirp->handle != INVALID_HANDLE_VALUE) { 984 if (!FindClose(dirp->handle)) { 985 errno = EBADF; 986 return -1; 987 } 988 dirp->handle = INVALID_HANDLE_VALUE; 989 } 990 free(dirp->path); 991 free(dirp); 992 return 0; 993 } 994 995 const char* os::dll_file_extension() { return ".dll"; } 996 997 const char * os::get_temp_directory() 998 { 999 static char path_buf[MAX_PATH]; 1000 if (GetTempPath(MAX_PATH, path_buf)>0) 1001 return path_buf; 1002 else{ 1003 path_buf[0]='\0'; 1004 return path_buf; 1005 } 1006 } 1007 1008 static bool file_exists(const char* filename) { 1009 if (filename == NULL || strlen(filename) == 0) { 1010 return false; 1011 } 1012 return GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES; 1013 } 1014 1015 void os::dll_build_name(char *buffer, size_t buflen, 1016 const char* pname, const char* fname) { 1017 // Copied from libhpi 1018 const size_t pnamelen = pname ? strlen(pname) : 0; 1019 const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0; 1020 1021 // Quietly truncates on buffer overflow. Should be an error. 1022 if (pnamelen + strlen(fname) + 10 > buflen) { 1023 *buffer = '\0'; 1024 return; 1025 } 1026 1027 if (pnamelen == 0) { 1028 jio_snprintf(buffer, buflen, "%s.dll", fname); 1029 } else if (c == ':' || c == '\\') { 1030 jio_snprintf(buffer, buflen, "%s%s.dll", pname, fname); 1031 } else if (strchr(pname, *os::path_separator()) != NULL) { 1032 int n; 1033 char** pelements = split_path(pname, &n); 1034 for (int i = 0 ; i < n ; i++) { 1035 char* path = pelements[i]; 1036 // Really shouldn't be NULL, but check can't hurt 1037 size_t plen = (path == NULL) ? 0 : strlen(path); 1038 if (plen == 0) { 1039 continue; // skip the empty path values 1040 } 1041 const char lastchar = path[plen - 1]; 1042 if (lastchar == ':' || lastchar == '\\') { 1043 jio_snprintf(buffer, buflen, "%s%s.dll", path, fname); 1044 } else { 1045 jio_snprintf(buffer, buflen, "%s\\%s.dll", path, fname); 1046 } 1047 if (file_exists(buffer)) { 1048 break; 1049 } 1050 } 1051 // release the storage 1052 for (int i = 0 ; i < n ; i++) { 1053 if (pelements[i] != NULL) { 1054 FREE_C_HEAP_ARRAY(char, pelements[i]); 1055 } 1056 } 1057 if (pelements != NULL) { 1058 FREE_C_HEAP_ARRAY(char*, pelements); 1059 } 1060 } else { 1061 jio_snprintf(buffer, buflen, "%s\\%s.dll", pname, fname); 1062 } 1063 } 1064 1065 // Needs to be in os specific directory because windows requires another 1066 // header file <direct.h> 1067 const char* os::get_current_directory(char *buf, int buflen) { 1068 return _getcwd(buf, buflen); 1069 } 1070 1071 //----------------------------------------------------------- 1072 // Helper functions for fatal error handler 1073 1074 // The following library functions are resolved dynamically at runtime: 1075 1076 // PSAPI functions, for Windows NT, 2000, XP 1077 1078 // psapi.h doesn't come with Visual Studio 6; it can be downloaded as Platform 1079 // SDK from Microsoft. Here are the definitions copied from psapi.h 1080 typedef struct _MODULEINFO { 1081 LPVOID lpBaseOfDll; 1082 DWORD SizeOfImage; 1083 LPVOID EntryPoint; 1084 } MODULEINFO, *LPMODULEINFO; 1085 1086 static BOOL (WINAPI *_EnumProcessModules) ( HANDLE, HMODULE *, DWORD, LPDWORD ); 1087 static DWORD (WINAPI *_GetModuleFileNameEx) ( HANDLE, HMODULE, LPTSTR, DWORD ); 1088 static BOOL (WINAPI *_GetModuleInformation)( HANDLE, HMODULE, LPMODULEINFO, DWORD ); 1089 1090 // ToolHelp Functions, for Windows 95, 98 and ME 1091 1092 static HANDLE(WINAPI *_CreateToolhelp32Snapshot)(DWORD,DWORD) ; 1093 static BOOL (WINAPI *_Module32First) (HANDLE,LPMODULEENTRY32) ; 1094 static BOOL (WINAPI *_Module32Next) (HANDLE,LPMODULEENTRY32) ; 1095 1096 bool _has_psapi; 1097 bool _psapi_init = false; 1098 bool _has_toolhelp; 1099 1100 static bool _init_psapi() { 1101 HINSTANCE psapi = LoadLibrary( "PSAPI.DLL" ) ; 1102 if( psapi == NULL ) return false ; 1103 1104 _EnumProcessModules = CAST_TO_FN_PTR( 1105 BOOL(WINAPI *)(HANDLE, HMODULE *, DWORD, LPDWORD), 1106 GetProcAddress(psapi, "EnumProcessModules")) ; 1107 _GetModuleFileNameEx = CAST_TO_FN_PTR( 1108 DWORD (WINAPI *)(HANDLE, HMODULE, LPTSTR, DWORD), 1109 GetProcAddress(psapi, "GetModuleFileNameExA")); 1110 _GetModuleInformation = CAST_TO_FN_PTR( 1111 BOOL (WINAPI *)(HANDLE, HMODULE, LPMODULEINFO, DWORD), 1112 GetProcAddress(psapi, "GetModuleInformation")); 1113 1114 _has_psapi = (_EnumProcessModules && _GetModuleFileNameEx && _GetModuleInformation); 1115 _psapi_init = true; 1116 return _has_psapi; 1117 } 1118 1119 static bool _init_toolhelp() { 1120 HINSTANCE kernel32 = LoadLibrary("Kernel32.DLL") ; 1121 if (kernel32 == NULL) return false ; 1122 1123 _CreateToolhelp32Snapshot = CAST_TO_FN_PTR( 1124 HANDLE(WINAPI *)(DWORD,DWORD), 1125 GetProcAddress(kernel32, "CreateToolhelp32Snapshot")); 1126 _Module32First = CAST_TO_FN_PTR( 1127 BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32), 1128 GetProcAddress(kernel32, "Module32First" )); 1129 _Module32Next = CAST_TO_FN_PTR( 1130 BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32), 1131 GetProcAddress(kernel32, "Module32Next" )); 1132 1133 _has_toolhelp = (_CreateToolhelp32Snapshot && _Module32First && _Module32Next); 1134 return _has_toolhelp; 1135 } 1136 1137 #ifdef _WIN64 1138 // Helper routine which returns true if address in 1139 // within the NTDLL address space. 1140 // 1141 static bool _addr_in_ntdll( address addr ) 1142 { 1143 HMODULE hmod; 1144 MODULEINFO minfo; 1145 1146 hmod = GetModuleHandle("NTDLL.DLL"); 1147 if ( hmod == NULL ) return false; 1148 if ( !_GetModuleInformation( GetCurrentProcess(), hmod, 1149 &minfo, sizeof(MODULEINFO)) ) 1150 return false; 1151 1152 if ( (addr >= minfo.lpBaseOfDll) && 1153 (addr < (address)((uintptr_t)minfo.lpBaseOfDll + (uintptr_t)minfo.SizeOfImage))) 1154 return true; 1155 else 1156 return false; 1157 } 1158 #endif 1159 1160 1161 // Enumerate all modules for a given process ID 1162 // 1163 // Notice that Windows 95/98/Me and Windows NT/2000/XP have 1164 // different API for doing this. We use PSAPI.DLL on NT based 1165 // Windows and ToolHelp on 95/98/Me. 1166 1167 // Callback function that is called by enumerate_modules() on 1168 // every DLL module. 1169 // Input parameters: 1170 // int pid, 1171 // char* module_file_name, 1172 // address module_base_addr, 1173 // unsigned module_size, 1174 // void* param 1175 typedef int (*EnumModulesCallbackFunc)(int, char *, address, unsigned, void *); 1176 1177 // enumerate_modules for Windows NT, using PSAPI 1178 static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void * param) 1179 { 1180 HANDLE hProcess ; 1181 1182 # define MAX_NUM_MODULES 128 1183 HMODULE modules[MAX_NUM_MODULES]; 1184 static char filename[ MAX_PATH ]; 1185 int result = 0; 1186 1187 if (!_has_psapi && (_psapi_init || !_init_psapi())) return 0; 1188 1189 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 1190 FALSE, pid ) ; 1191 if (hProcess == NULL) return 0; 1192 1193 DWORD size_needed; 1194 if (!_EnumProcessModules(hProcess, modules, 1195 sizeof(modules), &size_needed)) { 1196 CloseHandle( hProcess ); 1197 return 0; 1198 } 1199 1200 // number of modules that are currently loaded 1201 int num_modules = size_needed / sizeof(HMODULE); 1202 1203 for (int i = 0; i < MIN2(num_modules, MAX_NUM_MODULES); i++) { 1204 // Get Full pathname: 1205 if(!_GetModuleFileNameEx(hProcess, modules[i], 1206 filename, sizeof(filename))) { 1207 filename[0] = '\0'; 1208 } 1209 1210 MODULEINFO modinfo; 1211 if (!_GetModuleInformation(hProcess, modules[i], 1212 &modinfo, sizeof(modinfo))) { 1213 modinfo.lpBaseOfDll = NULL; 1214 modinfo.SizeOfImage = 0; 1215 } 1216 1217 // Invoke callback function 1218 result = func(pid, filename, (address)modinfo.lpBaseOfDll, 1219 modinfo.SizeOfImage, param); 1220 if (result) break; 1221 } 1222 1223 CloseHandle( hProcess ) ; 1224 return result; 1225 } 1226 1227 1228 // enumerate_modules for Windows 95/98/ME, using TOOLHELP 1229 static int _enumerate_modules_windows( int pid, EnumModulesCallbackFunc func, void *param) 1230 { 1231 HANDLE hSnapShot ; 1232 static MODULEENTRY32 modentry ; 1233 int result = 0; 1234 1235 if (!_has_toolhelp) return 0; 1236 1237 // Get a handle to a Toolhelp snapshot of the system 1238 hSnapShot = _CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid ) ; 1239 if( hSnapShot == INVALID_HANDLE_VALUE ) { 1240 return FALSE ; 1241 } 1242 1243 // iterate through all modules 1244 modentry.dwSize = sizeof(MODULEENTRY32) ; 1245 bool not_done = _Module32First( hSnapShot, &modentry ) != 0; 1246 1247 while( not_done ) { 1248 // invoke the callback 1249 result=func(pid, modentry.szExePath, (address)modentry.modBaseAddr, 1250 modentry.modBaseSize, param); 1251 if (result) break; 1252 1253 modentry.dwSize = sizeof(MODULEENTRY32) ; 1254 not_done = _Module32Next( hSnapShot, &modentry ) != 0; 1255 } 1256 1257 CloseHandle(hSnapShot); 1258 return result; 1259 } 1260 1261 int enumerate_modules( int pid, EnumModulesCallbackFunc func, void * param ) 1262 { 1263 // Get current process ID if caller doesn't provide it. 1264 if (!pid) pid = os::current_process_id(); 1265 1266 if (os::win32::is_nt()) return _enumerate_modules_winnt (pid, func, param); 1267 else return _enumerate_modules_windows(pid, func, param); 1268 } 1269 1270 struct _modinfo { 1271 address addr; 1272 char* full_path; // point to a char buffer 1273 int buflen; // size of the buffer 1274 address base_addr; 1275 }; 1276 1277 static int _locate_module_by_addr(int pid, char * mod_fname, address base_addr, 1278 unsigned size, void * param) { 1279 struct _modinfo *pmod = (struct _modinfo *)param; 1280 if (!pmod) return -1; 1281 1282 if (base_addr <= pmod->addr && 1283 base_addr+size > pmod->addr) { 1284 // if a buffer is provided, copy path name to the buffer 1285 if (pmod->full_path) { 1286 jio_snprintf(pmod->full_path, pmod->buflen, "%s", mod_fname); 1287 } 1288 pmod->base_addr = base_addr; 1289 return 1; 1290 } 1291 return 0; 1292 } 1293 1294 bool os::dll_address_to_library_name(address addr, char* buf, 1295 int buflen, int* offset) { 1296 // NOTE: the reason we don't use SymGetModuleInfo() is it doesn't always 1297 // return the full path to the DLL file, sometimes it returns path 1298 // to the corresponding PDB file (debug info); sometimes it only 1299 // returns partial path, which makes life painful. 1300 1301 struct _modinfo mi; 1302 mi.addr = addr; 1303 mi.full_path = buf; 1304 mi.buflen = buflen; 1305 int pid = os::current_process_id(); 1306 if (enumerate_modules(pid, _locate_module_by_addr, (void *)&mi)) { 1307 // buf already contains path name 1308 if (offset) *offset = addr - mi.base_addr; 1309 return true; 1310 } else { 1311 if (buf) buf[0] = '\0'; 1312 if (offset) *offset = -1; 1313 return false; 1314 } 1315 } 1316 1317 bool os::dll_address_to_function_name(address addr, char *buf, 1318 int buflen, int *offset) { 1319 // Unimplemented on Windows - in order to use SymGetSymFromAddr(), 1320 // we need to initialize imagehlp/dbghelp, then load symbol table 1321 // for every module. That's too much work to do after a fatal error. 1322 // For an example on how to implement this function, see 1.4.2. 1323 if (offset) *offset = -1; 1324 if (buf) buf[0] = '\0'; 1325 return false; 1326 } 1327 1328 void* os::dll_lookup(void* handle, const char* name) { 1329 return GetProcAddress((HMODULE)handle, name); 1330 } 1331 1332 // save the start and end address of jvm.dll into param[0] and param[1] 1333 static int _locate_jvm_dll(int pid, char* mod_fname, address base_addr, 1334 unsigned size, void * param) { 1335 if (!param) return -1; 1336 1337 if (base_addr <= (address)_locate_jvm_dll && 1338 base_addr+size > (address)_locate_jvm_dll) { 1339 ((address*)param)[0] = base_addr; 1340 ((address*)param)[1] = base_addr + size; 1341 return 1; 1342 } 1343 return 0; 1344 } 1345 1346 address vm_lib_location[2]; // start and end address of jvm.dll 1347 1348 // check if addr is inside jvm.dll 1349 bool os::address_is_in_vm(address addr) { 1350 if (!vm_lib_location[0] || !vm_lib_location[1]) { 1351 int pid = os::current_process_id(); 1352 if (!enumerate_modules(pid, _locate_jvm_dll, (void *)vm_lib_location)) { 1353 assert(false, "Can't find jvm module."); 1354 return false; 1355 } 1356 } 1357 1358 return (vm_lib_location[0] <= addr) && (addr < vm_lib_location[1]); 1359 } 1360 1361 // print module info; param is outputStream* 1362 static int _print_module(int pid, char* fname, address base, 1363 unsigned size, void* param) { 1364 if (!param) return -1; 1365 1366 outputStream* st = (outputStream*)param; 1367 1368 address end_addr = base + size; 1369 st->print(PTR_FORMAT " - " PTR_FORMAT " \t%s\n", base, end_addr, fname); 1370 return 0; 1371 } 1372 1373 // Loads .dll/.so and 1374 // in case of error it checks if .dll/.so was built for the 1375 // same architecture as Hotspot is running on 1376 void * os::dll_load(const char *name, char *ebuf, int ebuflen) 1377 { 1378 void * result = LoadLibrary(name); 1379 if (result != NULL) 1380 { 1381 return result; 1382 } 1383 1384 long errcode = GetLastError(); 1385 if (errcode == ERROR_MOD_NOT_FOUND) { 1386 strncpy(ebuf, "Can't find dependent libraries", ebuflen-1); 1387 ebuf[ebuflen-1]='\0'; 1388 return NULL; 1389 } 1390 1391 // Parsing dll below 1392 // If we can read dll-info and find that dll was built 1393 // for an architecture other than Hotspot is running in 1394 // - then print to buffer "DLL was built for a different architecture" 1395 // else call getLastErrorString to obtain system error message 1396 1397 // Read system error message into ebuf 1398 // It may or may not be overwritten below (in the for loop and just above) 1399 getLastErrorString(ebuf, (size_t) ebuflen); 1400 ebuf[ebuflen-1]='\0'; 1401 int file_descriptor=::open(name, O_RDONLY | O_BINARY, 0); 1402 if (file_descriptor<0) 1403 { 1404 return NULL; 1405 } 1406 1407 uint32_t signature_offset; 1408 uint16_t lib_arch=0; 1409 bool failed_to_get_lib_arch= 1410 ( 1411 //Go to position 3c in the dll 1412 (os::seek_to_file_offset(file_descriptor,IMAGE_FILE_PTR_TO_SIGNATURE)<0) 1413 || 1414 // Read loacation of signature 1415 (sizeof(signature_offset)!= 1416 (os::read(file_descriptor, (void*)&signature_offset,sizeof(signature_offset)))) 1417 || 1418 //Go to COFF File Header in dll 1419 //that is located after"signature" (4 bytes long) 1420 (os::seek_to_file_offset(file_descriptor, 1421 signature_offset+IMAGE_FILE_SIGNATURE_LENGTH)<0) 1422 || 1423 //Read field that contains code of architecture 1424 // that dll was build for 1425 (sizeof(lib_arch)!= 1426 (os::read(file_descriptor, (void*)&lib_arch,sizeof(lib_arch)))) 1427 ); 1428 1429 ::close(file_descriptor); 1430 if (failed_to_get_lib_arch) 1431 { 1432 // file i/o error - report getLastErrorString(...) msg 1433 return NULL; 1434 } 1435 1436 typedef struct 1437 { 1438 uint16_t arch_code; 1439 char* arch_name; 1440 } arch_t; 1441 1442 static const arch_t arch_array[]={ 1443 {IMAGE_FILE_MACHINE_I386, (char*)"IA 32"}, 1444 {IMAGE_FILE_MACHINE_AMD64, (char*)"AMD 64"}, 1445 {IMAGE_FILE_MACHINE_IA64, (char*)"IA 64"} 1446 }; 1447 #if (defined _M_IA64) 1448 static const uint16_t running_arch=IMAGE_FILE_MACHINE_IA64; 1449 #elif (defined _M_AMD64) 1450 static const uint16_t running_arch=IMAGE_FILE_MACHINE_AMD64; 1451 #elif (defined _M_IX86) 1452 static const uint16_t running_arch=IMAGE_FILE_MACHINE_I386; 1453 #else 1454 #error Method os::dll_load requires that one of following \ 1455 is defined :_M_IA64,_M_AMD64 or _M_IX86 1456 #endif 1457 1458 1459 // Obtain a string for printf operation 1460 // lib_arch_str shall contain string what platform this .dll was built for 1461 // running_arch_str shall string contain what platform Hotspot was built for 1462 char *running_arch_str=NULL,*lib_arch_str=NULL; 1463 for (unsigned int i=0;i<ARRAY_SIZE(arch_array);i++) 1464 { 1465 if (lib_arch==arch_array[i].arch_code) 1466 lib_arch_str=arch_array[i].arch_name; 1467 if (running_arch==arch_array[i].arch_code) 1468 running_arch_str=arch_array[i].arch_name; 1469 } 1470 1471 assert(running_arch_str, 1472 "Didn't find runing architecture code in arch_array"); 1473 1474 // If the architure is right 1475 // but some other error took place - report getLastErrorString(...) msg 1476 if (lib_arch == running_arch) 1477 { 1478 return NULL; 1479 } 1480 1481 if (lib_arch_str!=NULL) 1482 { 1483 ::_snprintf(ebuf, ebuflen-1, 1484 "Can't load %s-bit .dll on a %s-bit platform", 1485 lib_arch_str,running_arch_str); 1486 } 1487 else 1488 { 1489 // don't know what architecture this dll was build for 1490 ::_snprintf(ebuf, ebuflen-1, 1491 "Can't load this .dll (machine code=0x%x) on a %s-bit platform", 1492 lib_arch,running_arch_str); 1493 } 1494 1495 return NULL; 1496 } 1497 1498 1499 void os::print_dll_info(outputStream *st) { 1500 int pid = os::current_process_id(); 1501 st->print_cr("Dynamic libraries:"); 1502 enumerate_modules(pid, _print_module, (void *)st); 1503 } 1504 1505 // function pointer to Windows API "GetNativeSystemInfo". 1506 typedef void (WINAPI *GetNativeSystemInfo_func_type)(LPSYSTEM_INFO); 1507 static GetNativeSystemInfo_func_type _GetNativeSystemInfo; 1508 1509 void os::print_os_info(outputStream* st) { 1510 st->print("OS:"); 1511 1512 OSVERSIONINFOEX osvi; 1513 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); 1514 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); 1515 1516 if (!GetVersionEx((OSVERSIONINFO *)&osvi)) { 1517 st->print_cr("N/A"); 1518 return; 1519 } 1520 1521 int os_vers = osvi.dwMajorVersion * 1000 + osvi.dwMinorVersion; 1522 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) { 1523 switch (os_vers) { 1524 case 3051: st->print(" Windows NT 3.51"); break; 1525 case 4000: st->print(" Windows NT 4.0"); break; 1526 case 5000: st->print(" Windows 2000"); break; 1527 case 5001: st->print(" Windows XP"); break; 1528 case 5002: 1529 case 6000: 1530 case 6001: { 1531 // Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could 1532 // find out whether we are running on 64 bit processor or not. 1533 SYSTEM_INFO si; 1534 ZeroMemory(&si, sizeof(SYSTEM_INFO)); 1535 // Check to see if _GetNativeSystemInfo has been initialized. 1536 if (_GetNativeSystemInfo == NULL) { 1537 HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32.dll")); 1538 _GetNativeSystemInfo = 1539 CAST_TO_FN_PTR(GetNativeSystemInfo_func_type, 1540 GetProcAddress(hKernel32, 1541 "GetNativeSystemInfo")); 1542 if (_GetNativeSystemInfo == NULL) 1543 GetSystemInfo(&si); 1544 } else { 1545 _GetNativeSystemInfo(&si); 1546 } 1547 if (os_vers == 5002) { 1548 if (osvi.wProductType == VER_NT_WORKSTATION && 1549 si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1550 st->print(" Windows XP x64 Edition"); 1551 else 1552 st->print(" Windows Server 2003 family"); 1553 } else if (os_vers == 6000) { 1554 if (osvi.wProductType == VER_NT_WORKSTATION) 1555 st->print(" Windows Vista"); 1556 else 1557 st->print(" Windows Server 2008"); 1558 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1559 st->print(" , 64 bit"); 1560 } else if (os_vers == 6001) { 1561 if (osvi.wProductType == VER_NT_WORKSTATION) { 1562 st->print(" Windows 7"); 1563 } else { 1564 // Unrecognized windows, print out its major and minor versions 1565 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1566 } 1567 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1568 st->print(" , 64 bit"); 1569 } else { // future os 1570 // Unrecognized windows, print out its major and minor versions 1571 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1572 if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) 1573 st->print(" , 64 bit"); 1574 } 1575 break; 1576 } 1577 default: // future windows, print out its major and minor versions 1578 st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1579 } 1580 } else { 1581 switch (os_vers) { 1582 case 4000: st->print(" Windows 95"); break; 1583 case 4010: st->print(" Windows 98"); break; 1584 case 4090: st->print(" Windows Me"); break; 1585 default: // future windows, print out its major and minor versions 1586 st->print(" Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion); 1587 } 1588 } 1589 st->print(" Build %d", osvi.dwBuildNumber); 1590 st->print(" %s", osvi.szCSDVersion); // service pack 1591 st->cr(); 1592 } 1593 1594 void os::print_memory_info(outputStream* st) { 1595 st->print("Memory:"); 1596 st->print(" %dk page", os::vm_page_size()>>10); 1597 1598 // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect 1599 // value if total memory is larger than 4GB 1600 MEMORYSTATUSEX ms; 1601 ms.dwLength = sizeof(ms); 1602 GlobalMemoryStatusEx(&ms); 1603 1604 st->print(", physical %uk", os::physical_memory() >> 10); 1605 st->print("(%uk free)", os::available_memory() >> 10); 1606 1607 st->print(", swap %uk", ms.ullTotalPageFile >> 10); 1608 st->print("(%uk free)", ms.ullAvailPageFile >> 10); 1609 st->cr(); 1610 } 1611 1612 void os::print_siginfo(outputStream *st, void *siginfo) { 1613 EXCEPTION_RECORD* er = (EXCEPTION_RECORD*)siginfo; 1614 st->print("siginfo:"); 1615 st->print(" ExceptionCode=0x%x", er->ExceptionCode); 1616 1617 if (er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && 1618 er->NumberParameters >= 2) { 1619 switch (er->ExceptionInformation[0]) { 1620 case 0: st->print(", reading address"); break; 1621 case 1: st->print(", writing address"); break; 1622 default: st->print(", ExceptionInformation=" INTPTR_FORMAT, 1623 er->ExceptionInformation[0]); 1624 } 1625 st->print(" " INTPTR_FORMAT, er->ExceptionInformation[1]); 1626 } else if (er->ExceptionCode == EXCEPTION_IN_PAGE_ERROR && 1627 er->NumberParameters >= 2 && UseSharedSpaces) { 1628 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1629 if (mapinfo->is_in_shared_space((void*)er->ExceptionInformation[1])) { 1630 st->print("\n\nError accessing class data sharing archive." \ 1631 " Mapped file inaccessible during execution, " \ 1632 " possible disk/network problem."); 1633 } 1634 } else { 1635 int num = er->NumberParameters; 1636 if (num > 0) { 1637 st->print(", ExceptionInformation="); 1638 for (int i = 0; i < num; i++) { 1639 st->print(INTPTR_FORMAT " ", er->ExceptionInformation[i]); 1640 } 1641 } 1642 } 1643 st->cr(); 1644 } 1645 1646 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 1647 // do nothing 1648 } 1649 1650 static char saved_jvm_path[MAX_PATH] = {0}; 1651 1652 // Find the full path to the current module, jvm.dll or jvm_g.dll 1653 void os::jvm_path(char *buf, jint buflen) { 1654 // Error checking. 1655 if (buflen < MAX_PATH) { 1656 assert(false, "must use a large-enough buffer"); 1657 buf[0] = '\0'; 1658 return; 1659 } 1660 // Lazy resolve the path to current module. 1661 if (saved_jvm_path[0] != 0) { 1662 strcpy(buf, saved_jvm_path); 1663 return; 1664 } 1665 1666 GetModuleFileName(vm_lib_handle, buf, buflen); 1667 strcpy(saved_jvm_path, buf); 1668 } 1669 1670 1671 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 1672 #ifndef _WIN64 1673 st->print("_"); 1674 #endif 1675 } 1676 1677 1678 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 1679 #ifndef _WIN64 1680 st->print("@%d", args_size * sizeof(int)); 1681 #endif 1682 } 1683 1684 // sun.misc.Signal 1685 // NOTE that this is a workaround for an apparent kernel bug where if 1686 // a signal handler for SIGBREAK is installed then that signal handler 1687 // takes priority over the console control handler for CTRL_CLOSE_EVENT. 1688 // See bug 4416763. 1689 static void (*sigbreakHandler)(int) = NULL; 1690 1691 static void UserHandler(int sig, void *siginfo, void *context) { 1692 os::signal_notify(sig); 1693 // We need to reinstate the signal handler each time... 1694 os::signal(sig, (void*)UserHandler); 1695 } 1696 1697 void* os::user_handler() { 1698 return (void*) UserHandler; 1699 } 1700 1701 void* os::signal(int signal_number, void* handler) { 1702 if ((signal_number == SIGBREAK) && (!ReduceSignalUsage)) { 1703 void (*oldHandler)(int) = sigbreakHandler; 1704 sigbreakHandler = (void (*)(int)) handler; 1705 return (void*) oldHandler; 1706 } else { 1707 return (void*)::signal(signal_number, (void (*)(int))handler); 1708 } 1709 } 1710 1711 void os::signal_raise(int signal_number) { 1712 raise(signal_number); 1713 } 1714 1715 // The Win32 C runtime library maps all console control events other than ^C 1716 // into SIGBREAK, which makes it impossible to distinguish ^BREAK from close, 1717 // logoff, and shutdown events. We therefore install our own console handler 1718 // that raises SIGTERM for the latter cases. 1719 // 1720 static BOOL WINAPI consoleHandler(DWORD event) { 1721 switch(event) { 1722 case CTRL_C_EVENT: 1723 if (is_error_reported()) { 1724 // Ctrl-C is pressed during error reporting, likely because the error 1725 // handler fails to abort. Let VM die immediately. 1726 os::die(); 1727 } 1728 1729 os::signal_raise(SIGINT); 1730 return TRUE; 1731 break; 1732 case CTRL_BREAK_EVENT: 1733 if (sigbreakHandler != NULL) { 1734 (*sigbreakHandler)(SIGBREAK); 1735 } 1736 return TRUE; 1737 break; 1738 case CTRL_CLOSE_EVENT: 1739 case CTRL_LOGOFF_EVENT: 1740 case CTRL_SHUTDOWN_EVENT: 1741 os::signal_raise(SIGTERM); 1742 return TRUE; 1743 break; 1744 default: 1745 break; 1746 } 1747 return FALSE; 1748 } 1749 1750 /* 1751 * The following code is moved from os.cpp for making this 1752 * code platform specific, which it is by its very nature. 1753 */ 1754 1755 // Return maximum OS signal used + 1 for internal use only 1756 // Used as exit signal for signal_thread 1757 int os::sigexitnum_pd(){ 1758 return NSIG; 1759 } 1760 1761 // a counter for each possible signal value, including signal_thread exit signal 1762 static volatile jint pending_signals[NSIG+1] = { 0 }; 1763 static HANDLE sig_sem; 1764 1765 void os::signal_init_pd() { 1766 // Initialize signal structures 1767 memset((void*)pending_signals, 0, sizeof(pending_signals)); 1768 1769 sig_sem = ::CreateSemaphore(NULL, 0, NSIG+1, NULL); 1770 1771 // Programs embedding the VM do not want it to attempt to receive 1772 // events like CTRL_LOGOFF_EVENT, which are used to implement the 1773 // shutdown hooks mechanism introduced in 1.3. For example, when 1774 // the VM is run as part of a Windows NT service (i.e., a servlet 1775 // engine in a web server), the correct behavior is for any console 1776 // control handler to return FALSE, not TRUE, because the OS's 1777 // "final" handler for such events allows the process to continue if 1778 // it is a service (while terminating it if it is not a service). 1779 // To make this behavior uniform and the mechanism simpler, we 1780 // completely disable the VM's usage of these console events if -Xrs 1781 // (=ReduceSignalUsage) is specified. This means, for example, that 1782 // the CTRL-BREAK thread dump mechanism is also disabled in this 1783 // case. See bugs 4323062, 4345157, and related bugs. 1784 1785 if (!ReduceSignalUsage) { 1786 // Add a CTRL-C handler 1787 SetConsoleCtrlHandler(consoleHandler, TRUE); 1788 } 1789 } 1790 1791 void os::signal_notify(int signal_number) { 1792 BOOL ret; 1793 1794 Atomic::inc(&pending_signals[signal_number]); 1795 ret = ::ReleaseSemaphore(sig_sem, 1, NULL); 1796 assert(ret != 0, "ReleaseSemaphore() failed"); 1797 } 1798 1799 static int check_pending_signals(bool wait_for_signal) { 1800 DWORD ret; 1801 while (true) { 1802 for (int i = 0; i < NSIG + 1; i++) { 1803 jint n = pending_signals[i]; 1804 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 1805 return i; 1806 } 1807 } 1808 if (!wait_for_signal) { 1809 return -1; 1810 } 1811 1812 JavaThread *thread = JavaThread::current(); 1813 1814 ThreadBlockInVM tbivm(thread); 1815 1816 bool threadIsSuspended; 1817 do { 1818 thread->set_suspend_equivalent(); 1819 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 1820 ret = ::WaitForSingleObject(sig_sem, INFINITE); 1821 assert(ret == WAIT_OBJECT_0, "WaitForSingleObject() failed"); 1822 1823 // were we externally suspended while we were waiting? 1824 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 1825 if (threadIsSuspended) { 1826 // 1827 // The semaphore has been incremented, but while we were waiting 1828 // another thread suspended us. We don't want to continue running 1829 // while suspended because that would surprise the thread that 1830 // suspended us. 1831 // 1832 ret = ::ReleaseSemaphore(sig_sem, 1, NULL); 1833 assert(ret != 0, "ReleaseSemaphore() failed"); 1834 1835 thread->java_suspend_self(); 1836 } 1837 } while (threadIsSuspended); 1838 } 1839 } 1840 1841 int os::signal_lookup() { 1842 return check_pending_signals(false); 1843 } 1844 1845 int os::signal_wait() { 1846 return check_pending_signals(true); 1847 } 1848 1849 // Implicit OS exception handling 1850 1851 LONG Handle_Exception(struct _EXCEPTION_POINTERS* exceptionInfo, address handler) { 1852 JavaThread* thread = JavaThread::current(); 1853 // Save pc in thread 1854 #ifdef _M_IA64 1855 thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->StIIP); 1856 // Set pc to handler 1857 exceptionInfo->ContextRecord->StIIP = (DWORD64)handler; 1858 #elif _M_AMD64 1859 thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Rip); 1860 // Set pc to handler 1861 exceptionInfo->ContextRecord->Rip = (DWORD64)handler; 1862 #else 1863 thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Eip); 1864 // Set pc to handler 1865 exceptionInfo->ContextRecord->Eip = (LONG)handler; 1866 #endif 1867 1868 // Continue the execution 1869 return EXCEPTION_CONTINUE_EXECUTION; 1870 } 1871 1872 1873 // Used for PostMortemDump 1874 extern "C" void safepoints(); 1875 extern "C" void find(int x); 1876 extern "C" void events(); 1877 1878 // According to Windows API documentation, an illegal instruction sequence should generate 1879 // the 0xC000001C exception code. However, real world experience shows that occasionnaly 1880 // the execution of an illegal instruction can generate the exception code 0xC000001E. This 1881 // seems to be an undocumented feature of Win NT 4.0 (and probably other Windows systems). 1882 1883 #define EXCEPTION_ILLEGAL_INSTRUCTION_2 0xC000001E 1884 1885 // From "Execution Protection in the Windows Operating System" draft 0.35 1886 // Once a system header becomes available, the "real" define should be 1887 // included or copied here. 1888 #define EXCEPTION_INFO_EXEC_VIOLATION 0x08 1889 1890 #define def_excpt(val) #val, val 1891 1892 struct siglabel { 1893 char *name; 1894 int number; 1895 }; 1896 1897 struct siglabel exceptlabels[] = { 1898 def_excpt(EXCEPTION_ACCESS_VIOLATION), 1899 def_excpt(EXCEPTION_DATATYPE_MISALIGNMENT), 1900 def_excpt(EXCEPTION_BREAKPOINT), 1901 def_excpt(EXCEPTION_SINGLE_STEP), 1902 def_excpt(EXCEPTION_ARRAY_BOUNDS_EXCEEDED), 1903 def_excpt(EXCEPTION_FLT_DENORMAL_OPERAND), 1904 def_excpt(EXCEPTION_FLT_DIVIDE_BY_ZERO), 1905 def_excpt(EXCEPTION_FLT_INEXACT_RESULT), 1906 def_excpt(EXCEPTION_FLT_INVALID_OPERATION), 1907 def_excpt(EXCEPTION_FLT_OVERFLOW), 1908 def_excpt(EXCEPTION_FLT_STACK_CHECK), 1909 def_excpt(EXCEPTION_FLT_UNDERFLOW), 1910 def_excpt(EXCEPTION_INT_DIVIDE_BY_ZERO), 1911 def_excpt(EXCEPTION_INT_OVERFLOW), 1912 def_excpt(EXCEPTION_PRIV_INSTRUCTION), 1913 def_excpt(EXCEPTION_IN_PAGE_ERROR), 1914 def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION), 1915 def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION_2), 1916 def_excpt(EXCEPTION_NONCONTINUABLE_EXCEPTION), 1917 def_excpt(EXCEPTION_STACK_OVERFLOW), 1918 def_excpt(EXCEPTION_INVALID_DISPOSITION), 1919 def_excpt(EXCEPTION_GUARD_PAGE), 1920 def_excpt(EXCEPTION_INVALID_HANDLE), 1921 NULL, 0 1922 }; 1923 1924 const char* os::exception_name(int exception_code, char *buf, size_t size) { 1925 for (int i = 0; exceptlabels[i].name != NULL; i++) { 1926 if (exceptlabels[i].number == exception_code) { 1927 jio_snprintf(buf, size, "%s", exceptlabels[i].name); 1928 return buf; 1929 } 1930 } 1931 1932 return NULL; 1933 } 1934 1935 //----------------------------------------------------------------------------- 1936 LONG Handle_IDiv_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) { 1937 // handle exception caused by idiv; should only happen for -MinInt/-1 1938 // (division by zero is handled explicitly) 1939 #ifdef _M_IA64 1940 assert(0, "Fix Handle_IDiv_Exception"); 1941 #elif _M_AMD64 1942 PCONTEXT ctx = exceptionInfo->ContextRecord; 1943 address pc = (address)ctx->Rip; 1944 NOT_PRODUCT(Events::log("idiv overflow exception at " INTPTR_FORMAT , pc)); 1945 assert(pc[0] == 0xF7, "not an idiv opcode"); 1946 assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands"); 1947 assert(ctx->Rax == min_jint, "unexpected idiv exception"); 1948 // set correct result values and continue after idiv instruction 1949 ctx->Rip = (DWORD)pc + 2; // idiv reg, reg is 2 bytes 1950 ctx->Rax = (DWORD)min_jint; // result 1951 ctx->Rdx = (DWORD)0; // remainder 1952 // Continue the execution 1953 #else 1954 PCONTEXT ctx = exceptionInfo->ContextRecord; 1955 address pc = (address)ctx->Eip; 1956 NOT_PRODUCT(Events::log("idiv overflow exception at " INTPTR_FORMAT , pc)); 1957 assert(pc[0] == 0xF7, "not an idiv opcode"); 1958 assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands"); 1959 assert(ctx->Eax == min_jint, "unexpected idiv exception"); 1960 // set correct result values and continue after idiv instruction 1961 ctx->Eip = (DWORD)pc + 2; // idiv reg, reg is 2 bytes 1962 ctx->Eax = (DWORD)min_jint; // result 1963 ctx->Edx = (DWORD)0; // remainder 1964 // Continue the execution 1965 #endif 1966 return EXCEPTION_CONTINUE_EXECUTION; 1967 } 1968 1969 #ifndef _WIN64 1970 //----------------------------------------------------------------------------- 1971 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) { 1972 // handle exception caused by native mothod modifying control word 1973 PCONTEXT ctx = exceptionInfo->ContextRecord; 1974 DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode; 1975 1976 switch (exception_code) { 1977 case EXCEPTION_FLT_DENORMAL_OPERAND: 1978 case EXCEPTION_FLT_DIVIDE_BY_ZERO: 1979 case EXCEPTION_FLT_INEXACT_RESULT: 1980 case EXCEPTION_FLT_INVALID_OPERATION: 1981 case EXCEPTION_FLT_OVERFLOW: 1982 case EXCEPTION_FLT_STACK_CHECK: 1983 case EXCEPTION_FLT_UNDERFLOW: 1984 jint fp_control_word = (* (jint*) StubRoutines::addr_fpu_cntrl_wrd_std()); 1985 if (fp_control_word != ctx->FloatSave.ControlWord) { 1986 // Restore FPCW and mask out FLT exceptions 1987 ctx->FloatSave.ControlWord = fp_control_word | 0xffffffc0; 1988 // Mask out pending FLT exceptions 1989 ctx->FloatSave.StatusWord &= 0xffffff00; 1990 return EXCEPTION_CONTINUE_EXECUTION; 1991 } 1992 } 1993 return EXCEPTION_CONTINUE_SEARCH; 1994 } 1995 #else //_WIN64 1996 /* 1997 On Windows, the mxcsr control bits are non-volatile across calls 1998 See also CR 6192333 1999 If EXCEPTION_FLT_* happened after some native method modified 2000 mxcsr - it is not a jvm fault. 2001 However should we decide to restore of mxcsr after a faulty 2002 native method we can uncomment following code 2003 jint MxCsr = INITIAL_MXCSR; 2004 // we can't use StubRoutines::addr_mxcsr_std() 2005 // because in Win64 mxcsr is not saved there 2006 if (MxCsr != ctx->MxCsr) { 2007 ctx->MxCsr = MxCsr; 2008 return EXCEPTION_CONTINUE_EXECUTION; 2009 } 2010 2011 */ 2012 #endif //_WIN64 2013 2014 2015 // Fatal error reporting is single threaded so we can make this a 2016 // static and preallocated. If it's more than MAX_PATH silently ignore 2017 // it. 2018 static char saved_error_file[MAX_PATH] = {0}; 2019 2020 void os::set_error_file(const char *logfile) { 2021 if (strlen(logfile) <= MAX_PATH) { 2022 strncpy(saved_error_file, logfile, MAX_PATH); 2023 } 2024 } 2025 2026 static inline void report_error(Thread* t, DWORD exception_code, 2027 address addr, void* siginfo, void* context) { 2028 VMError err(t, exception_code, addr, siginfo, context); 2029 err.report_and_die(); 2030 2031 // If UseOsErrorReporting, this will return here and save the error file 2032 // somewhere where we can find it in the minidump. 2033 } 2034 2035 //----------------------------------------------------------------------------- 2036 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { 2037 if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH; 2038 DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode; 2039 #ifdef _M_IA64 2040 address pc = (address) exceptionInfo->ContextRecord->StIIP; 2041 #elif _M_AMD64 2042 address pc = (address) exceptionInfo->ContextRecord->Rip; 2043 #else 2044 address pc = (address) exceptionInfo->ContextRecord->Eip; 2045 #endif 2046 Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady 2047 2048 #ifndef _WIN64 2049 // Execution protection violation - win32 running on AMD64 only 2050 // Handled first to avoid misdiagnosis as a "normal" access violation; 2051 // This is safe to do because we have a new/unique ExceptionInformation 2052 // code for this condition. 2053 if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2054 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2055 int exception_subcode = (int) exceptionRecord->ExceptionInformation[0]; 2056 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2057 2058 if (exception_subcode == EXCEPTION_INFO_EXEC_VIOLATION) { 2059 int page_size = os::vm_page_size(); 2060 2061 // Make sure the pc and the faulting address are sane. 2062 // 2063 // If an instruction spans a page boundary, and the page containing 2064 // the beginning of the instruction is executable but the following 2065 // page is not, the pc and the faulting address might be slightly 2066 // different - we still want to unguard the 2nd page in this case. 2067 // 2068 // 15 bytes seems to be a (very) safe value for max instruction size. 2069 bool pc_is_near_addr = 2070 (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15); 2071 bool instr_spans_page_boundary = 2072 (align_size_down((intptr_t) pc ^ (intptr_t) addr, 2073 (intptr_t) page_size) > 0); 2074 2075 if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) { 2076 static volatile address last_addr = 2077 (address) os::non_memory_address_word(); 2078 2079 // In conservative mode, don't unguard unless the address is in the VM 2080 if (UnguardOnExecutionViolation > 0 && addr != last_addr && 2081 (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) { 2082 2083 // Set memory to RWX and retry 2084 address page_start = 2085 (address) align_size_down((intptr_t) addr, (intptr_t) page_size); 2086 bool res = os::protect_memory((char*) page_start, page_size, 2087 os::MEM_PROT_RWX); 2088 2089 if (PrintMiscellaneous && Verbose) { 2090 char buf[256]; 2091 jio_snprintf(buf, sizeof(buf), "Execution protection violation " 2092 "at " INTPTR_FORMAT 2093 ", unguarding " INTPTR_FORMAT ": %s", addr, 2094 page_start, (res ? "success" : strerror(errno))); 2095 tty->print_raw_cr(buf); 2096 } 2097 2098 // Set last_addr so if we fault again at the same address, we don't 2099 // end up in an endless loop. 2100 // 2101 // There are two potential complications here. Two threads trapping 2102 // at the same address at the same time could cause one of the 2103 // threads to think it already unguarded, and abort the VM. Likely 2104 // very rare. 2105 // 2106 // The other race involves two threads alternately trapping at 2107 // different addresses and failing to unguard the page, resulting in 2108 // an endless loop. This condition is probably even more unlikely 2109 // than the first. 2110 // 2111 // Although both cases could be avoided by using locks or thread 2112 // local last_addr, these solutions are unnecessary complication: 2113 // this handler is a best-effort safety net, not a complete solution. 2114 // It is disabled by default and should only be used as a workaround 2115 // in case we missed any no-execute-unsafe VM code. 2116 2117 last_addr = addr; 2118 2119 return EXCEPTION_CONTINUE_EXECUTION; 2120 } 2121 } 2122 2123 // Last unguard failed or not unguarding 2124 tty->print_raw_cr("Execution protection violation"); 2125 report_error(t, exception_code, addr, exceptionInfo->ExceptionRecord, 2126 exceptionInfo->ContextRecord); 2127 return EXCEPTION_CONTINUE_SEARCH; 2128 } 2129 } 2130 #endif // _WIN64 2131 2132 // Check to see if we caught the safepoint code in the 2133 // process of write protecting the memory serialization page. 2134 // It write enables the page immediately after protecting it 2135 // so just return. 2136 if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) { 2137 JavaThread* thread = (JavaThread*) t; 2138 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2139 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2140 if ( os::is_memory_serialize_page(thread, addr) ) { 2141 // Block current thread until the memory serialize page permission restored. 2142 os::block_on_serialize_page_trap(); 2143 return EXCEPTION_CONTINUE_EXECUTION; 2144 } 2145 } 2146 2147 2148 if (t != NULL && t->is_Java_thread()) { 2149 JavaThread* thread = (JavaThread*) t; 2150 bool in_java = thread->thread_state() == _thread_in_Java; 2151 2152 // Handle potential stack overflows up front. 2153 if (exception_code == EXCEPTION_STACK_OVERFLOW) { 2154 if (os::uses_stack_guard_pages()) { 2155 #ifdef _M_IA64 2156 // 2157 // If it's a legal stack address continue, Windows will map it in. 2158 // 2159 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2160 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2161 if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) 2162 return EXCEPTION_CONTINUE_EXECUTION; 2163 2164 // The register save area is the same size as the memory stack 2165 // and starts at the page just above the start of the memory stack. 2166 // If we get a fault in this area, we've run out of register 2167 // stack. If we are in java, try throwing a stack overflow exception. 2168 if (addr > thread->stack_base() && 2169 addr <= (thread->stack_base()+thread->stack_size()) ) { 2170 char buf[256]; 2171 jio_snprintf(buf, sizeof(buf), 2172 "Register stack overflow, addr:%p, stack_base:%p\n", 2173 addr, thread->stack_base() ); 2174 tty->print_raw_cr(buf); 2175 // If not in java code, return and hope for the best. 2176 return in_java ? Handle_Exception(exceptionInfo, 2177 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)) 2178 : EXCEPTION_CONTINUE_EXECUTION; 2179 } 2180 #endif 2181 if (thread->stack_yellow_zone_enabled()) { 2182 // Yellow zone violation. The o/s has unprotected the first yellow 2183 // zone page for us. Note: must call disable_stack_yellow_zone to 2184 // update the enabled status, even if the zone contains only one page. 2185 thread->disable_stack_yellow_zone(); 2186 // If not in java code, return and hope for the best. 2187 return in_java ? Handle_Exception(exceptionInfo, 2188 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)) 2189 : EXCEPTION_CONTINUE_EXECUTION; 2190 } else { 2191 // Fatal red zone violation. 2192 thread->disable_stack_red_zone(); 2193 tty->print_raw_cr("An unrecoverable stack overflow has occurred."); 2194 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2195 exceptionInfo->ContextRecord); 2196 return EXCEPTION_CONTINUE_SEARCH; 2197 } 2198 } else if (in_java) { 2199 // JVM-managed guard pages cannot be used on win95/98. The o/s provides 2200 // a one-time-only guard page, which it has released to us. The next 2201 // stack overflow on this thread will result in an ACCESS_VIOLATION. 2202 return Handle_Exception(exceptionInfo, 2203 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)); 2204 } else { 2205 // Can only return and hope for the best. Further stack growth will 2206 // result in an ACCESS_VIOLATION. 2207 return EXCEPTION_CONTINUE_EXECUTION; 2208 } 2209 } else if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2210 // Either stack overflow or null pointer exception. 2211 if (in_java) { 2212 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2213 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2214 address stack_end = thread->stack_base() - thread->stack_size(); 2215 if (addr < stack_end && addr >= stack_end - os::vm_page_size()) { 2216 // Stack overflow. 2217 assert(!os::uses_stack_guard_pages(), 2218 "should be caught by red zone code above."); 2219 return Handle_Exception(exceptionInfo, 2220 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)); 2221 } 2222 // 2223 // Check for safepoint polling and implicit null 2224 // We only expect null pointers in the stubs (vtable) 2225 // the rest are checked explicitly now. 2226 // 2227 CodeBlob* cb = CodeCache::find_blob(pc); 2228 if (cb != NULL) { 2229 if (os::is_poll_address(addr)) { 2230 address stub = SharedRuntime::get_poll_stub(pc); 2231 return Handle_Exception(exceptionInfo, stub); 2232 } 2233 } 2234 { 2235 #ifdef _WIN64 2236 // 2237 // If it's a legal stack address map the entire region in 2238 // 2239 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; 2240 address addr = (address) exceptionRecord->ExceptionInformation[1]; 2241 if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) { 2242 addr = (address)((uintptr_t)addr & 2243 (~((uintptr_t)os::vm_page_size() - (uintptr_t)1))); 2244 os::commit_memory((char *)addr, thread->stack_base() - addr, 2245 false ); 2246 return EXCEPTION_CONTINUE_EXECUTION; 2247 } 2248 else 2249 #endif 2250 { 2251 // Null pointer exception. 2252 #ifdef _M_IA64 2253 // We catch register stack overflows in compiled code by doing 2254 // an explicit compare and executing a st8(G0, G0) if the 2255 // BSP enters into our guard area. We test for the overflow 2256 // condition and fall into the normal null pointer exception 2257 // code if BSP hasn't overflowed. 2258 if ( in_java ) { 2259 if(thread->register_stack_overflow()) { 2260 assert((address)exceptionInfo->ContextRecord->IntS3 == 2261 thread->register_stack_limit(), 2262 "GR7 doesn't contain register_stack_limit"); 2263 // Disable the yellow zone which sets the state that 2264 // we've got a stack overflow problem. 2265 if (thread->stack_yellow_zone_enabled()) { 2266 thread->disable_stack_yellow_zone(); 2267 } 2268 // Give us some room to process the exception 2269 thread->disable_register_stack_guard(); 2270 // Update GR7 with the new limit so we can continue running 2271 // compiled code. 2272 exceptionInfo->ContextRecord->IntS3 = 2273 (ULONGLONG)thread->register_stack_limit(); 2274 return Handle_Exception(exceptionInfo, 2275 SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW)); 2276 } else { 2277 // 2278 // Check for implicit null 2279 // We only expect null pointers in the stubs (vtable) 2280 // the rest are checked explicitly now. 2281 // 2282 if (((uintptr_t)addr) < os::vm_page_size() ) { 2283 // an access to the first page of VM--assume it is a null pointer 2284 address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL); 2285 if (stub != NULL) return Handle_Exception(exceptionInfo, stub); 2286 } 2287 } 2288 } // in_java 2289 2290 // IA64 doesn't use implicit null checking yet. So we shouldn't 2291 // get here. 2292 tty->print_raw_cr("Access violation, possible null pointer exception"); 2293 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2294 exceptionInfo->ContextRecord); 2295 return EXCEPTION_CONTINUE_SEARCH; 2296 #else /* !IA64 */ 2297 2298 // Windows 98 reports faulting addresses incorrectly 2299 if (!MacroAssembler::needs_explicit_null_check((intptr_t)addr) || 2300 !os::win32::is_nt()) { 2301 address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL); 2302 if (stub != NULL) return Handle_Exception(exceptionInfo, stub); 2303 } 2304 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2305 exceptionInfo->ContextRecord); 2306 return EXCEPTION_CONTINUE_SEARCH; 2307 #endif 2308 } 2309 } 2310 } 2311 2312 #ifdef _WIN64 2313 // Special care for fast JNI field accessors. 2314 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks 2315 // in and the heap gets shrunk before the field access. 2316 if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2317 address addr = JNI_FastGetField::find_slowcase_pc(pc); 2318 if (addr != (address)-1) { 2319 return Handle_Exception(exceptionInfo, addr); 2320 } 2321 } 2322 #endif 2323 2324 #ifdef _WIN64 2325 // Windows will sometimes generate an access violation 2326 // when we call malloc. Since we use VectoredExceptions 2327 // on 64 bit platforms, we see this exception. We must 2328 // pass this exception on so Windows can recover. 2329 // We check to see if the pc of the fault is in NTDLL.DLL 2330 // if so, we pass control on to Windows for handling. 2331 if (UseVectoredExceptions && _addr_in_ntdll(pc)) return EXCEPTION_CONTINUE_SEARCH; 2332 #endif 2333 2334 // Stack overflow or null pointer exception in native code. 2335 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2336 exceptionInfo->ContextRecord); 2337 return EXCEPTION_CONTINUE_SEARCH; 2338 } 2339 2340 if (in_java) { 2341 switch (exception_code) { 2342 case EXCEPTION_INT_DIVIDE_BY_ZERO: 2343 return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO)); 2344 2345 case EXCEPTION_INT_OVERFLOW: 2346 return Handle_IDiv_Exception(exceptionInfo); 2347 2348 } // switch 2349 } 2350 #ifndef _WIN64 2351 if ((thread->thread_state() == _thread_in_Java) || 2352 (thread->thread_state() == _thread_in_native) ) 2353 { 2354 LONG result=Handle_FLT_Exception(exceptionInfo); 2355 if (result==EXCEPTION_CONTINUE_EXECUTION) return result; 2356 } 2357 #endif //_WIN64 2358 } 2359 2360 if (exception_code != EXCEPTION_BREAKPOINT) { 2361 #ifndef _WIN64 2362 report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2363 exceptionInfo->ContextRecord); 2364 #else 2365 // Itanium Windows uses a VectoredExceptionHandler 2366 // Which means that C++ programatic exception handlers (try/except) 2367 // will get here. Continue the search for the right except block if 2368 // the exception code is not a fatal code. 2369 switch ( exception_code ) { 2370 case EXCEPTION_ACCESS_VIOLATION: 2371 case EXCEPTION_STACK_OVERFLOW: 2372 case EXCEPTION_ILLEGAL_INSTRUCTION: 2373 case EXCEPTION_ILLEGAL_INSTRUCTION_2: 2374 case EXCEPTION_INT_OVERFLOW: 2375 case EXCEPTION_INT_DIVIDE_BY_ZERO: 2376 { report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord, 2377 exceptionInfo->ContextRecord); 2378 } 2379 break; 2380 default: 2381 break; 2382 } 2383 #endif 2384 } 2385 return EXCEPTION_CONTINUE_SEARCH; 2386 } 2387 2388 #ifndef _WIN64 2389 // Special care for fast JNI accessors. 2390 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and 2391 // the heap gets shrunk before the field access. 2392 // Need to install our own structured exception handler since native code may 2393 // install its own. 2394 LONG WINAPI fastJNIAccessorExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { 2395 DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode; 2396 if (exception_code == EXCEPTION_ACCESS_VIOLATION) { 2397 address pc = (address) exceptionInfo->ContextRecord->Eip; 2398 address addr = JNI_FastGetField::find_slowcase_pc(pc); 2399 if (addr != (address)-1) { 2400 return Handle_Exception(exceptionInfo, addr); 2401 } 2402 } 2403 return EXCEPTION_CONTINUE_SEARCH; 2404 } 2405 2406 #define DEFINE_FAST_GETFIELD(Return,Fieldname,Result) \ 2407 Return JNICALL jni_fast_Get##Result##Field_wrapper(JNIEnv *env, jobject obj, jfieldID fieldID) { \ 2408 __try { \ 2409 return (*JNI_FastGetField::jni_fast_Get##Result##Field_fp)(env, obj, fieldID); \ 2410 } __except(fastJNIAccessorExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) { \ 2411 } \ 2412 return 0; \ 2413 } 2414 2415 DEFINE_FAST_GETFIELD(jboolean, bool, Boolean) 2416 DEFINE_FAST_GETFIELD(jbyte, byte, Byte) 2417 DEFINE_FAST_GETFIELD(jchar, char, Char) 2418 DEFINE_FAST_GETFIELD(jshort, short, Short) 2419 DEFINE_FAST_GETFIELD(jint, int, Int) 2420 DEFINE_FAST_GETFIELD(jlong, long, Long) 2421 DEFINE_FAST_GETFIELD(jfloat, float, Float) 2422 DEFINE_FAST_GETFIELD(jdouble, double, Double) 2423 2424 address os::win32::fast_jni_accessor_wrapper(BasicType type) { 2425 switch (type) { 2426 case T_BOOLEAN: return (address)jni_fast_GetBooleanField_wrapper; 2427 case T_BYTE: return (address)jni_fast_GetByteField_wrapper; 2428 case T_CHAR: return (address)jni_fast_GetCharField_wrapper; 2429 case T_SHORT: return (address)jni_fast_GetShortField_wrapper; 2430 case T_INT: return (address)jni_fast_GetIntField_wrapper; 2431 case T_LONG: return (address)jni_fast_GetLongField_wrapper; 2432 case T_FLOAT: return (address)jni_fast_GetFloatField_wrapper; 2433 case T_DOUBLE: return (address)jni_fast_GetDoubleField_wrapper; 2434 default: ShouldNotReachHere(); 2435 } 2436 return (address)-1; 2437 } 2438 #endif 2439 2440 // Virtual Memory 2441 2442 int os::vm_page_size() { return os::win32::vm_page_size(); } 2443 int os::vm_allocation_granularity() { 2444 return os::win32::vm_allocation_granularity(); 2445 } 2446 2447 // Windows large page support is available on Windows 2003. In order to use 2448 // large page memory, the administrator must first assign additional privilege 2449 // to the user: 2450 // + select Control Panel -> Administrative Tools -> Local Security Policy 2451 // + select Local Policies -> User Rights Assignment 2452 // + double click "Lock pages in memory", add users and/or groups 2453 // + reboot 2454 // Note the above steps are needed for administrator as well, as administrators 2455 // by default do not have the privilege to lock pages in memory. 2456 // 2457 // Note about Windows 2003: although the API supports committing large page 2458 // memory on a page-by-page basis and VirtualAlloc() returns success under this 2459 // scenario, I found through experiment it only uses large page if the entire 2460 // memory region is reserved and committed in a single VirtualAlloc() call. 2461 // This makes Windows large page support more or less like Solaris ISM, in 2462 // that the entire heap must be committed upfront. This probably will change 2463 // in the future, if so the code below needs to be revisited. 2464 2465 #ifndef MEM_LARGE_PAGES 2466 #define MEM_LARGE_PAGES 0x20000000 2467 #endif 2468 2469 // GetLargePageMinimum is only available on Windows 2003. The other functions 2470 // are available on NT but not on Windows 98/Me. We have to resolve them at 2471 // runtime. 2472 typedef SIZE_T (WINAPI *GetLargePageMinimum_func_type) (void); 2473 typedef BOOL (WINAPI *AdjustTokenPrivileges_func_type) 2474 (HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD); 2475 typedef BOOL (WINAPI *OpenProcessToken_func_type) (HANDLE, DWORD, PHANDLE); 2476 typedef BOOL (WINAPI *LookupPrivilegeValue_func_type) (LPCTSTR, LPCTSTR, PLUID); 2477 2478 static GetLargePageMinimum_func_type _GetLargePageMinimum; 2479 static AdjustTokenPrivileges_func_type _AdjustTokenPrivileges; 2480 static OpenProcessToken_func_type _OpenProcessToken; 2481 static LookupPrivilegeValue_func_type _LookupPrivilegeValue; 2482 2483 static HINSTANCE _kernel32; 2484 static HINSTANCE _advapi32; 2485 static HANDLE _hProcess; 2486 static HANDLE _hToken; 2487 2488 static size_t _large_page_size = 0; 2489 2490 static bool resolve_functions_for_large_page_init() { 2491 _kernel32 = LoadLibrary("kernel32.dll"); 2492 if (_kernel32 == NULL) return false; 2493 2494 _GetLargePageMinimum = CAST_TO_FN_PTR(GetLargePageMinimum_func_type, 2495 GetProcAddress(_kernel32, "GetLargePageMinimum")); 2496 if (_GetLargePageMinimum == NULL) return false; 2497 2498 _advapi32 = LoadLibrary("advapi32.dll"); 2499 if (_advapi32 == NULL) return false; 2500 2501 _AdjustTokenPrivileges = CAST_TO_FN_PTR(AdjustTokenPrivileges_func_type, 2502 GetProcAddress(_advapi32, "AdjustTokenPrivileges")); 2503 _OpenProcessToken = CAST_TO_FN_PTR(OpenProcessToken_func_type, 2504 GetProcAddress(_advapi32, "OpenProcessToken")); 2505 _LookupPrivilegeValue = CAST_TO_FN_PTR(LookupPrivilegeValue_func_type, 2506 GetProcAddress(_advapi32, "LookupPrivilegeValueA")); 2507 return _AdjustTokenPrivileges != NULL && 2508 _OpenProcessToken != NULL && 2509 _LookupPrivilegeValue != NULL; 2510 } 2511 2512 static bool request_lock_memory_privilege() { 2513 _hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 2514 os::current_process_id()); 2515 2516 LUID luid; 2517 if (_hProcess != NULL && 2518 _OpenProcessToken(_hProcess, TOKEN_ADJUST_PRIVILEGES, &_hToken) && 2519 _LookupPrivilegeValue(NULL, "SeLockMemoryPrivilege", &luid)) { 2520 2521 TOKEN_PRIVILEGES tp; 2522 tp.PrivilegeCount = 1; 2523 tp.Privileges[0].Luid = luid; 2524 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 2525 2526 // AdjustTokenPrivileges() may return TRUE even when it couldn't change the 2527 // privilege. Check GetLastError() too. See MSDN document. 2528 if (_AdjustTokenPrivileges(_hToken, false, &tp, sizeof(tp), NULL, NULL) && 2529 (GetLastError() == ERROR_SUCCESS)) { 2530 return true; 2531 } 2532 } 2533 2534 return false; 2535 } 2536 2537 static void cleanup_after_large_page_init() { 2538 _GetLargePageMinimum = NULL; 2539 _AdjustTokenPrivileges = NULL; 2540 _OpenProcessToken = NULL; 2541 _LookupPrivilegeValue = NULL; 2542 if (_kernel32) FreeLibrary(_kernel32); 2543 _kernel32 = NULL; 2544 if (_advapi32) FreeLibrary(_advapi32); 2545 _advapi32 = NULL; 2546 if (_hProcess) CloseHandle(_hProcess); 2547 _hProcess = NULL; 2548 if (_hToken) CloseHandle(_hToken); 2549 _hToken = NULL; 2550 } 2551 2552 bool os::large_page_init() { 2553 if (!UseLargePages) return false; 2554 2555 // print a warning if any large page related flag is specified on command line 2556 bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) || 2557 !FLAG_IS_DEFAULT(LargePageSizeInBytes); 2558 bool success = false; 2559 2560 # define WARN(msg) if (warn_on_failure) { warning(msg); } 2561 if (resolve_functions_for_large_page_init()) { 2562 if (request_lock_memory_privilege()) { 2563 size_t s = _GetLargePageMinimum(); 2564 if (s) { 2565 #if defined(IA32) || defined(AMD64) 2566 if (s > 4*M || LargePageSizeInBytes > 4*M) { 2567 WARN("JVM cannot use large pages bigger than 4mb."); 2568 } else { 2569 #endif 2570 if (LargePageSizeInBytes && LargePageSizeInBytes % s == 0) { 2571 _large_page_size = LargePageSizeInBytes; 2572 } else { 2573 _large_page_size = s; 2574 } 2575 success = true; 2576 #if defined(IA32) || defined(AMD64) 2577 } 2578 #endif 2579 } else { 2580 WARN("Large page is not supported by the processor."); 2581 } 2582 } else { 2583 WARN("JVM cannot use large page memory because it does not have enough privilege to lock pages in memory."); 2584 } 2585 } else { 2586 WARN("Large page is not supported by the operating system."); 2587 } 2588 #undef WARN 2589 2590 const size_t default_page_size = (size_t) vm_page_size(); 2591 if (success && _large_page_size > default_page_size) { 2592 _page_sizes[0] = _large_page_size; 2593 _page_sizes[1] = default_page_size; 2594 _page_sizes[2] = 0; 2595 } 2596 2597 cleanup_after_large_page_init(); 2598 return success; 2599 } 2600 2601 // On win32, one cannot release just a part of reserved memory, it's an 2602 // all or nothing deal. When we split a reservation, we must break the 2603 // reservation into two reservations. 2604 void os::split_reserved_memory(char *base, size_t size, size_t split, 2605 bool realloc) { 2606 if (size > 0) { 2607 release_memory(base, size); 2608 if (realloc) { 2609 reserve_memory(split, base); 2610 } 2611 if (size != split) { 2612 reserve_memory(size - split, base + split); 2613 } 2614 } 2615 } 2616 2617 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) { 2618 assert((size_t)addr % os::vm_allocation_granularity() == 0, 2619 "reserve alignment"); 2620 assert(bytes % os::vm_allocation_granularity() == 0, "reserve block size"); 2621 char* res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE, PAGE_READWRITE); 2622 assert(res == NULL || addr == NULL || addr == res, 2623 "Unexpected address from reserve."); 2624 return res; 2625 } 2626 2627 // Reserve memory at an arbitrary address, only if that area is 2628 // available (and not reserved for something else). 2629 char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2630 // Windows os::reserve_memory() fails of the requested address range is 2631 // not avilable. 2632 return reserve_memory(bytes, requested_addr); 2633 } 2634 2635 size_t os::large_page_size() { 2636 return _large_page_size; 2637 } 2638 2639 bool os::can_commit_large_page_memory() { 2640 // Windows only uses large page memory when the entire region is reserved 2641 // and committed in a single VirtualAlloc() call. This may change in the 2642 // future, but with Windows 2003 it's not possible to commit on demand. 2643 return false; 2644 } 2645 2646 bool os::can_execute_large_page_memory() { 2647 return true; 2648 } 2649 2650 char* os::reserve_memory_special(size_t bytes, char* addr, bool exec) { 2651 2652 const DWORD prot = exec ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; 2653 2654 if (UseLargePagesIndividualAllocation) { 2655 if (TracePageSizes && Verbose) { 2656 tty->print_cr("Reserving large pages individually."); 2657 } 2658 char * p_buf; 2659 // first reserve enough address space in advance since we want to be 2660 // able to break a single contiguous virtual address range into multiple 2661 // large page commits but WS2003 does not allow reserving large page space 2662 // so we just use 4K pages for reserve, this gives us a legal contiguous 2663 // address space. then we will deallocate that reservation, and re alloc 2664 // using large pages 2665 const size_t size_of_reserve = bytes + _large_page_size; 2666 if (bytes > size_of_reserve) { 2667 // Overflowed. 2668 warning("Individually allocated large pages failed, " 2669 "use -XX:-UseLargePagesIndividualAllocation to turn off"); 2670 return NULL; 2671 } 2672 p_buf = (char *) VirtualAlloc(addr, 2673 size_of_reserve, // size of Reserve 2674 MEM_RESERVE, 2675 PAGE_READWRITE); 2676 // If reservation failed, return NULL 2677 if (p_buf == NULL) return NULL; 2678 2679 release_memory(p_buf, bytes + _large_page_size); 2680 // round up to page boundary. If the size_of_reserve did not 2681 // overflow and the reservation did not fail, this align up 2682 // should not overflow. 2683 p_buf = (char *) align_size_up((size_t)p_buf, _large_page_size); 2684 2685 // now go through and allocate one page at a time until all bytes are 2686 // allocated 2687 size_t bytes_remaining = align_size_up(bytes, _large_page_size); 2688 // An overflow of align_size_up() would have been caught above 2689 // in the calculation of size_of_reserve. 2690 char * next_alloc_addr = p_buf; 2691 2692 #ifdef ASSERT 2693 // Variable for the failure injection 2694 long ran_num = os::random(); 2695 size_t fail_after = ran_num % bytes; 2696 #endif 2697 2698 while (bytes_remaining) { 2699 size_t bytes_to_rq = MIN2(bytes_remaining, _large_page_size); 2700 // Note allocate and commit 2701 char * p_new; 2702 2703 #ifdef ASSERT 2704 bool inject_error = LargePagesIndividualAllocationInjectError && 2705 (bytes_remaining <= fail_after); 2706 #else 2707 const bool inject_error = false; 2708 #endif 2709 2710 if (inject_error) { 2711 p_new = NULL; 2712 } else { 2713 p_new = (char *) VirtualAlloc(next_alloc_addr, 2714 bytes_to_rq, 2715 MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, 2716 prot); 2717 } 2718 2719 if (p_new == NULL) { 2720 // Free any allocated pages 2721 if (next_alloc_addr > p_buf) { 2722 // Some memory was committed so release it. 2723 size_t bytes_to_release = bytes - bytes_remaining; 2724 release_memory(p_buf, bytes_to_release); 2725 } 2726 #ifdef ASSERT 2727 if (UseLargePagesIndividualAllocation && 2728 LargePagesIndividualAllocationInjectError) { 2729 if (TracePageSizes && Verbose) { 2730 tty->print_cr("Reserving large pages individually failed."); 2731 } 2732 } 2733 #endif 2734 return NULL; 2735 } 2736 bytes_remaining -= bytes_to_rq; 2737 next_alloc_addr += bytes_to_rq; 2738 } 2739 2740 return p_buf; 2741 2742 } else { 2743 // normal policy just allocate it all at once 2744 DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES; 2745 char * res = (char *)VirtualAlloc(NULL, bytes, flag, prot); 2746 return res; 2747 } 2748 } 2749 2750 bool os::release_memory_special(char* base, size_t bytes) { 2751 return release_memory(base, bytes); 2752 } 2753 2754 void os::print_statistics() { 2755 } 2756 2757 bool os::commit_memory(char* addr, size_t bytes, bool exec) { 2758 if (bytes == 0) { 2759 // Don't bother the OS with noops. 2760 return true; 2761 } 2762 assert((size_t) addr % os::vm_page_size() == 0, "commit on page boundaries"); 2763 assert(bytes % os::vm_page_size() == 0, "commit in page-sized chunks"); 2764 // Don't attempt to print anything if the OS call fails. We're 2765 // probably low on resources, so the print itself may cause crashes. 2766 bool result = VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) != 0; 2767 if (result != NULL && exec) { 2768 DWORD oldprot; 2769 // Windows doc says to use VirtualProtect to get execute permissions 2770 return VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot) != 0; 2771 } else { 2772 return result; 2773 } 2774 } 2775 2776 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint, 2777 bool exec) { 2778 return commit_memory(addr, size, exec); 2779 } 2780 2781 bool os::uncommit_memory(char* addr, size_t bytes) { 2782 if (bytes == 0) { 2783 // Don't bother the OS with noops. 2784 return true; 2785 } 2786 assert((size_t) addr % os::vm_page_size() == 0, "uncommit on page boundaries"); 2787 assert(bytes % os::vm_page_size() == 0, "uncommit in page-sized chunks"); 2788 return VirtualFree(addr, bytes, MEM_DECOMMIT) != 0; 2789 } 2790 2791 bool os::release_memory(char* addr, size_t bytes) { 2792 return VirtualFree(addr, 0, MEM_RELEASE) != 0; 2793 } 2794 2795 // Set protections specified 2796 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 2797 bool is_committed) { 2798 unsigned int p = 0; 2799 switch (prot) { 2800 case MEM_PROT_NONE: p = PAGE_NOACCESS; break; 2801 case MEM_PROT_READ: p = PAGE_READONLY; break; 2802 case MEM_PROT_RW: p = PAGE_READWRITE; break; 2803 case MEM_PROT_RWX: p = PAGE_EXECUTE_READWRITE; break; 2804 default: 2805 ShouldNotReachHere(); 2806 } 2807 2808 DWORD old_status; 2809 2810 // Strange enough, but on Win32 one can change protection only for committed 2811 // memory, not a big deal anyway, as bytes less or equal than 64K 2812 if (!is_committed && !commit_memory(addr, bytes, prot == MEM_PROT_RWX)) { 2813 fatal("cannot commit protection page"); 2814 } 2815 // One cannot use os::guard_memory() here, as on Win32 guard page 2816 // have different (one-shot) semantics, from MSDN on PAGE_GUARD: 2817 // 2818 // Pages in the region become guard pages. Any attempt to access a guard page 2819 // causes the system to raise a STATUS_GUARD_PAGE exception and turn off 2820 // the guard page status. Guard pages thus act as a one-time access alarm. 2821 return VirtualProtect(addr, bytes, p, &old_status) != 0; 2822 } 2823 2824 bool os::guard_memory(char* addr, size_t bytes) { 2825 DWORD old_status; 2826 return VirtualProtect(addr, bytes, PAGE_READWRITE | PAGE_GUARD, &old_status) != 0; 2827 } 2828 2829 bool os::unguard_memory(char* addr, size_t bytes) { 2830 DWORD old_status; 2831 return VirtualProtect(addr, bytes, PAGE_READWRITE, &old_status) != 0; 2832 } 2833 2834 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { } 2835 void os::free_memory(char *addr, size_t bytes) { } 2836 void os::numa_make_global(char *addr, size_t bytes) { } 2837 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { } 2838 bool os::numa_topology_changed() { return false; } 2839 size_t os::numa_get_groups_num() { return 1; } 2840 int os::numa_get_group_id() { return 0; } 2841 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2842 if (size > 0) { 2843 ids[0] = 0; 2844 return 1; 2845 } 2846 return 0; 2847 } 2848 2849 bool os::get_page_info(char *start, page_info* info) { 2850 return false; 2851 } 2852 2853 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { 2854 return end; 2855 } 2856 2857 char* os::non_memory_address_word() { 2858 // Must never look like an address returned by reserve_memory, 2859 // even in its subfields (as defined by the CPU immediate fields, 2860 // if the CPU splits constants across multiple instructions). 2861 return (char*)-1; 2862 } 2863 2864 #define MAX_ERROR_COUNT 100 2865 #define SYS_THREAD_ERROR 0xffffffffUL 2866 2867 void os::pd_start_thread(Thread* thread) { 2868 DWORD ret = ResumeThread(thread->osthread()->thread_handle()); 2869 // Returns previous suspend state: 2870 // 0: Thread was not suspended 2871 // 1: Thread is running now 2872 // >1: Thread is still suspended. 2873 assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back 2874 } 2875 2876 size_t os::read(int fd, void *buf, unsigned int nBytes) { 2877 return ::read(fd, buf, nBytes); 2878 } 2879 2880 class HighResolutionInterval { 2881 // The default timer resolution seems to be 10 milliseconds. 2882 // (Where is this written down?) 2883 // If someone wants to sleep for only a fraction of the default, 2884 // then we set the timer resolution down to 1 millisecond for 2885 // the duration of their interval. 2886 // We carefully set the resolution back, since otherwise we 2887 // seem to incur an overhead (3%?) that we don't need. 2888 // CONSIDER: if ms is small, say 3, then we should run with a high resolution time. 2889 // Buf if ms is large, say 500, or 503, we should avoid the call to timeBeginPeriod(). 2890 // Alternatively, we could compute the relative error (503/500 = .6%) and only use 2891 // timeBeginPeriod() if the relative error exceeded some threshold. 2892 // timeBeginPeriod() has been linked to problems with clock drift on win32 systems and 2893 // to decreased efficiency related to increased timer "tick" rates. We want to minimize 2894 // (a) calls to timeBeginPeriod() and timeEndPeriod() and (b) time spent with high 2895 // resolution timers running. 2896 private: 2897 jlong resolution; 2898 public: 2899 HighResolutionInterval(jlong ms) { 2900 resolution = ms % 10L; 2901 if (resolution != 0) { 2902 MMRESULT result = timeBeginPeriod(1L); 2903 } 2904 } 2905 ~HighResolutionInterval() { 2906 if (resolution != 0) { 2907 MMRESULT result = timeEndPeriod(1L); 2908 } 2909 resolution = 0L; 2910 } 2911 }; 2912 2913 int os::sleep(Thread* thread, jlong ms, bool interruptable) { 2914 jlong limit = (jlong) MAXDWORD; 2915 2916 while(ms > limit) { 2917 int res; 2918 if ((res = sleep(thread, limit, interruptable)) != OS_TIMEOUT) 2919 return res; 2920 ms -= limit; 2921 } 2922 2923 assert(thread == Thread::current(), "thread consistency check"); 2924 OSThread* osthread = thread->osthread(); 2925 OSThreadWaitState osts(osthread, false /* not Object.wait() */); 2926 int result; 2927 if (interruptable) { 2928 assert(thread->is_Java_thread(), "must be java thread"); 2929 JavaThread *jt = (JavaThread *) thread; 2930 ThreadBlockInVM tbivm(jt); 2931 2932 jt->set_suspend_equivalent(); 2933 // cleared by handle_special_suspend_equivalent_condition() or 2934 // java_suspend_self() via check_and_wait_while_suspended() 2935 2936 HANDLE events[1]; 2937 events[0] = osthread->interrupt_event(); 2938 HighResolutionInterval *phri=NULL; 2939 if(!ForceTimeHighResolution) 2940 phri = new HighResolutionInterval( ms ); 2941 if (WaitForMultipleObjects(1, events, FALSE, (DWORD)ms) == WAIT_TIMEOUT) { 2942 result = OS_TIMEOUT; 2943 } else { 2944 ResetEvent(osthread->interrupt_event()); 2945 osthread->set_interrupted(false); 2946 result = OS_INTRPT; 2947 } 2948 delete phri; //if it is NULL, harmless 2949 2950 // were we externally suspended while we were waiting? 2951 jt->check_and_wait_while_suspended(); 2952 } else { 2953 assert(!thread->is_Java_thread(), "must not be java thread"); 2954 Sleep((long) ms); 2955 result = OS_TIMEOUT; 2956 } 2957 return result; 2958 } 2959 2960 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 2961 void os::infinite_sleep() { 2962 while (true) { // sleep forever ... 2963 Sleep(100000); // ... 100 seconds at a time 2964 } 2965 } 2966 2967 typedef BOOL (WINAPI * STTSignature)(void) ; 2968 2969 os::YieldResult os::NakedYield() { 2970 // Use either SwitchToThread() or Sleep(0) 2971 // Consider passing back the return value from SwitchToThread(). 2972 // We use GetProcAddress() as ancient Win9X versions of windows doen't support SwitchToThread. 2973 // In that case we revert to Sleep(0). 2974 static volatile STTSignature stt = (STTSignature) 1 ; 2975 2976 if (stt == ((STTSignature) 1)) { 2977 stt = (STTSignature) ::GetProcAddress (LoadLibrary ("Kernel32.dll"), "SwitchToThread") ; 2978 // It's OK if threads race during initialization as the operation above is idempotent. 2979 } 2980 if (stt != NULL) { 2981 return (*stt)() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ; 2982 } else { 2983 Sleep (0) ; 2984 } 2985 return os::YIELD_UNKNOWN ; 2986 } 2987 2988 void os::yield() { os::NakedYield(); } 2989 2990 void os::yield_all(int attempts) { 2991 // Yields to all threads, including threads with lower priorities 2992 Sleep(1); 2993 } 2994 2995 // Win32 only gives you access to seven real priorities at a time, 2996 // so we compress Java's ten down to seven. It would be better 2997 // if we dynamically adjusted relative priorities. 2998 2999 int os::java_to_os_priority[MaxPriority + 1] = { 3000 THREAD_PRIORITY_IDLE, // 0 Entry should never be used 3001 THREAD_PRIORITY_LOWEST, // 1 MinPriority 3002 THREAD_PRIORITY_LOWEST, // 2 3003 THREAD_PRIORITY_BELOW_NORMAL, // 3 3004 THREAD_PRIORITY_BELOW_NORMAL, // 4 3005 THREAD_PRIORITY_NORMAL, // 5 NormPriority 3006 THREAD_PRIORITY_NORMAL, // 6 3007 THREAD_PRIORITY_ABOVE_NORMAL, // 7 3008 THREAD_PRIORITY_ABOVE_NORMAL, // 8 3009 THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority 3010 THREAD_PRIORITY_HIGHEST // 10 MaxPriority 3011 }; 3012 3013 int prio_policy1[MaxPriority + 1] = { 3014 THREAD_PRIORITY_IDLE, // 0 Entry should never be used 3015 THREAD_PRIORITY_LOWEST, // 1 MinPriority 3016 THREAD_PRIORITY_LOWEST, // 2 3017 THREAD_PRIORITY_BELOW_NORMAL, // 3 3018 THREAD_PRIORITY_BELOW_NORMAL, // 4 3019 THREAD_PRIORITY_NORMAL, // 5 NormPriority 3020 THREAD_PRIORITY_ABOVE_NORMAL, // 6 3021 THREAD_PRIORITY_ABOVE_NORMAL, // 7 3022 THREAD_PRIORITY_HIGHEST, // 8 3023 THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority 3024 THREAD_PRIORITY_TIME_CRITICAL // 10 MaxPriority 3025 }; 3026 3027 static int prio_init() { 3028 // If ThreadPriorityPolicy is 1, switch tables 3029 if (ThreadPriorityPolicy == 1) { 3030 int i; 3031 for (i = 0; i < MaxPriority + 1; i++) { 3032 os::java_to_os_priority[i] = prio_policy1[i]; 3033 } 3034 } 3035 return 0; 3036 } 3037 3038 OSReturn os::set_native_priority(Thread* thread, int priority) { 3039 if (!UseThreadPriorities) return OS_OK; 3040 bool ret = SetThreadPriority(thread->osthread()->thread_handle(), priority) != 0; 3041 return ret ? OS_OK : OS_ERR; 3042 } 3043 3044 OSReturn os::get_native_priority(const Thread* const thread, int* priority_ptr) { 3045 if ( !UseThreadPriorities ) { 3046 *priority_ptr = java_to_os_priority[NormPriority]; 3047 return OS_OK; 3048 } 3049 int os_prio = GetThreadPriority(thread->osthread()->thread_handle()); 3050 if (os_prio == THREAD_PRIORITY_ERROR_RETURN) { 3051 assert(false, "GetThreadPriority failed"); 3052 return OS_ERR; 3053 } 3054 *priority_ptr = os_prio; 3055 return OS_OK; 3056 } 3057 3058 3059 // Hint to the underlying OS that a task switch would not be good. 3060 // Void return because it's a hint and can fail. 3061 void os::hint_no_preempt() {} 3062 3063 void os::interrupt(Thread* thread) { 3064 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(), 3065 "possibility of dangling Thread pointer"); 3066 3067 OSThread* osthread = thread->osthread(); 3068 osthread->set_interrupted(true); 3069 // More than one thread can get here with the same value of osthread, 3070 // resulting in multiple notifications. We do, however, want the store 3071 // to interrupted() to be visible to other threads before we post 3072 // the interrupt event. 3073 OrderAccess::release(); 3074 SetEvent(osthread->interrupt_event()); 3075 // For JSR166: unpark after setting status 3076 if (thread->is_Java_thread()) 3077 ((JavaThread*)thread)->parker()->unpark(); 3078 3079 ParkEvent * ev = thread->_ParkEvent ; 3080 if (ev != NULL) ev->unpark() ; 3081 3082 } 3083 3084 3085 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 3086 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(), 3087 "possibility of dangling Thread pointer"); 3088 3089 OSThread* osthread = thread->osthread(); 3090 bool interrupted; 3091 interrupted = osthread->interrupted(); 3092 if (clear_interrupted == true) { 3093 osthread->set_interrupted(false); 3094 ResetEvent(osthread->interrupt_event()); 3095 } // Otherwise leave the interrupted state alone 3096 3097 return interrupted; 3098 } 3099 3100 // Get's a pc (hint) for a running thread. Currently used only for profiling. 3101 ExtendedPC os::get_thread_pc(Thread* thread) { 3102 CONTEXT context; 3103 context.ContextFlags = CONTEXT_CONTROL; 3104 HANDLE handle = thread->osthread()->thread_handle(); 3105 #ifdef _M_IA64 3106 assert(0, "Fix get_thread_pc"); 3107 return ExtendedPC(NULL); 3108 #else 3109 if (GetThreadContext(handle, &context)) { 3110 #ifdef _M_AMD64 3111 return ExtendedPC((address) context.Rip); 3112 #else 3113 return ExtendedPC((address) context.Eip); 3114 #endif 3115 } else { 3116 return ExtendedPC(NULL); 3117 } 3118 #endif 3119 } 3120 3121 // GetCurrentThreadId() returns DWORD 3122 intx os::current_thread_id() { return GetCurrentThreadId(); } 3123 3124 static int _initial_pid = 0; 3125 3126 int os::current_process_id() 3127 { 3128 return (_initial_pid ? _initial_pid : _getpid()); 3129 } 3130 3131 int os::win32::_vm_page_size = 0; 3132 int os::win32::_vm_allocation_granularity = 0; 3133 int os::win32::_processor_type = 0; 3134 // Processor level is not available on non-NT systems, use vm_version instead 3135 int os::win32::_processor_level = 0; 3136 julong os::win32::_physical_memory = 0; 3137 size_t os::win32::_default_stack_size = 0; 3138 3139 intx os::win32::_os_thread_limit = 0; 3140 volatile intx os::win32::_os_thread_count = 0; 3141 3142 bool os::win32::_is_nt = false; 3143 bool os::win32::_is_windows_2003 = false; 3144 3145 3146 void os::win32::initialize_system_info() { 3147 SYSTEM_INFO si; 3148 GetSystemInfo(&si); 3149 _vm_page_size = si.dwPageSize; 3150 _vm_allocation_granularity = si.dwAllocationGranularity; 3151 _processor_type = si.dwProcessorType; 3152 _processor_level = si.wProcessorLevel; 3153 set_processor_count(si.dwNumberOfProcessors); 3154 3155 MEMORYSTATUSEX ms; 3156 ms.dwLength = sizeof(ms); 3157 3158 // also returns dwAvailPhys (free physical memory bytes), dwTotalVirtual, dwAvailVirtual, 3159 // dwMemoryLoad (% of memory in use) 3160 GlobalMemoryStatusEx(&ms); 3161 _physical_memory = ms.ullTotalPhys; 3162 3163 OSVERSIONINFO oi; 3164 oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); 3165 GetVersionEx(&oi); 3166 switch(oi.dwPlatformId) { 3167 case VER_PLATFORM_WIN32_WINDOWS: _is_nt = false; break; 3168 case VER_PLATFORM_WIN32_NT: 3169 _is_nt = true; 3170 { 3171 int os_vers = oi.dwMajorVersion * 1000 + oi.dwMinorVersion; 3172 if (os_vers == 5002) { 3173 _is_windows_2003 = true; 3174 } 3175 } 3176 break; 3177 default: fatal("Unknown platform"); 3178 } 3179 3180 _default_stack_size = os::current_stack_size(); 3181 assert(_default_stack_size > (size_t) _vm_page_size, "invalid stack size"); 3182 assert((_default_stack_size & (_vm_page_size - 1)) == 0, 3183 "stack size not a multiple of page size"); 3184 3185 initialize_performance_counter(); 3186 3187 // Win95/Win98 scheduler bug work-around. The Win95/98 scheduler is 3188 // known to deadlock the system, if the VM issues to thread operations with 3189 // a too high frequency, e.g., such as changing the priorities. 3190 // The 6000 seems to work well - no deadlocks has been notices on the test 3191 // programs that we have seen experience this problem. 3192 if (!os::win32::is_nt()) { 3193 StarvationMonitorInterval = 6000; 3194 } 3195 } 3196 3197 3198 void os::win32::setmode_streams() { 3199 _setmode(_fileno(stdin), _O_BINARY); 3200 _setmode(_fileno(stdout), _O_BINARY); 3201 _setmode(_fileno(stderr), _O_BINARY); 3202 } 3203 3204 3205 int os::message_box(const char* title, const char* message) { 3206 int result = MessageBox(NULL, message, title, 3207 MB_YESNO | MB_ICONERROR | MB_SYSTEMMODAL | MB_DEFAULT_DESKTOP_ONLY); 3208 return result == IDYES; 3209 } 3210 3211 int os::allocate_thread_local_storage() { 3212 return TlsAlloc(); 3213 } 3214 3215 3216 void os::free_thread_local_storage(int index) { 3217 TlsFree(index); 3218 } 3219 3220 3221 void os::thread_local_storage_at_put(int index, void* value) { 3222 TlsSetValue(index, value); 3223 assert(thread_local_storage_at(index) == value, "Just checking"); 3224 } 3225 3226 3227 void* os::thread_local_storage_at(int index) { 3228 return TlsGetValue(index); 3229 } 3230 3231 3232 #ifndef PRODUCT 3233 #ifndef _WIN64 3234 // Helpers to check whether NX protection is enabled 3235 int nx_exception_filter(_EXCEPTION_POINTERS *pex) { 3236 if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && 3237 pex->ExceptionRecord->NumberParameters > 0 && 3238 pex->ExceptionRecord->ExceptionInformation[0] == 3239 EXCEPTION_INFO_EXEC_VIOLATION) { 3240 return EXCEPTION_EXECUTE_HANDLER; 3241 } 3242 return EXCEPTION_CONTINUE_SEARCH; 3243 } 3244 3245 void nx_check_protection() { 3246 // If NX is enabled we'll get an exception calling into code on the stack 3247 char code[] = { (char)0xC3 }; // ret 3248 void *code_ptr = (void *)code; 3249 __try { 3250 __asm call code_ptr 3251 } __except(nx_exception_filter((_EXCEPTION_POINTERS*)_exception_info())) { 3252 tty->print_raw_cr("NX protection detected."); 3253 } 3254 } 3255 #endif // _WIN64 3256 #endif // PRODUCT 3257 3258 // this is called _before_ the global arguments have been parsed 3259 void os::init(void) { 3260 _initial_pid = _getpid(); 3261 3262 init_random(1234567); 3263 3264 win32::initialize_system_info(); 3265 win32::setmode_streams(); 3266 init_page_sizes((size_t) win32::vm_page_size()); 3267 3268 // For better scalability on MP systems (must be called after initialize_system_info) 3269 #ifndef PRODUCT 3270 if (is_MP()) { 3271 NoYieldsInMicrolock = true; 3272 } 3273 #endif 3274 // This may be overridden later when argument processing is done. 3275 FLAG_SET_ERGO(bool, UseLargePagesIndividualAllocation, 3276 os::win32::is_windows_2003()); 3277 3278 // Initialize main_process and main_thread 3279 main_process = GetCurrentProcess(); // Remember main_process is a pseudo handle 3280 if (!DuplicateHandle(main_process, GetCurrentThread(), main_process, 3281 &main_thread, THREAD_ALL_ACCESS, false, 0)) { 3282 fatal("DuplicateHandle failed\n"); 3283 } 3284 main_thread_id = (int) GetCurrentThreadId(); 3285 } 3286 3287 // To install functions for atexit processing 3288 extern "C" { 3289 static void perfMemory_exit_helper() { 3290 perfMemory_exit(); 3291 } 3292 } 3293 3294 3295 // this is called _after_ the global arguments have been parsed 3296 jint os::init_2(void) { 3297 // Allocate a single page and mark it as readable for safepoint polling 3298 address polling_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READONLY); 3299 guarantee( polling_page != NULL, "Reserve Failed for polling page"); 3300 3301 address return_page = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY); 3302 guarantee( return_page != NULL, "Commit Failed for polling page"); 3303 3304 os::set_polling_page( polling_page ); 3305 3306 #ifndef PRODUCT 3307 if( Verbose && PrintMiscellaneous ) 3308 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); 3309 #endif 3310 3311 if (!UseMembar) { 3312 address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE); 3313 guarantee( mem_serialize_page != NULL, "Reserve Failed for memory serialize page"); 3314 3315 return_page = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE); 3316 guarantee( return_page != NULL, "Commit Failed for memory serialize page"); 3317 3318 os::set_memory_serialize_page( mem_serialize_page ); 3319 3320 #ifndef PRODUCT 3321 if(Verbose && PrintMiscellaneous) 3322 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); 3323 #endif 3324 } 3325 3326 FLAG_SET_DEFAULT(UseLargePages, os::large_page_init()); 3327 3328 // Setup Windows Exceptions 3329 3330 // On Itanium systems, Structured Exception Handling does not 3331 // work since stack frames must be walkable by the OS. Since 3332 // much of our code is dynamically generated, and we do not have 3333 // proper unwind .xdata sections, the system simply exits 3334 // rather than delivering the exception. To work around 3335 // this we use VectorExceptions instead. 3336 #ifdef _WIN64 3337 if (UseVectoredExceptions) { 3338 topLevelVectoredExceptionHandler = AddVectoredExceptionHandler( 1, topLevelExceptionFilter); 3339 } 3340 #endif 3341 3342 // for debugging float code generation bugs 3343 if (ForceFloatExceptions) { 3344 #ifndef _WIN64 3345 static long fp_control_word = 0; 3346 __asm { fstcw fp_control_word } 3347 // see Intel PPro Manual, Vol. 2, p 7-16 3348 const long precision = 0x20; 3349 const long underflow = 0x10; 3350 const long overflow = 0x08; 3351 const long zero_div = 0x04; 3352 const long denorm = 0x02; 3353 const long invalid = 0x01; 3354 fp_control_word |= invalid; 3355 __asm { fldcw fp_control_word } 3356 #endif 3357 } 3358 3359 // Initialize HPI. 3360 jint hpi_result = hpi::initialize(); 3361 if (hpi_result != JNI_OK) { return hpi_result; } 3362 3363 // If stack_commit_size is 0, windows will reserve the default size, 3364 // but only commit a small portion of it. 3365 size_t stack_commit_size = round_to(ThreadStackSize*K, os::vm_page_size()); 3366 size_t default_reserve_size = os::win32::default_stack_size(); 3367 size_t actual_reserve_size = stack_commit_size; 3368 if (stack_commit_size < default_reserve_size) { 3369 // If stack_commit_size == 0, we want this too 3370 actual_reserve_size = default_reserve_size; 3371 } 3372 3373 JavaThread::set_stack_size_at_create(stack_commit_size); 3374 3375 // Calculate theoretical max. size of Threads to guard gainst artifical 3376 // out-of-memory situations, where all available address-space has been 3377 // reserved by thread stacks. 3378 assert(actual_reserve_size != 0, "Must have a stack"); 3379 3380 // Calculate the thread limit when we should start doing Virtual Memory 3381 // banging. Currently when the threads will have used all but 200Mb of space. 3382 // 3383 // TODO: consider performing a similar calculation for commit size instead 3384 // as reserve size, since on a 64-bit platform we'll run into that more 3385 // often than running out of virtual memory space. We can use the 3386 // lower value of the two calculations as the os_thread_limit. 3387 size_t max_address_space = ((size_t)1 << (BitsPerWord - 1)) - (200 * K * K); 3388 win32::_os_thread_limit = (intx)(max_address_space / actual_reserve_size); 3389 3390 // at exit methods are called in the reverse order of their registration. 3391 // there is no limit to the number of functions registered. atexit does 3392 // not set errno. 3393 3394 if (PerfAllowAtExitRegistration) { 3395 // only register atexit functions if PerfAllowAtExitRegistration is set. 3396 // atexit functions can be delayed until process exit time, which 3397 // can be problematic for embedded VM situations. Embedded VMs should 3398 // call DestroyJavaVM() to assure that VM resources are released. 3399 3400 // note: perfMemory_exit_helper atexit function may be removed in 3401 // the future if the appropriate cleanup code can be added to the 3402 // VM_Exit VMOperation's doit method. 3403 if (atexit(perfMemory_exit_helper) != 0) { 3404 warning("os::init_2 atexit(perfMemory_exit_helper) failed"); 3405 } 3406 } 3407 3408 // initialize PSAPI or ToolHelp for fatal error handler 3409 if (win32::is_nt()) _init_psapi(); 3410 else _init_toolhelp(); 3411 3412 #ifndef _WIN64 3413 // Print something if NX is enabled (win32 on AMD64) 3414 NOT_PRODUCT(if (PrintMiscellaneous && Verbose) nx_check_protection()); 3415 #endif 3416 3417 // initialize thread priority policy 3418 prio_init(); 3419 3420 if (UseNUMA && !ForceNUMA) { 3421 UseNUMA = false; // Currently unsupported. 3422 } 3423 3424 return JNI_OK; 3425 } 3426 3427 3428 // Mark the polling page as unreadable 3429 void os::make_polling_page_unreadable(void) { 3430 DWORD old_status; 3431 if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_NOACCESS, &old_status) ) 3432 fatal("Could not disable polling page"); 3433 }; 3434 3435 // Mark the polling page as readable 3436 void os::make_polling_page_readable(void) { 3437 DWORD old_status; 3438 if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_READONLY, &old_status) ) 3439 fatal("Could not enable polling page"); 3440 }; 3441 3442 3443 int os::stat(const char *path, struct stat *sbuf) { 3444 char pathbuf[MAX_PATH]; 3445 if (strlen(path) > MAX_PATH - 1) { 3446 errno = ENAMETOOLONG; 3447 return -1; 3448 } 3449 hpi::native_path(strcpy(pathbuf, path)); 3450 int ret = ::stat(pathbuf, sbuf); 3451 if (sbuf != NULL && UseUTCFileTimestamp) { 3452 // Fix for 6539723. st_mtime returned from stat() is dependent on 3453 // the system timezone and so can return different values for the 3454 // same file if/when daylight savings time changes. This adjustment 3455 // makes sure the same timestamp is returned regardless of the TZ. 3456 // 3457 // See: 3458 // http://msdn.microsoft.com/library/ 3459 // default.asp?url=/library/en-us/sysinfo/base/ 3460 // time_zone_information_str.asp 3461 // and 3462 // http://msdn.microsoft.com/library/default.asp?url= 3463 // /library/en-us/sysinfo/base/settimezoneinformation.asp 3464 // 3465 // NOTE: there is a insidious bug here: If the timezone is changed 3466 // after the call to stat() but before 'GetTimeZoneInformation()', then 3467 // the adjustment we do here will be wrong and we'll return the wrong 3468 // value (which will likely end up creating an invalid class data 3469 // archive). Absent a better API for this, or some time zone locking 3470 // mechanism, we'll have to live with this risk. 3471 TIME_ZONE_INFORMATION tz; 3472 DWORD tzid = GetTimeZoneInformation(&tz); 3473 int daylightBias = 3474 (tzid == TIME_ZONE_ID_DAYLIGHT) ? tz.DaylightBias : tz.StandardBias; 3475 sbuf->st_mtime += (tz.Bias + daylightBias) * 60; 3476 } 3477 return ret; 3478 } 3479 3480 3481 #define FT2INT64(ft) \ 3482 ((jlong)((jlong)(ft).dwHighDateTime << 32 | (julong)(ft).dwLowDateTime)) 3483 3484 3485 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 3486 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 3487 // of a thread. 3488 // 3489 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns 3490 // the fast estimate available on the platform. 3491 3492 // current_thread_cpu_time() is not optimized for Windows yet 3493 jlong os::current_thread_cpu_time() { 3494 // return user + sys since the cost is the same 3495 return os::thread_cpu_time(Thread::current(), true /* user+sys */); 3496 } 3497 3498 jlong os::thread_cpu_time(Thread* thread) { 3499 // consistent with what current_thread_cpu_time() returns. 3500 return os::thread_cpu_time(thread, true /* user+sys */); 3501 } 3502 3503 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 3504 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 3505 } 3506 3507 jlong os::thread_cpu_time(Thread* thread, bool user_sys_cpu_time) { 3508 // This code is copy from clasic VM -> hpi::sysThreadCPUTime 3509 // If this function changes, os::is_thread_cpu_time_supported() should too 3510 if (os::win32::is_nt()) { 3511 FILETIME CreationTime; 3512 FILETIME ExitTime; 3513 FILETIME KernelTime; 3514 FILETIME UserTime; 3515 3516 if ( GetThreadTimes(thread->osthread()->thread_handle(), 3517 &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0) 3518 return -1; 3519 else 3520 if (user_sys_cpu_time) { 3521 return (FT2INT64(UserTime) + FT2INT64(KernelTime)) * 100; 3522 } else { 3523 return FT2INT64(UserTime) * 100; 3524 } 3525 } else { 3526 return (jlong) timeGetTime() * 1000000; 3527 } 3528 } 3529 3530 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 3531 info_ptr->max_value = ALL_64_BITS; // the max value -- all 64 bits 3532 info_ptr->may_skip_backward = false; // GetThreadTimes returns absolute time 3533 info_ptr->may_skip_forward = false; // GetThreadTimes returns absolute time 3534 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 3535 } 3536 3537 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 3538 info_ptr->max_value = ALL_64_BITS; // the max value -- all 64 bits 3539 info_ptr->may_skip_backward = false; // GetThreadTimes returns absolute time 3540 info_ptr->may_skip_forward = false; // GetThreadTimes returns absolute time 3541 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 3542 } 3543 3544 bool os::is_thread_cpu_time_supported() { 3545 // see os::thread_cpu_time 3546 if (os::win32::is_nt()) { 3547 FILETIME CreationTime; 3548 FILETIME ExitTime; 3549 FILETIME KernelTime; 3550 FILETIME UserTime; 3551 3552 if ( GetThreadTimes(GetCurrentThread(), 3553 &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0) 3554 return false; 3555 else 3556 return true; 3557 } else { 3558 return false; 3559 } 3560 } 3561 3562 // Windows does't provide a loadavg primitive so this is stubbed out for now. 3563 // It does have primitives (PDH API) to get CPU usage and run queue length. 3564 // "\\Processor(_Total)\\% Processor Time", "\\System\\Processor Queue Length" 3565 // If we wanted to implement loadavg on Windows, we have a few options: 3566 // 3567 // a) Query CPU usage and run queue length and "fake" an answer by 3568 // returning the CPU usage if it's under 100%, and the run queue 3569 // length otherwise. It turns out that querying is pretty slow 3570 // on Windows, on the order of 200 microseconds on a fast machine. 3571 // Note that on the Windows the CPU usage value is the % usage 3572 // since the last time the API was called (and the first call 3573 // returns 100%), so we'd have to deal with that as well. 3574 // 3575 // b) Sample the "fake" answer using a sampling thread and store 3576 // the answer in a global variable. The call to loadavg would 3577 // just return the value of the global, avoiding the slow query. 3578 // 3579 // c) Sample a better answer using exponential decay to smooth the 3580 // value. This is basically the algorithm used by UNIX kernels. 3581 // 3582 // Note that sampling thread starvation could affect both (b) and (c). 3583 int os::loadavg(double loadavg[], int nelem) { 3584 return -1; 3585 } 3586 3587 3588 // DontYieldALot=false by default: dutifully perform all yields as requested by JVM_Yield() 3589 bool os::dont_yield() { 3590 return DontYieldALot; 3591 } 3592 3593 // Is a (classpath) directory empty? 3594 bool os::dir_is_empty(const char* path) { 3595 WIN32_FIND_DATA fd; 3596 HANDLE f = FindFirstFile(path, &fd); 3597 if (f == INVALID_HANDLE_VALUE) { 3598 return true; 3599 } 3600 FindClose(f); 3601 return false; 3602 } 3603 3604 // create binary file, rewriting existing file if required 3605 int os::create_binary_file(const char* path, bool rewrite_existing) { 3606 int oflags = _O_CREAT | _O_WRONLY | _O_BINARY; 3607 if (!rewrite_existing) { 3608 oflags |= _O_EXCL; 3609 } 3610 return ::open(path, oflags, _S_IREAD | _S_IWRITE); 3611 } 3612 3613 // return current position of file pointer 3614 jlong os::current_file_offset(int fd) { 3615 return (jlong)::_lseeki64(fd, (__int64)0L, SEEK_CUR); 3616 } 3617 3618 // move file pointer to the specified offset 3619 jlong os::seek_to_file_offset(int fd, jlong offset) { 3620 return (jlong)::_lseeki64(fd, (__int64)offset, SEEK_SET); 3621 } 3622 3623 3624 // Map a block of memory. 3625 char* os::map_memory(int fd, const char* file_name, size_t file_offset, 3626 char *addr, size_t bytes, bool read_only, 3627 bool allow_exec) { 3628 HANDLE hFile; 3629 char* base; 3630 3631 hFile = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, 3632 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 3633 if (hFile == NULL) { 3634 if (PrintMiscellaneous && Verbose) { 3635 DWORD err = GetLastError(); 3636 tty->print_cr("CreateFile() failed: GetLastError->%ld."); 3637 } 3638 return NULL; 3639 } 3640 3641 if (allow_exec) { 3642 // CreateFileMapping/MapViewOfFileEx can't map executable memory 3643 // unless it comes from a PE image (which the shared archive is not.) 3644 // Even VirtualProtect refuses to give execute access to mapped memory 3645 // that was not previously executable. 3646 // 3647 // Instead, stick the executable region in anonymous memory. Yuck. 3648 // Penalty is that ~4 pages will not be shareable - in the future 3649 // we might consider DLLizing the shared archive with a proper PE 3650 // header so that mapping executable + sharing is possible. 3651 3652 base = (char*) VirtualAlloc(addr, bytes, MEM_COMMIT | MEM_RESERVE, 3653 PAGE_READWRITE); 3654 if (base == NULL) { 3655 if (PrintMiscellaneous && Verbose) { 3656 DWORD err = GetLastError(); 3657 tty->print_cr("VirtualAlloc() failed: GetLastError->%ld.", err); 3658 } 3659 CloseHandle(hFile); 3660 return NULL; 3661 } 3662 3663 DWORD bytes_read; 3664 OVERLAPPED overlapped; 3665 overlapped.Offset = (DWORD)file_offset; 3666 overlapped.OffsetHigh = 0; 3667 overlapped.hEvent = NULL; 3668 // ReadFile guarantees that if the return value is true, the requested 3669 // number of bytes were read before returning. 3670 bool res = ReadFile(hFile, base, (DWORD)bytes, &bytes_read, &overlapped) != 0; 3671 if (!res) { 3672 if (PrintMiscellaneous && Verbose) { 3673 DWORD err = GetLastError(); 3674 tty->print_cr("ReadFile() failed: GetLastError->%ld.", err); 3675 } 3676 release_memory(base, bytes); 3677 CloseHandle(hFile); 3678 return NULL; 3679 } 3680 } else { 3681 HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0, 3682 NULL /*file_name*/); 3683 if (hMap == NULL) { 3684 if (PrintMiscellaneous && Verbose) { 3685 DWORD err = GetLastError(); 3686 tty->print_cr("CreateFileMapping() failed: GetLastError->%ld."); 3687 } 3688 CloseHandle(hFile); 3689 return NULL; 3690 } 3691 3692 DWORD access = read_only ? FILE_MAP_READ : FILE_MAP_COPY; 3693 base = (char*)MapViewOfFileEx(hMap, access, 0, (DWORD)file_offset, 3694 (DWORD)bytes, addr); 3695 if (base == NULL) { 3696 if (PrintMiscellaneous && Verbose) { 3697 DWORD err = GetLastError(); 3698 tty->print_cr("MapViewOfFileEx() failed: GetLastError->%ld.", err); 3699 } 3700 CloseHandle(hMap); 3701 CloseHandle(hFile); 3702 return NULL; 3703 } 3704 3705 if (CloseHandle(hMap) == 0) { 3706 if (PrintMiscellaneous && Verbose) { 3707 DWORD err = GetLastError(); 3708 tty->print_cr("CloseHandle(hMap) failed: GetLastError->%ld.", err); 3709 } 3710 CloseHandle(hFile); 3711 return base; 3712 } 3713 } 3714 3715 if (allow_exec) { 3716 DWORD old_protect; 3717 DWORD exec_access = read_only ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE; 3718 bool res = VirtualProtect(base, bytes, exec_access, &old_protect) != 0; 3719 3720 if (!res) { 3721 if (PrintMiscellaneous && Verbose) { 3722 DWORD err = GetLastError(); 3723 tty->print_cr("VirtualProtect() failed: GetLastError->%ld.", err); 3724 } 3725 // Don't consider this a hard error, on IA32 even if the 3726 // VirtualProtect fails, we should still be able to execute 3727 CloseHandle(hFile); 3728 return base; 3729 } 3730 } 3731 3732 if (CloseHandle(hFile) == 0) { 3733 if (PrintMiscellaneous && Verbose) { 3734 DWORD err = GetLastError(); 3735 tty->print_cr("CloseHandle(hFile) failed: GetLastError->%ld.", err); 3736 } 3737 return base; 3738 } 3739 3740 return base; 3741 } 3742 3743 3744 // Remap a block of memory. 3745 char* os::remap_memory(int fd, const char* file_name, size_t file_offset, 3746 char *addr, size_t bytes, bool read_only, 3747 bool allow_exec) { 3748 // This OS does not allow existing memory maps to be remapped so we 3749 // have to unmap the memory before we remap it. 3750 if (!os::unmap_memory(addr, bytes)) { 3751 return NULL; 3752 } 3753 3754 // There is a very small theoretical window between the unmap_memory() 3755 // call above and the map_memory() call below where a thread in native 3756 // code may be able to access an address that is no longer mapped. 3757 3758 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 3759 allow_exec); 3760 } 3761 3762 3763 // Unmap a block of memory. 3764 // Returns true=success, otherwise false. 3765 3766 bool os::unmap_memory(char* addr, size_t bytes) { 3767 BOOL result = UnmapViewOfFile(addr); 3768 if (result == 0) { 3769 if (PrintMiscellaneous && Verbose) { 3770 DWORD err = GetLastError(); 3771 tty->print_cr("UnmapViewOfFile() failed: GetLastError->%ld.", err); 3772 } 3773 return false; 3774 } 3775 return true; 3776 } 3777 3778 void os::pause() { 3779 char filename[MAX_PATH]; 3780 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 3781 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 3782 } else { 3783 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 3784 } 3785 3786 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 3787 if (fd != -1) { 3788 struct stat buf; 3789 close(fd); 3790 while (::stat(filename, &buf) == 0) { 3791 Sleep(100); 3792 } 3793 } else { 3794 jio_fprintf(stderr, 3795 "Could not open pause file '%s', continuing immediately.\n", filename); 3796 } 3797 } 3798 3799 // An Event wraps a win32 "CreateEvent" kernel handle. 3800 // 3801 // We have a number of choices regarding "CreateEvent" win32 handle leakage: 3802 // 3803 // 1: When a thread dies return the Event to the EventFreeList, clear the ParkHandle 3804 // field, and call CloseHandle() on the win32 event handle. Unpark() would 3805 // need to be modified to tolerate finding a NULL (invalid) win32 event handle. 3806 // In addition, an unpark() operation might fetch the handle field, but the 3807 // event could recycle between the fetch and the SetEvent() operation. 3808 // SetEvent() would either fail because the handle was invalid, or inadvertently work, 3809 // as the win32 handle value had been recycled. In an ideal world calling SetEvent() 3810 // on an stale but recycled handle would be harmless, but in practice this might 3811 // confuse other non-Sun code, so it's not a viable approach. 3812 // 3813 // 2: Once a win32 event handle is associated with an Event, it remains associated 3814 // with the Event. The event handle is never closed. This could be construed 3815 // as handle leakage, but only up to the maximum # of threads that have been extant 3816 // at any one time. This shouldn't be an issue, as windows platforms typically 3817 // permit a process to have hundreds of thousands of open handles. 3818 // 3819 // 3: Same as (1), but periodically, at stop-the-world time, rundown the EventFreeList 3820 // and release unused handles. 3821 // 3822 // 4: Add a CRITICAL_SECTION to the Event to protect LD+SetEvent from LD;ST(null);CloseHandle. 3823 // It's not clear, however, that we wouldn't be trading one type of leak for another. 3824 // 3825 // 5. Use an RCU-like mechanism (Read-Copy Update). 3826 // Or perhaps something similar to Maged Michael's "Hazard pointers". 3827 // 3828 // We use (2). 3829 // 3830 // TODO-FIXME: 3831 // 1. Reconcile Doug's JSR166 j.u.c park-unpark with the objectmonitor implementation. 3832 // 2. Consider wrapping the WaitForSingleObject(Ex) calls in SEH try/finally blocks 3833 // to recover from (or at least detect) the dreaded Windows 841176 bug. 3834 // 3. Collapse the interrupt_event, the JSR166 parker event, and the objectmonitor ParkEvent 3835 // into a single win32 CreateEvent() handle. 3836 // 3837 // _Event transitions in park() 3838 // -1 => -1 : illegal 3839 // 1 => 0 : pass - return immediately 3840 // 0 => -1 : block 3841 // 3842 // _Event serves as a restricted-range semaphore : 3843 // -1 : thread is blocked 3844 // 0 : neutral - thread is running or ready 3845 // 1 : signaled - thread is running or ready 3846 // 3847 // Another possible encoding of _Event would be 3848 // with explicit "PARKED" and "SIGNALED" bits. 3849 3850 int os::PlatformEvent::park (jlong Millis) { 3851 guarantee (_ParkHandle != NULL , "Invariant") ; 3852 guarantee (Millis > 0 , "Invariant") ; 3853 int v ; 3854 3855 // CONSIDER: defer assigning a CreateEvent() handle to the Event until 3856 // the initial park() operation. 3857 3858 for (;;) { 3859 v = _Event ; 3860 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 3861 } 3862 guarantee ((v == 0) || (v == 1), "invariant") ; 3863 if (v != 0) return OS_OK ; 3864 3865 // Do this the hard way by blocking ... 3866 // TODO: consider a brief spin here, gated on the success of recent 3867 // spin attempts by this thread. 3868 // 3869 // We decompose long timeouts into series of shorter timed waits. 3870 // Evidently large timo values passed in WaitForSingleObject() are problematic on some 3871 // versions of Windows. See EventWait() for details. This may be superstition. Or not. 3872 // We trust the WAIT_TIMEOUT indication and don't track the elapsed wait time 3873 // with os::javaTimeNanos(). Furthermore, we assume that spurious returns from 3874 // ::WaitForSingleObject() caused by latent ::setEvent() operations will tend 3875 // to happen early in the wait interval. Specifically, after a spurious wakeup (rv == 3876 // WAIT_OBJECT_0 but _Event is still < 0) we don't bother to recompute Millis to compensate 3877 // for the already waited time. This policy does not admit any new outcomes. 3878 // In the future, however, we might want to track the accumulated wait time and 3879 // adjust Millis accordingly if we encounter a spurious wakeup. 3880 3881 const int MAXTIMEOUT = 0x10000000 ; 3882 DWORD rv = WAIT_TIMEOUT ; 3883 while (_Event < 0 && Millis > 0) { 3884 DWORD prd = Millis ; // set prd = MAX (Millis, MAXTIMEOUT) 3885 if (Millis > MAXTIMEOUT) { 3886 prd = MAXTIMEOUT ; 3887 } 3888 rv = ::WaitForSingleObject (_ParkHandle, prd) ; 3889 assert (rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed") ; 3890 if (rv == WAIT_TIMEOUT) { 3891 Millis -= prd ; 3892 } 3893 } 3894 v = _Event ; 3895 _Event = 0 ; 3896 OrderAccess::fence() ; 3897 // If we encounter a nearly simultanous timeout expiry and unpark() 3898 // we return OS_OK indicating we awoke via unpark(). 3899 // Implementor's license -- returning OS_TIMEOUT would be equally valid, however. 3900 return (v >= 0) ? OS_OK : OS_TIMEOUT ; 3901 } 3902 3903 void os::PlatformEvent::park () { 3904 guarantee (_ParkHandle != NULL, "Invariant") ; 3905 // Invariant: Only the thread associated with the Event/PlatformEvent 3906 // may call park(). 3907 int v ; 3908 for (;;) { 3909 v = _Event ; 3910 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 3911 } 3912 guarantee ((v == 0) || (v == 1), "invariant") ; 3913 if (v != 0) return ; 3914 3915 // Do this the hard way by blocking ... 3916 // TODO: consider a brief spin here, gated on the success of recent 3917 // spin attempts by this thread. 3918 while (_Event < 0) { 3919 DWORD rv = ::WaitForSingleObject (_ParkHandle, INFINITE) ; 3920 assert (rv == WAIT_OBJECT_0, "WaitForSingleObject failed") ; 3921 } 3922 3923 // Usually we'll find _Event == 0 at this point, but as 3924 // an optional optimization we clear it, just in case can 3925 // multiple unpark() operations drove _Event up to 1. 3926 _Event = 0 ; 3927 OrderAccess::fence() ; 3928 guarantee (_Event >= 0, "invariant") ; 3929 } 3930 3931 void os::PlatformEvent::unpark() { 3932 guarantee (_ParkHandle != NULL, "Invariant") ; 3933 int v ; 3934 for (;;) { 3935 v = _Event ; // Increment _Event if it's < 1. 3936 if (v > 0) { 3937 // If it's already signaled just return. 3938 // The LD of _Event could have reordered or be satisfied 3939 // by a read-aside from this processor's write buffer. 3940 // To avoid problems execute a barrier and then 3941 // ratify the value. A degenerate CAS() would also work. 3942 // Viz., CAS (v+0, &_Event, v) == v). 3943 OrderAccess::fence() ; 3944 if (_Event == v) return ; 3945 continue ; 3946 } 3947 if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ; 3948 } 3949 if (v < 0) { 3950 ::SetEvent (_ParkHandle) ; 3951 } 3952 } 3953 3954 3955 // JSR166 3956 // ------------------------------------------------------- 3957 3958 /* 3959 * The Windows implementation of Park is very straightforward: Basic 3960 * operations on Win32 Events turn out to have the right semantics to 3961 * use them directly. We opportunistically resuse the event inherited 3962 * from Monitor. 3963 */ 3964 3965 3966 void Parker::park(bool isAbsolute, jlong time) { 3967 guarantee (_ParkEvent != NULL, "invariant") ; 3968 // First, demultiplex/decode time arguments 3969 if (time < 0) { // don't wait 3970 return; 3971 } 3972 else if (time == 0) { 3973 time = INFINITE; 3974 } 3975 else if (isAbsolute) { 3976 time -= os::javaTimeMillis(); // convert to relative time 3977 if (time <= 0) // already elapsed 3978 return; 3979 } 3980 else { // relative 3981 time /= 1000000; // Must coarsen from nanos to millis 3982 if (time == 0) // Wait for the minimal time unit if zero 3983 time = 1; 3984 } 3985 3986 JavaThread* thread = (JavaThread*)(Thread::current()); 3987 assert(thread->is_Java_thread(), "Must be JavaThread"); 3988 JavaThread *jt = (JavaThread *)thread; 3989 3990 // Don't wait if interrupted or already triggered 3991 if (Thread::is_interrupted(thread, false) || 3992 WaitForSingleObject(_ParkEvent, 0) == WAIT_OBJECT_0) { 3993 ResetEvent(_ParkEvent); 3994 return; 3995 } 3996 else { 3997 ThreadBlockInVM tbivm(jt); 3998 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 3999 jt->set_suspend_equivalent(); 4000 4001 WaitForSingleObject(_ParkEvent, time); 4002 ResetEvent(_ParkEvent); 4003 4004 // If externally suspended while waiting, re-suspend 4005 if (jt->handle_special_suspend_equivalent_condition()) { 4006 jt->java_suspend_self(); 4007 } 4008 } 4009 } 4010 4011 void Parker::unpark() { 4012 guarantee (_ParkEvent != NULL, "invariant") ; 4013 SetEvent(_ParkEvent); 4014 } 4015 4016 // Run the specified command in a separate process. Return its exit value, 4017 // or -1 on failure (e.g. can't create a new process). 4018 int os::fork_and_exec(char* cmd) { 4019 STARTUPINFO si; 4020 PROCESS_INFORMATION pi; 4021 4022 memset(&si, 0, sizeof(si)); 4023 si.cb = sizeof(si); 4024 memset(&pi, 0, sizeof(pi)); 4025 BOOL rslt = CreateProcess(NULL, // executable name - use command line 4026 cmd, // command line 4027 NULL, // process security attribute 4028 NULL, // thread security attribute 4029 TRUE, // inherits system handles 4030 0, // no creation flags 4031 NULL, // use parent's environment block 4032 NULL, // use parent's starting directory 4033 &si, // (in) startup information 4034 &pi); // (out) process information 4035 4036 if (rslt) { 4037 // Wait until child process exits. 4038 WaitForSingleObject(pi.hProcess, INFINITE); 4039 4040 DWORD exit_code; 4041 GetExitCodeProcess(pi.hProcess, &exit_code); 4042 4043 // Close process and thread handles. 4044 CloseHandle(pi.hProcess); 4045 CloseHandle(pi.hThread); 4046 4047 return (int)exit_code; 4048 } else { 4049 return -1; 4050 } 4051 } 4052 4053 //-------------------------------------------------------------------------------------------------- 4054 // Non-product code 4055 4056 static int mallocDebugIntervalCounter = 0; 4057 static int mallocDebugCounter = 0; 4058 bool os::check_heap(bool force) { 4059 if (++mallocDebugCounter < MallocVerifyStart && !force) return true; 4060 if (++mallocDebugIntervalCounter >= MallocVerifyInterval || force) { 4061 // Note: HeapValidate executes two hardware breakpoints when it finds something 4062 // wrong; at these points, eax contains the address of the offending block (I think). 4063 // To get to the exlicit error message(s) below, just continue twice. 4064 HANDLE heap = GetProcessHeap(); 4065 { HeapLock(heap); 4066 PROCESS_HEAP_ENTRY phe; 4067 phe.lpData = NULL; 4068 while (HeapWalk(heap, &phe) != 0) { 4069 if ((phe.wFlags & PROCESS_HEAP_ENTRY_BUSY) && 4070 !HeapValidate(heap, 0, phe.lpData)) { 4071 tty->print_cr("C heap has been corrupted (time: %d allocations)", mallocDebugCounter); 4072 tty->print_cr("corrupted block near address %#x, length %d", phe.lpData, phe.cbData); 4073 fatal("corrupted C heap"); 4074 } 4075 } 4076 int err = GetLastError(); 4077 if (err != ERROR_NO_MORE_ITEMS && err != ERROR_CALL_NOT_IMPLEMENTED) { 4078 fatal1("heap walk aborted with error %d", err); 4079 } 4080 HeapUnlock(heap); 4081 } 4082 mallocDebugIntervalCounter = 0; 4083 } 4084 return true; 4085 } 4086 4087 4088 #ifndef PRODUCT 4089 bool os::find(address addr) { 4090 // Nothing yet 4091 return false; 4092 } 4093 #endif 4094 4095 LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) { 4096 DWORD exception_code = e->ExceptionRecord->ExceptionCode; 4097 4098 if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) { 4099 JavaThread* thread = (JavaThread*)ThreadLocalStorage::get_thread_slow(); 4100 PEXCEPTION_RECORD exceptionRecord = e->ExceptionRecord; 4101 address addr = (address) exceptionRecord->ExceptionInformation[1]; 4102 4103 if (os::is_memory_serialize_page(thread, addr)) 4104 return EXCEPTION_CONTINUE_EXECUTION; 4105 } 4106 4107 return EXCEPTION_CONTINUE_SEARCH; 4108 } 4109 4110 static int getLastErrorString(char *buf, size_t len) 4111 { 4112 long errval; 4113 4114 if ((errval = GetLastError()) != 0) 4115 { 4116 /* DOS error */ 4117 size_t n = (size_t)FormatMessage( 4118 FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 4119 NULL, 4120 errval, 4121 0, 4122 buf, 4123 (DWORD)len, 4124 NULL); 4125 if (n > 3) { 4126 /* Drop final '.', CR, LF */ 4127 if (buf[n - 1] == '\n') n--; 4128 if (buf[n - 1] == '\r') n--; 4129 if (buf[n - 1] == '.') n--; 4130 buf[n] = '\0'; 4131 } 4132 return (int)n; 4133 } 4134 4135 if (errno != 0) 4136 { 4137 /* C runtime error that has no corresponding DOS error code */ 4138 const char *s = strerror(errno); 4139 size_t n = strlen(s); 4140 if (n >= len) n = len - 1; 4141 strncpy(buf, s, n); 4142 buf[n] = '\0'; 4143 return (int)n; 4144 } 4145 return 0; 4146 }