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