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