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