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