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