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