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