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