src/os/windows/vm/os_windows.cpp
author coleenp
Wed Jan 12 13:59:18 2011 -0800 (2 years ago)
changeset 1999 2c8e1acf0433
parent 1958b69c41ea1764
child 2412a541ca8fa0e3
permissions -rw-r--r--
7009828: Fix for 6938627 breaks visualvm monitoring when -Djava.io.tmpdir is defined
Summary: Change get_temp_directory() back to /tmp and %TEMP% like it always was and where the tools expect it to be.
Reviewed-by: phh, dcubed, kamg, alanb
        1 /*
        2  * Copyright (c) 1997, 2010, 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 #ifdef _WIN64
       26 // Must be at least Windows 2000 or XP to use VectoredExceptions
       27 #define _WIN32_WINNT 0x500
       28 #endif
       29 
       30 // do not include precompiled header file
       31 # include "incls/_os_windows.cpp.incl"
       32 
       33 #ifdef _DEBUG
       34 #include <crtdbg.h>
       35 #endif
       36 
       37 
       38 #include <windows.h>
       39 #include <sys/types.h>
       40 #include <sys/stat.h>
       41 #include <sys/timeb.h>
       42 #include <objidl.h>
       43 #include <shlobj.h>
       44 
       45 #include <malloc.h>
       46 #include <signal.h>
       47 #include <direct.h>
       48 #include <errno.h>
       49 #include <fcntl.h>
       50 #include <io.h>
       51 #include <process.h>              // For _beginthreadex(), _endthreadex()
       52 #include <imagehlp.h>             // For os::dll_address_to_function_name
       53 
       54 /* for enumerating dll libraries */
       55 #include <tlhelp32.h>
       56 #include <vdmdbg.h>
       57 
       58 // for timer info max values which include all bits
       59 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
       60 
       61 // For DLL loading/load error detection
       62 // Values of PE COFF
       63 #define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c
       64 #define IMAGE_FILE_SIGNATURE_LENGTH 4
       65 
       66 static HANDLE main_process;
       67 static HANDLE main_thread;
       68 static int    main_thread_id;
       69 
       70 static FILETIME process_creation_time;
       71 static FILETIME process_exit_time;
       72 static FILETIME process_user_time;
       73 static FILETIME process_kernel_time;
       74 
       75 #ifdef _WIN64
       76 PVOID  topLevelVectoredExceptionHandler = NULL;
       77 #endif
       78 
       79 #ifdef _M_IA64
       80 #define __CPU__ ia64
       81 #elif _M_AMD64
       82 #define __CPU__ amd64
       83 #else
       84 #define __CPU__ i486
       85 #endif
       86 
       87 // save DLL module handle, used by GetModuleFileName
       88 
       89 HINSTANCE vm_lib_handle;
       90 static int getLastErrorString(char *buf, size_t len);
       91 
       92 BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
       93   switch (reason) {
       94     case DLL_PROCESS_ATTACH:
       95       vm_lib_handle = hinst;
       96       if(ForceTimeHighResolution)
       97         timeBeginPeriod(1L);
       98       break;
       99     case DLL_PROCESS_DETACH:
      100       if(ForceTimeHighResolution)
      101         timeEndPeriod(1L);
      102 #ifdef _WIN64
      103       if (topLevelVectoredExceptionHandler != NULL) {
      104         RemoveVectoredExceptionHandler(topLevelVectoredExceptionHandler);
      105         topLevelVectoredExceptionHandler = NULL;
      106       }
      107 #endif
      108       break;
      109     default:
      110       break;
      111   }
      112   return true;
      113 }
      114 
      115 static inline double fileTimeAsDouble(FILETIME* time) {
      116   const double high  = (double) ((unsigned int) ~0);
      117   const double split = 10000000.0;
      118   double result = (time->dwLowDateTime / split) +
      119                    time->dwHighDateTime * (high/split);
      120   return result;
      121 }
      122 
      123 // Implementation of os
      124 
      125 bool os::getenv(const char* name, char* buffer, int len) {
      126  int result = GetEnvironmentVariable(name, buffer, len);
      127  return result > 0 && result < len;
      128 }
      129 
      130 
      131 // No setuid programs under Windows.
      132 bool os::have_special_privileges() {
      133   return false;
      134 }
      135 
      136 
      137 // This method is  a periodic task to check for misbehaving JNI applications
      138 // under CheckJNI, we can add any periodic checks here.
      139 // For Windows at the moment does nothing
      140 void os::run_periodic_checks() {
      141   return;
      142 }
      143 
      144 #ifndef _WIN64
      145 // previous UnhandledExceptionFilter, if there is one
      146 static LPTOP_LEVEL_EXCEPTION_FILTER prev_uef_handler = NULL;
      147 
      148 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo);
      149 #endif
      150 void os::init_system_properties_values() {
      151   /* sysclasspath, java_home, dll_dir */
      152   {
      153       char *home_path;
      154       char *dll_path;
      155       char *pslash;
      156       char *bin = "\\bin";
      157       char home_dir[MAX_PATH];
      158 
      159       if (!getenv("_ALT_JAVA_HOME_DIR", home_dir, MAX_PATH)) {
      160           os::jvm_path(home_dir, sizeof(home_dir));
      161           // Found the full path to jvm[_g].dll.
      162           // Now cut the path to <java_home>/jre if we can.
      163           *(strrchr(home_dir, '\\')) = '\0';  /* get rid of \jvm.dll */
      164           pslash = strrchr(home_dir, '\\');
      165           if (pslash != NULL) {
      166               *pslash = '\0';                 /* get rid of \{client|server} */
      167               pslash = strrchr(home_dir, '\\');
      168               if (pslash != NULL)
      169                   *pslash = '\0';             /* get rid of \bin */
      170           }
      171       }
      172 
      173       home_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + 1);
      174       if (home_path == NULL)
      175           return;
      176       strcpy(home_path, home_dir);
      177       Arguments::set_java_home(home_path);
      178 
      179       dll_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + strlen(bin) + 1);
      180       if (dll_path == NULL)
      181           return;
      182       strcpy(dll_path, home_dir);
      183       strcat(dll_path, bin);
      184       Arguments::set_dll_dir(dll_path);
      185 
      186       if (!set_boot_path('\\', ';'))
      187           return;
      188   }
      189 
      190   /* library_path */
      191   #define EXT_DIR "\\lib\\ext"
      192   #define BIN_DIR "\\bin"
      193   #define PACKAGE_DIR "\\Sun\\Java"
      194   {
      195     /* Win32 library search order (See the documentation for LoadLibrary):
      196      *
      197      * 1. The directory from which application is loaded.
      198      * 2. The current directory
      199      * 3. The system wide Java Extensions directory (Java only)
      200      * 4. System directory (GetSystemDirectory)
      201      * 5. Windows directory (GetWindowsDirectory)
      202      * 6. The PATH environment variable
      203      */
      204 
      205     char *library_path;
      206     char tmp[MAX_PATH];
      207     char *path_str = ::getenv("PATH");
      208 
      209     library_path = NEW_C_HEAP_ARRAY(char, MAX_PATH * 5 + sizeof(PACKAGE_DIR) +
      210         sizeof(BIN_DIR) + (path_str ? strlen(path_str) : 0) + 10);
      211 
      212     library_path[0] = '\0';
      213 
      214     GetModuleFileName(NULL, tmp, sizeof(tmp));
      215     *(strrchr(tmp, '\\')) = '\0';
      216     strcat(library_path, tmp);
      217 
      218     strcat(library_path, ";.");
      219 
      220     GetWindowsDirectory(tmp, sizeof(tmp));
      221     strcat(library_path, ";");
      222     strcat(library_path, tmp);
      223     strcat(library_path, PACKAGE_DIR BIN_DIR);
      224 
      225     GetSystemDirectory(tmp, sizeof(tmp));
      226     strcat(library_path, ";");
      227     strcat(library_path, tmp);
      228 
      229     GetWindowsDirectory(tmp, sizeof(tmp));
      230     strcat(library_path, ";");
      231     strcat(library_path, tmp);
      232 
      233     if (path_str) {
      234         strcat(library_path, ";");
      235         strcat(library_path, path_str);
      236     }
      237 
      238     Arguments::set_library_path(library_path);
      239     FREE_C_HEAP_ARRAY(char, library_path);
      240   }
      241 
      242   /* Default extensions directory */
      243   {
      244     char path[MAX_PATH];
      245     char buf[2 * MAX_PATH + 2 * sizeof(EXT_DIR) + sizeof(PACKAGE_DIR) + 1];
      246     GetWindowsDirectory(path, MAX_PATH);
      247     sprintf(buf, "%s%s;%s%s%s", Arguments::get_java_home(), EXT_DIR,
      248         path, PACKAGE_DIR, EXT_DIR);
      249     Arguments::set_ext_dirs(buf);
      250   }
      251   #undef EXT_DIR
      252   #undef BIN_DIR
      253   #undef PACKAGE_DIR
      254 
      255   /* Default endorsed standards directory. */
      256   {
      257     #define ENDORSED_DIR "\\lib\\endorsed"
      258     size_t len = strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR);
      259     char * buf = NEW_C_HEAP_ARRAY(char, len);
      260     sprintf(buf, "%s%s", Arguments::get_java_home(), ENDORSED_DIR);
      261     Arguments::set_endorsed_dirs(buf);
      262     #undef ENDORSED_DIR
      263   }
      264 
      265 #ifndef _WIN64
      266   // set our UnhandledExceptionFilter and save any previous one
      267   prev_uef_handler = SetUnhandledExceptionFilter(Handle_FLT_Exception);
      268 #endif
      269 
      270   // Done
      271   return;
      272 }
      273 
      274 void os::breakpoint() {
      275   DebugBreak();
      276 }
      277 
      278 // Invoked from the BREAKPOINT Macro
      279 extern "C" void breakpoint() {
      280   os::breakpoint();
      281 }
      282 
      283 // Returns an estimate of the current stack pointer. Result must be guaranteed
      284 // to point into the calling threads stack, and be no lower than the current
      285 // stack pointer.
      286 
      287 address os::current_stack_pointer() {
      288   int dummy;
      289   address sp = (address)&dummy;
      290   return sp;
      291 }
      292 
      293 // os::current_stack_base()
      294 //
      295 //   Returns the base of the stack, which is the stack's
      296 //   starting address.  This function must be called
      297 //   while running on the stack of the thread being queried.
      298 
      299 address os::current_stack_base() {
      300   MEMORY_BASIC_INFORMATION minfo;
      301   address stack_bottom;
      302   size_t stack_size;
      303 
      304   VirtualQuery(&minfo, &minfo, sizeof(minfo));
      305   stack_bottom =  (address)minfo.AllocationBase;
      306   stack_size = minfo.RegionSize;
      307 
      308   // Add up the sizes of all the regions with the same
      309   // AllocationBase.
      310   while( 1 )
      311   {
      312     VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo));
      313     if ( stack_bottom == (address)minfo.AllocationBase )
      314       stack_size += minfo.RegionSize;
      315     else
      316       break;
      317   }
      318 
      319 #ifdef _M_IA64
      320   // IA64 has memory and register stacks
      321   stack_size = stack_size / 2;
      322 #endif
      323   return stack_bottom + stack_size;
      324 }
      325 
      326 size_t os::current_stack_size() {
      327   size_t sz;
      328   MEMORY_BASIC_INFORMATION minfo;
      329   VirtualQuery(&minfo, &minfo, sizeof(minfo));
      330   sz = (size_t)os::current_stack_base() - (size_t)minfo.AllocationBase;
      331   return sz;
      332 }
      333 
      334 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
      335   const struct tm* time_struct_ptr = localtime(clock);
      336   if (time_struct_ptr != NULL) {
      337     *res = *time_struct_ptr;
      338     return res;
      339   }
      340   return NULL;
      341 }
      342 
      343 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo);
      344 
      345 // Thread start routine for all new Java threads
      346 static unsigned __stdcall java_start(Thread* thread) {
      347   // Try to randomize the cache line index of hot stack frames.
      348   // This helps when threads of the same stack traces evict each other's
      349   // cache lines. The threads can be either from the same JVM instance, or
      350   // from different JVM instances. The benefit is especially true for
      351   // processors with hyperthreading technology.
      352   static int counter = 0;
      353   int pid = os::current_process_id();
      354   _alloca(((pid ^ counter++) & 7) * 128);
      355 
      356   OSThread* osthr = thread->osthread();
      357   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
      358 
      359   if (UseNUMA) {
      360     int lgrp_id = os::numa_get_group_id();
      361     if (lgrp_id != -1) {
      362       thread->set_lgrp_id(lgrp_id);
      363     }
      364   }
      365 
      366 
      367   if (UseVectoredExceptions) {
      368     // If we are using vectored exception we don't need to set a SEH
      369     thread->run();
      370   }
      371   else {
      372     // Install a win32 structured exception handler around every thread created
      373     // by VM, so VM can genrate error dump when an exception occurred in non-
      374     // Java thread (e.g. VM thread).
      375     __try {
      376        thread->run();
      377     } __except(topLevelExceptionFilter(
      378                (_EXCEPTION_POINTERS*)_exception_info())) {
      379         // Nothing to do.
      380     }
      381   }
      382 
      383   // One less thread is executing
      384   // When the VMThread gets here, the main thread may have already exited
      385   // which frees the CodeHeap containing the Atomic::add code
      386   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
      387     Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count);
      388   }
      389 
      390   return 0;
      391 }
      392 
      393 static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle, int thread_id) {
      394   // Allocate the OSThread object
      395   OSThread* osthread = new OSThread(NULL, NULL);
      396   if (osthread == NULL) return NULL;
      397 
      398   // Initialize support for Java interrupts
      399   HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
      400   if (interrupt_event == NULL) {
      401     delete osthread;
      402     return NULL;
      403   }
      404   osthread->set_interrupt_event(interrupt_event);
      405 
      406   // Store info on the Win32 thread into the OSThread
      407   osthread->set_thread_handle(thread_handle);
      408   osthread->set_thread_id(thread_id);
      409 
      410   if (UseNUMA) {
      411     int lgrp_id = os::numa_get_group_id();
      412     if (lgrp_id != -1) {
      413       thread->set_lgrp_id(lgrp_id);
      414     }
      415   }
      416 
      417   // Initial thread state is INITIALIZED, not SUSPENDED
      418   osthread->set_state(INITIALIZED);
      419 
      420   return osthread;
      421 }
      422 
      423 
      424 bool os::create_attached_thread(JavaThread* thread) {
      425 #ifdef ASSERT
      426   thread->verify_not_published();
      427 #endif
      428   HANDLE thread_h;
      429   if (!DuplicateHandle(main_process, GetCurrentThread(), GetCurrentProcess(),
      430                        &thread_h, THREAD_ALL_ACCESS, false, 0)) {
      431     fatal("DuplicateHandle failed\n");
      432   }
      433   OSThread* osthread = create_os_thread(thread, thread_h,
      434                                         (int)current_thread_id());
      435   if (osthread == NULL) {
      436      return false;
      437   }
      438 
      439   // Initial thread state is RUNNABLE
      440   osthread->set_state(RUNNABLE);
      441 
      442   thread->set_osthread(osthread);
      443   return true;
      444 }
      445 
      446 bool os::create_main_thread(JavaThread* thread) {
      447 #ifdef ASSERT
      448   thread->verify_not_published();
      449 #endif
      450   if (_starting_thread == NULL) {
      451     _starting_thread = create_os_thread(thread, main_thread, main_thread_id);
      452      if (_starting_thread == NULL) {
      453         return false;
      454      }
      455   }
      456 
      457   // The primordial thread is runnable from the start)
      458   _starting_thread->set_state(RUNNABLE);
      459 
      460   thread->set_osthread(_starting_thread);
      461   return true;
      462 }
      463 
      464 // Allocate and initialize a new OSThread
      465 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
      466   unsigned thread_id;
      467 
      468   // Allocate the OSThread object
      469   OSThread* osthread = new OSThread(NULL, NULL);
      470   if (osthread == NULL) {
      471     return false;
      472   }
      473 
      474   // Initialize support for Java interrupts
      475   HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
      476   if (interrupt_event == NULL) {
      477     delete osthread;
      478     return NULL;
      479   }
      480   osthread->set_interrupt_event(interrupt_event);
      481   osthread->set_interrupted(false);
      482 
      483   thread->set_osthread(osthread);
      484 
      485   if (stack_size == 0) {
      486     switch (thr_type) {
      487     case os::java_thread:
      488       // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
      489       if (JavaThread::stack_size_at_create() > 0)
      490         stack_size = JavaThread::stack_size_at_create();
      491       break;
      492     case os::compiler_thread:
      493       if (CompilerThreadStackSize > 0) {
      494         stack_size = (size_t)(CompilerThreadStackSize * K);
      495         break;
      496       } // else fall through:
      497         // use VMThreadStackSize if CompilerThreadStackSize is not defined
      498     case os::vm_thread:
      499     case os::pgc_thread:
      500     case os::cgc_thread:
      501     case os::watcher_thread:
      502       if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
      503       break;
      504     }
      505   }
      506 
      507   // Create the Win32 thread
      508   //
      509   // Contrary to what MSDN document says, "stack_size" in _beginthreadex()
      510   // does not specify stack size. Instead, it specifies the size of
      511   // initially committed space. The stack size is determined by
      512   // PE header in the executable. If the committed "stack_size" is larger
      513   // than default value in the PE header, the stack is rounded up to the
      514   // nearest multiple of 1MB. For example if the launcher has default
      515   // stack size of 320k, specifying any size less than 320k does not
      516   // affect the actual stack size at all, it only affects the initial
      517   // commitment. On the other hand, specifying 'stack_size' larger than
      518   // default value may cause significant increase in memory usage, because
      519   // not only the stack space will be rounded up to MB, but also the
      520   // entire space is committed upfront.
      521   //
      522   // Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION'
      523   // for CreateThread() that can treat 'stack_size' as stack size. However we
      524   // are not supposed to call CreateThread() directly according to MSDN
      525   // document because JVM uses C runtime library. The good news is that the
      526   // flag appears to work with _beginthredex() as well.
      527 
      528 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
      529 #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
      530 #endif
      531 
      532   HANDLE thread_handle =
      533     (HANDLE)_beginthreadex(NULL,
      534                            (unsigned)stack_size,
      535                            (unsigned (__stdcall *)(void*)) java_start,
      536                            thread,
      537                            CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
      538                            &thread_id);
      539   if (thread_handle == NULL) {
      540     // perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again
      541     // without the flag.
      542     thread_handle =
      543     (HANDLE)_beginthreadex(NULL,
      544                            (unsigned)stack_size,
      545                            (unsigned (__stdcall *)(void*)) java_start,
      546                            thread,
      547                            CREATE_SUSPENDED,
      548                            &thread_id);
      549   }
      550   if (thread_handle == NULL) {
      551     // Need to clean up stuff we've allocated so far
      552     CloseHandle(osthread->interrupt_event());
      553     thread->set_osthread(NULL);
      554     delete osthread;
      555     return NULL;
      556   }
      557 
      558   Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count);
      559 
      560   // Store info on the Win32 thread into the OSThread
      561   osthread->set_thread_handle(thread_handle);
      562   osthread->set_thread_id(thread_id);
      563 
      564   // Initial thread state is INITIALIZED, not SUSPENDED
      565   osthread->set_state(INITIALIZED);
      566 
      567   // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
      568   return true;
      569 }
      570 
      571 
      572 // Free Win32 resources related to the OSThread
      573 void os::free_thread(OSThread* osthread) {
      574   assert(osthread != NULL, "osthread not set");
      575   CloseHandle(osthread->thread_handle());
      576   CloseHandle(osthread->interrupt_event());
      577   delete osthread;
      578 }
      579 
      580 
      581 static int    has_performance_count = 0;
      582 static jlong first_filetime;
      583 static jlong initial_performance_count;
      584 static jlong performance_frequency;
      585 
      586 
      587 jlong as_long(LARGE_INTEGER x) {
      588   jlong result = 0; // initialization to avoid warning
      589   set_high(&result, x.HighPart);
      590   set_low(&result,  x.LowPart);
      591   return result;
      592 }
      593 
      594 
      595 jlong os::elapsed_counter() {
      596   LARGE_INTEGER count;
      597   if (has_performance_count) {
      598     QueryPerformanceCounter(&count);
      599     return as_long(count) - initial_performance_count;
      600   } else {
      601     FILETIME wt;
      602     GetSystemTimeAsFileTime(&wt);
      603     return (jlong_from(wt.dwHighDateTime, wt.dwLowDateTime) - first_filetime);
      604   }
      605 }
      606 
      607 
      608 jlong os::elapsed_frequency() {
      609   if (has_performance_count) {
      610     return performance_frequency;
      611   } else {
      612    // the FILETIME time is the number of 100-nanosecond intervals since January 1,1601.
      613    return 10000000;
      614   }
      615 }
      616 
      617 
      618 julong os::available_memory() {
      619   return win32::available_memory();
      620 }
      621 
      622 julong os::win32::available_memory() {
      623   // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
      624   // value if total memory is larger than 4GB
      625   MEMORYSTATUSEX ms;
      626   ms.dwLength = sizeof(ms);
      627   GlobalMemoryStatusEx(&ms);
      628 
      629   return (julong)ms.ullAvailPhys;
      630 }
      631 
      632 julong os::physical_memory() {
      633   return win32::physical_memory();
      634 }
      635 
      636 julong os::allocatable_physical_memory(julong size) {
      637 #ifdef _LP64
      638   return size;
      639 #else
      640   // Limit to 1400m because of the 2gb address space wall
      641   return MIN2(size, (julong)1400*M);
      642 #endif
      643 }
      644 
      645 // VC6 lacks DWORD_PTR
      646 #if _MSC_VER < 1300
      647 typedef UINT_PTR DWORD_PTR;
      648 #endif
      649 
      650 int os::active_processor_count() {
      651   DWORD_PTR lpProcessAffinityMask = 0;
      652   DWORD_PTR lpSystemAffinityMask = 0;
      653   int proc_count = processor_count();
      654   if (proc_count <= sizeof(UINT_PTR) * BitsPerByte &&
      655       GetProcessAffinityMask(GetCurrentProcess(), &lpProcessAffinityMask, &lpSystemAffinityMask)) {
      656     // Nof active processors is number of bits in process affinity mask
      657     int bitcount = 0;
      658     while (lpProcessAffinityMask != 0) {
      659       lpProcessAffinityMask = lpProcessAffinityMask & (lpProcessAffinityMask-1);
      660       bitcount++;
      661     }
      662     return bitcount;
      663   } else {
      664     return proc_count;
      665   }
      666 }
      667 
      668 bool os::distribute_processes(uint length, uint* distribution) {
      669   // Not yet implemented.
      670   return false;
      671 }
      672 
      673 bool os::bind_to_processor(uint processor_id) {
      674   // Not yet implemented.
      675   return false;
      676 }
      677 
      678 static void initialize_performance_counter() {
      679   LARGE_INTEGER count;
      680   if (QueryPerformanceFrequency(&count)) {
      681     has_performance_count = 1;
      682     performance_frequency = as_long(count);
      683     QueryPerformanceCounter(&count);
      684     initial_performance_count = as_long(count);
      685   } else {
      686     has_performance_count = 0;
      687     FILETIME wt;
      688     GetSystemTimeAsFileTime(&wt);
      689     first_filetime = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
      690   }
      691 }
      692 
      693 
      694 double os::elapsedTime() {
      695   return (double) elapsed_counter() / (double) elapsed_frequency();
      696 }
      697 
      698 
      699 // Windows format:
      700 //   The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
      701 // Java format:
      702 //   Java standards require the number of milliseconds since 1/1/1970
      703 
      704 // Constant offset - calculated using offset()
      705 static jlong  _offset   = 116444736000000000;
      706 // Fake time counter for reproducible results when debugging
      707 static jlong  fake_time = 0;
      708 
      709 #ifdef ASSERT
      710 // Just to be safe, recalculate the offset in debug mode
      711 static jlong _calculated_offset = 0;
      712 static int   _has_calculated_offset = 0;
      713 
      714 jlong offset() {
      715   if (_has_calculated_offset) return _calculated_offset;
      716   SYSTEMTIME java_origin;
      717   java_origin.wYear          = 1970;
      718   java_origin.wMonth         = 1;
      719   java_origin.wDayOfWeek     = 0; // ignored
      720   java_origin.wDay           = 1;
      721   java_origin.wHour          = 0;
      722   java_origin.wMinute        = 0;
      723   java_origin.wSecond        = 0;
      724   java_origin.wMilliseconds  = 0;
      725   FILETIME jot;
      726   if (!SystemTimeToFileTime(&java_origin, &jot)) {
      727     fatal(err_msg("Error = %d\nWindows error", GetLastError()));
      728   }
      729   _calculated_offset = jlong_from(jot.dwHighDateTime, jot.dwLowDateTime);
      730   _has_calculated_offset = 1;
      731   assert(_calculated_offset == _offset, "Calculated and constant time offsets must be equal");
      732   return _calculated_offset;
      733 }
      734 #else
      735 jlong offset() {
      736   return _offset;
      737 }
      738 #endif
      739 
      740 jlong windows_to_java_time(FILETIME wt) {
      741   jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
      742   return (a - offset()) / 10000;
      743 }
      744 
      745 FILETIME java_to_windows_time(jlong l) {
      746   jlong a = (l * 10000) + offset();
      747   FILETIME result;
      748   result.dwHighDateTime = high(a);
      749   result.dwLowDateTime  = low(a);
      750   return result;
      751 }
      752 
      753 // For now, we say that Windows does not support vtime.  I have no idea
      754 // whether it can actually be made to (DLD, 9/13/05).
      755 
      756 bool os::supports_vtime() { return false; }
      757 bool os::enable_vtime() { return false; }
      758 bool os::vtime_enabled() { return false; }
      759 double os::elapsedVTime() {
      760   // better than nothing, but not much
      761   return elapsedTime();
      762 }
      763 
      764 jlong os::javaTimeMillis() {
      765   if (UseFakeTimers) {
      766     return fake_time++;
      767   } else {
      768     FILETIME wt;
      769     GetSystemTimeAsFileTime(&wt);
      770     return windows_to_java_time(wt);
      771   }
      772 }
      773 
      774 #define NANOS_PER_SEC         CONST64(1000000000)
      775 #define NANOS_PER_MILLISEC    1000000
      776 jlong os::javaTimeNanos() {
      777   if (!has_performance_count) {
      778     return javaTimeMillis() * NANOS_PER_MILLISEC; // the best we can do.
      779   } else {
      780     LARGE_INTEGER current_count;
      781     QueryPerformanceCounter(&current_count);
      782     double current = as_long(current_count);
      783     double freq = performance_frequency;
      784     jlong time = (jlong)((current/freq) * NANOS_PER_SEC);
      785     return time;
      786   }
      787 }
      788 
      789 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
      790   if (!has_performance_count) {
      791     // javaTimeMillis() doesn't have much percision,
      792     // but it is not going to wrap -- so all 64 bits
      793     info_ptr->max_value = ALL_64_BITS;
      794 
      795     // this is a wall clock timer, so may skip
      796     info_ptr->may_skip_backward = true;
      797     info_ptr->may_skip_forward = true;
      798   } else {
      799     jlong freq = performance_frequency;
      800     if (freq < NANOS_PER_SEC) {
      801       // the performance counter is 64 bits and we will
      802       // be multiplying it -- so no wrap in 64 bits
      803       info_ptr->max_value = ALL_64_BITS;
      804     } else if (freq > NANOS_PER_SEC) {
      805       // use the max value the counter can reach to
      806       // determine the max value which could be returned
      807       julong max_counter = (julong)ALL_64_BITS;
      808       info_ptr->max_value = (jlong)(max_counter / (freq / NANOS_PER_SEC));
      809     } else {
      810       // the performance counter is 64 bits and we will
      811       // be using it directly -- so no wrap in 64 bits
      812       info_ptr->max_value = ALL_64_BITS;
      813     }
      814 
      815     // using a counter, so no skipping
      816     info_ptr->may_skip_backward = false;
      817     info_ptr->may_skip_forward = false;
      818   }
      819   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
      820 }
      821 
      822 char* os::local_time_string(char *buf, size_t buflen) {
      823   SYSTEMTIME st;
      824   GetLocalTime(&st);
      825   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
      826                st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
      827   return buf;
      828 }
      829 
      830 bool os::getTimesSecs(double* process_real_time,
      831                      double* process_user_time,
      832                      double* process_system_time) {
      833   HANDLE h_process = GetCurrentProcess();
      834   FILETIME create_time, exit_time, kernel_time, user_time;
      835   BOOL result = GetProcessTimes(h_process,
      836                                &create_time,
      837                                &exit_time,
      838                                &kernel_time,
      839                                &user_time);
      840   if (result != 0) {
      841     FILETIME wt;
      842     GetSystemTimeAsFileTime(&wt);
      843     jlong rtc_millis = windows_to_java_time(wt);
      844     jlong user_millis = windows_to_java_time(user_time);
      845     jlong system_millis = windows_to_java_time(kernel_time);
      846     *process_real_time = ((double) rtc_millis) / ((double) MILLIUNITS);
      847     *process_user_time = ((double) user_millis) / ((double) MILLIUNITS);
      848     *process_system_time = ((double) system_millis) / ((double) MILLIUNITS);
      849     return true;
      850   } else {
      851     return false;
      852   }
      853 }
      854 
      855 void os::shutdown() {
      856 
      857   // allow PerfMemory to attempt cleanup of any persistent resources
      858   perfMemory_exit();
      859 
      860   // flush buffered output, finish log files
      861   ostream_abort();
      862 
      863   // Check for abort hook
      864   abort_hook_t abort_hook = Arguments::abort_hook();
      865   if (abort_hook != NULL) {
      866     abort_hook();
      867   }
      868 }
      869 
      870 void os::abort(bool dump_core)
      871 {
      872   os::shutdown();
      873   // no core dump on Windows
      874   ::exit(1);
      875 }
      876 
      877 // Die immediately, no exit hook, no abort hook, no cleanup.
      878 void os::die() {
      879   _exit(-1);
      880 }
      881 
      882 // Directory routines copied from src/win32/native/java/io/dirent_md.c
      883 //  * dirent_md.c       1.15 00/02/02
      884 //
      885 // The declarations for DIR and struct dirent are in jvm_win32.h.
      886 
      887 /* Caller must have already run dirname through JVM_NativePath, which removes
      888    duplicate slashes and converts all instances of '/' into '\\'. */
      889 
      890 DIR *
      891 os::opendir(const char *dirname)
      892 {
      893     assert(dirname != NULL, "just checking");   // hotspot change
      894     DIR *dirp = (DIR *)malloc(sizeof(DIR));
      895     DWORD fattr;                                // hotspot change
      896     char alt_dirname[4] = { 0, 0, 0, 0 };
      897 
      898     if (dirp == 0) {
      899         errno = ENOMEM;
      900         return 0;
      901     }
      902 
      903     /*
      904      * Win32 accepts "\" in its POSIX stat(), but refuses to treat it
      905      * as a directory in FindFirstFile().  We detect this case here and
      906      * prepend the current drive name.
      907      */
      908     if (dirname[1] == '\0' && dirname[0] == '\\') {
      909         alt_dirname[0] = _getdrive() + 'A' - 1;
      910         alt_dirname[1] = ':';
      911         alt_dirname[2] = '\\';
      912         alt_dirname[3] = '\0';
      913         dirname = alt_dirname;
      914     }
      915 
      916     dirp->path = (char *)malloc(strlen(dirname) + 5);
      917     if (dirp->path == 0) {
      918         free(dirp);
      919         errno = ENOMEM;
      920         return 0;
      921     }
      922     strcpy(dirp->path, dirname);
      923 
      924     fattr = GetFileAttributes(dirp->path);
      925     if (fattr == 0xffffffff) {
      926         free(dirp->path);
      927         free(dirp);
      928         errno = ENOENT;
      929         return 0;
      930     } else if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
      931         free(dirp->path);
      932         free(dirp);
      933         errno = ENOTDIR;
      934         return 0;
      935     }
      936 
      937     /* Append "*.*", or possibly "\\*.*", to path */
      938     if (dirp->path[1] == ':'
      939         && (dirp->path[2] == '\0'
      940             || (dirp->path[2] == '\\' && dirp->path[3] == '\0'))) {
      941         /* No '\\' needed for cases like "Z:" or "Z:\" */
      942         strcat(dirp->path, "*.*");
      943     } else {
      944         strcat(dirp->path, "\\*.*");
      945     }
      946 
      947     dirp->handle = FindFirstFile(dirp->path, &dirp->find_data);
      948     if (dirp->handle == INVALID_HANDLE_VALUE) {
      949         if (GetLastError() != ERROR_FILE_NOT_FOUND) {
      950             free(dirp->path);
      951             free(dirp);
      952             errno = EACCES;
      953             return 0;
      954         }
      955     }
      956     return dirp;
      957 }
      958 
      959 /* parameter dbuf unused on Windows */
      960 
      961 struct dirent *
      962 os::readdir(DIR *dirp, dirent *dbuf)
      963 {
      964     assert(dirp != NULL, "just checking");      // hotspot change
      965     if (dirp->handle == INVALID_HANDLE_VALUE) {
      966         return 0;
      967     }
      968 
      969     strcpy(dirp->dirent.d_name, dirp->find_data.cFileName);
      970 
      971     if (!FindNextFile(dirp->handle, &dirp->find_data)) {
      972         if (GetLastError() == ERROR_INVALID_HANDLE) {
      973             errno = EBADF;
      974             return 0;
      975         }
      976         FindClose(dirp->handle);
      977         dirp->handle = INVALID_HANDLE_VALUE;
      978     }
      979 
      980     return &dirp->dirent;
      981 }
      982 
      983 int
      984 os::closedir(DIR *dirp)
      985 {
      986     assert(dirp != NULL, "just checking");      // hotspot change
      987     if (dirp->handle != INVALID_HANDLE_VALUE) {
      988         if (!FindClose(dirp->handle)) {
      989             errno = EBADF;
      990             return -1;
      991         }
      992         dirp->handle = INVALID_HANDLE_VALUE;
      993     }
      994     free(dirp->path);
      995     free(dirp);
      996     return 0;
      997 }
      998 
      999 const char* os::dll_file_extension() { return ".dll"; }
     1000 
     1001 // This must be hard coded because it's the system's temporary
     1002 // directory not the java application's temp directory, ala java.io.tmpdir.
     1003 const char* os::get_temp_directory() {
     1004   static char path_buf[MAX_PATH];
     1005   if (GetTempPath(MAX_PATH, path_buf)>0)
     1006     return path_buf;
     1007   else{
     1008     path_buf[0]='\0';
     1009     return path_buf;
     1010   }
     1011 }
     1012 
     1013 static bool file_exists(const char* filename) {
     1014   if (filename == NULL || strlen(filename) == 0) {
     1015     return false;
     1016   }
     1017   return GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES;
     1018 }
     1019 
     1020 void os::dll_build_name(char *buffer, size_t buflen,
     1021                         const char* pname, const char* fname) {
     1022   // Copied from libhpi
     1023   const size_t pnamelen = pname ? strlen(pname) : 0;
     1024   const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0;
     1025 
     1026   // Quietly truncates on buffer overflow. Should be an error.
     1027   if (pnamelen + strlen(fname) + 10 > buflen) {
     1028     *buffer = '\0';
     1029     return;
     1030   }
     1031 
     1032   if (pnamelen == 0) {
     1033     jio_snprintf(buffer, buflen, "%s.dll", fname);
     1034   } else if (c == ':' || c == '\\') {
     1035     jio_snprintf(buffer, buflen, "%s%s.dll", pname, fname);
     1036   } else if (strchr(pname, *os::path_separator()) != NULL) {
     1037     int n;
     1038     char** pelements = split_path(pname, &n);
     1039     for (int i = 0 ; i < n ; i++) {
     1040       char* path = pelements[i];
     1041       // Really shouldn't be NULL, but check can't hurt
     1042       size_t plen = (path == NULL) ? 0 : strlen(path);
     1043       if (plen == 0) {
     1044         continue; // skip the empty path values
     1045       }
     1046       const char lastchar = path[plen - 1];
     1047       if (lastchar == ':' || lastchar == '\\') {
     1048         jio_snprintf(buffer, buflen, "%s%s.dll", path, fname);
     1049       } else {
     1050         jio_snprintf(buffer, buflen, "%s\\%s.dll", path, fname);
     1051       }
     1052       if (file_exists(buffer)) {
     1053         break;
     1054       }
     1055     }
     1056     // release the storage
     1057     for (int i = 0 ; i < n ; i++) {
     1058       if (pelements[i] != NULL) {
     1059         FREE_C_HEAP_ARRAY(char, pelements[i]);
     1060       }
     1061     }
     1062     if (pelements != NULL) {
     1063       FREE_C_HEAP_ARRAY(char*, pelements);
     1064     }
     1065   } else {
     1066     jio_snprintf(buffer, buflen, "%s\\%s.dll", pname, fname);
     1067   }
     1068 }
     1069 
     1070 // Needs to be in os specific directory because windows requires another
     1071 // header file <direct.h>
     1072 const char* os::get_current_directory(char *buf, int buflen) {
     1073   return _getcwd(buf, buflen);
     1074 }
     1075 
     1076 //-----------------------------------------------------------
     1077 // Helper functions for fatal error handler
     1078 
     1079 // The following library functions are resolved dynamically at runtime:
     1080 
     1081 // PSAPI functions, for Windows NT, 2000, XP
     1082 
     1083 // psapi.h doesn't come with Visual Studio 6; it can be downloaded as Platform
     1084 // SDK from Microsoft.  Here are the definitions copied from psapi.h
     1085 typedef struct _MODULEINFO {
     1086     LPVOID lpBaseOfDll;
     1087     DWORD SizeOfImage;
     1088     LPVOID EntryPoint;
     1089 } MODULEINFO, *LPMODULEINFO;
     1090 
     1091 static BOOL  (WINAPI *_EnumProcessModules)  ( HANDLE, HMODULE *, DWORD, LPDWORD );
     1092 static DWORD (WINAPI *_GetModuleFileNameEx) ( HANDLE, HMODULE, LPTSTR, DWORD );
     1093 static BOOL  (WINAPI *_GetModuleInformation)( HANDLE, HMODULE, LPMODULEINFO, DWORD );
     1094 
     1095 // ToolHelp Functions, for Windows 95, 98 and ME
     1096 
     1097 static HANDLE(WINAPI *_CreateToolhelp32Snapshot)(DWORD,DWORD) ;
     1098 static BOOL  (WINAPI *_Module32First)           (HANDLE,LPMODULEENTRY32) ;
     1099 static BOOL  (WINAPI *_Module32Next)            (HANDLE,LPMODULEENTRY32) ;
     1100 
     1101 bool _has_psapi;
     1102 bool _psapi_init = false;
     1103 bool _has_toolhelp;
     1104 
     1105 static bool _init_psapi() {
     1106   HINSTANCE psapi = LoadLibrary( "PSAPI.DLL" ) ;
     1107   if( psapi == NULL ) return false ;
     1108 
     1109   _EnumProcessModules = CAST_TO_FN_PTR(
     1110       BOOL(WINAPI *)(HANDLE, HMODULE *, DWORD, LPDWORD),
     1111       GetProcAddress(psapi, "EnumProcessModules")) ;
     1112   _GetModuleFileNameEx = CAST_TO_FN_PTR(
     1113       DWORD (WINAPI *)(HANDLE, HMODULE, LPTSTR, DWORD),
     1114       GetProcAddress(psapi, "GetModuleFileNameExA"));
     1115   _GetModuleInformation = CAST_TO_FN_PTR(
     1116       BOOL (WINAPI *)(HANDLE, HMODULE, LPMODULEINFO, DWORD),
     1117       GetProcAddress(psapi, "GetModuleInformation"));
     1118 
     1119   _has_psapi = (_EnumProcessModules && _GetModuleFileNameEx && _GetModuleInformation);
     1120   _psapi_init = true;
     1121   return _has_psapi;
     1122 }
     1123 
     1124 static bool _init_toolhelp() {
     1125   HINSTANCE kernel32 = LoadLibrary("Kernel32.DLL") ;
     1126   if (kernel32 == NULL) return false ;
     1127 
     1128   _CreateToolhelp32Snapshot = CAST_TO_FN_PTR(
     1129       HANDLE(WINAPI *)(DWORD,DWORD),
     1130       GetProcAddress(kernel32, "CreateToolhelp32Snapshot"));
     1131   _Module32First = CAST_TO_FN_PTR(
     1132       BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32),
     1133       GetProcAddress(kernel32, "Module32First" ));
     1134   _Module32Next = CAST_TO_FN_PTR(
     1135       BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32),
     1136       GetProcAddress(kernel32, "Module32Next" ));
     1137 
     1138   _has_toolhelp = (_CreateToolhelp32Snapshot && _Module32First && _Module32Next);
     1139   return _has_toolhelp;
     1140 }
     1141 
     1142 #ifdef _WIN64
     1143 // Helper routine which returns true if address in
     1144 // within the NTDLL address space.
     1145 //
     1146 static bool _addr_in_ntdll( address addr )
     1147 {
     1148   HMODULE hmod;
     1149   MODULEINFO minfo;
     1150 
     1151   hmod = GetModuleHandle("NTDLL.DLL");
     1152   if ( hmod == NULL ) return false;
     1153   if ( !_GetModuleInformation( GetCurrentProcess(), hmod,
     1154                                &minfo, sizeof(MODULEINFO)) )
     1155     return false;
     1156 
     1157   if ( (addr >= minfo.lpBaseOfDll) &&
     1158        (addr < (address)((uintptr_t)minfo.lpBaseOfDll + (uintptr_t)minfo.SizeOfImage)))
     1159     return true;
     1160   else
     1161     return false;
     1162 }
     1163 #endif
     1164 
     1165 
     1166 // Enumerate all modules for a given process ID
     1167 //
     1168 // Notice that Windows 95/98/Me and Windows NT/2000/XP have
     1169 // different API for doing this. We use PSAPI.DLL on NT based
     1170 // Windows and ToolHelp on 95/98/Me.
     1171 
     1172 // Callback function that is called by enumerate_modules() on
     1173 // every DLL module.
     1174 // Input parameters:
     1175 //    int       pid,
     1176 //    char*     module_file_name,
     1177 //    address   module_base_addr,
     1178 //    unsigned  module_size,
     1179 //    void*     param
     1180 typedef int (*EnumModulesCallbackFunc)(int, char *, address, unsigned, void *);
     1181 
     1182 // enumerate_modules for Windows NT, using PSAPI
     1183 static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void * param)
     1184 {
     1185   HANDLE   hProcess ;
     1186 
     1187 # define MAX_NUM_MODULES 128
     1188   HMODULE     modules[MAX_NUM_MODULES];
     1189   static char filename[ MAX_PATH ];
     1190   int         result = 0;
     1191 
     1192   if (!_has_psapi && (_psapi_init || !_init_psapi())) return 0;
     1193 
     1194   hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
     1195                          FALSE, pid ) ;
     1196   if (hProcess == NULL) return 0;
     1197 
     1198   DWORD size_needed;
     1199   if (!_EnumProcessModules(hProcess, modules,
     1200                            sizeof(modules), &size_needed)) {
     1201       CloseHandle( hProcess );
     1202       return 0;
     1203   }
     1204 
     1205   // number of modules that are currently loaded
     1206   int num_modules = size_needed / sizeof(HMODULE);
     1207 
     1208   for (int i = 0; i < MIN2(num_modules, MAX_NUM_MODULES); i++) {
     1209     // Get Full pathname:
     1210     if(!_GetModuleFileNameEx(hProcess, modules[i],
     1211                              filename, sizeof(filename))) {
     1212         filename[0] = '\0';
     1213     }
     1214 
     1215     MODULEINFO modinfo;
     1216     if (!_GetModuleInformation(hProcess, modules[i],
     1217                                &modinfo, sizeof(modinfo))) {
     1218         modinfo.lpBaseOfDll = NULL;
     1219         modinfo.SizeOfImage = 0;
     1220     }
     1221 
     1222     // Invoke callback function
     1223     result = func(pid, filename, (address)modinfo.lpBaseOfDll,
     1224                   modinfo.SizeOfImage, param);
     1225     if (result) break;
     1226   }
     1227 
     1228   CloseHandle( hProcess ) ;
     1229   return result;
     1230 }
     1231 
     1232 
     1233 // enumerate_modules for Windows 95/98/ME, using TOOLHELP
     1234 static int _enumerate_modules_windows( int pid, EnumModulesCallbackFunc func, void *param)
     1235 {
     1236   HANDLE                hSnapShot ;
     1237   static MODULEENTRY32  modentry ;
     1238   int                   result = 0;
     1239 
     1240   if (!_has_toolhelp) return 0;
     1241 
     1242   // Get a handle to a Toolhelp snapshot of the system
     1243   hSnapShot = _CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid ) ;
     1244   if( hSnapShot == INVALID_HANDLE_VALUE ) {
     1245       return FALSE ;
     1246   }
     1247 
     1248   // iterate through all modules
     1249   modentry.dwSize = sizeof(MODULEENTRY32) ;
     1250   bool not_done = _Module32First( hSnapShot, &modentry ) != 0;
     1251 
     1252   while( not_done ) {
     1253     // invoke the callback
     1254     result=func(pid, modentry.szExePath, (address)modentry.modBaseAddr,
     1255                 modentry.modBaseSize, param);
     1256     if (result) break;
     1257 
     1258     modentry.dwSize = sizeof(MODULEENTRY32) ;
     1259     not_done = _Module32Next( hSnapShot, &modentry ) != 0;
     1260   }
     1261 
     1262   CloseHandle(hSnapShot);
     1263   return result;
     1264 }
     1265 
     1266 int enumerate_modules( int pid, EnumModulesCallbackFunc func, void * param )
     1267 {
     1268   // Get current process ID if caller doesn't provide it.
     1269   if (!pid) pid = os::current_process_id();
     1270 
     1271   if (os::win32::is_nt()) return _enumerate_modules_winnt  (pid, func, param);
     1272   else                    return _enumerate_modules_windows(pid, func, param);
     1273 }
     1274 
     1275 struct _modinfo {
     1276    address addr;
     1277    char*   full_path;   // point to a char buffer
     1278    int     buflen;      // size of the buffer
     1279    address base_addr;
     1280 };
     1281 
     1282 static int _locate_module_by_addr(int pid, char * mod_fname, address base_addr,
     1283                                   unsigned size, void * param) {
     1284    struct _modinfo *pmod = (struct _modinfo *)param;
     1285    if (!pmod) return -1;
     1286 
     1287    if (base_addr     <= pmod->addr &&
     1288        base_addr+size > pmod->addr) {
     1289      // if a buffer is provided, copy path name to the buffer
     1290      if (pmod->full_path) {
     1291        jio_snprintf(pmod->full_path, pmod->buflen, "%s", mod_fname);
     1292      }
     1293      pmod->base_addr = base_addr;
     1294      return 1;
     1295    }
     1296    return 0;
     1297 }
     1298 
     1299 bool os::dll_address_to_library_name(address addr, char* buf,
     1300                                      int buflen, int* offset) {
     1301 // NOTE: the reason we don't use SymGetModuleInfo() is it doesn't always
     1302 //       return the full path to the DLL file, sometimes it returns path
     1303 //       to the corresponding PDB file (debug info); sometimes it only
     1304 //       returns partial path, which makes life painful.
     1305 
     1306    struct _modinfo mi;
     1307    mi.addr      = addr;
     1308    mi.full_path = buf;
     1309    mi.buflen    = buflen;
     1310    int pid = os::current_process_id();
     1311    if (enumerate_modules(pid, _locate_module_by_addr, (void *)&mi)) {
     1312       // buf already contains path name
     1313       if (offset) *offset = addr - mi.base_addr;
     1314       return true;
     1315    } else {
     1316       if (buf) buf[0] = '\0';
     1317       if (offset) *offset = -1;
     1318       return false;
     1319    }
     1320 }
     1321 
     1322 bool os::dll_address_to_function_name(address addr, char *buf,
     1323                                       int buflen, int *offset) {
     1324   // Unimplemented on Windows - in order to use SymGetSymFromAddr(),
     1325   // we need to initialize imagehlp/dbghelp, then load symbol table
     1326   // for every module. That's too much work to do after a fatal error.
     1327   // For an example on how to implement this function, see 1.4.2.
     1328   if (offset)  *offset  = -1;
     1329   if (buf) buf[0] = '\0';
     1330   return false;
     1331 }
     1332 
     1333 void* os::dll_lookup(void* handle, const char* name) {
     1334   return GetProcAddress((HMODULE)handle, name);
     1335 }
     1336 
     1337 // save the start and end address of jvm.dll into param[0] and param[1]
     1338 static int _locate_jvm_dll(int pid, char* mod_fname, address base_addr,
     1339                     unsigned size, void * param) {
     1340    if (!param) return -1;
     1341 
     1342    if (base_addr     <= (address)_locate_jvm_dll &&
     1343        base_addr+size > (address)_locate_jvm_dll) {
     1344          ((address*)param)[0] = base_addr;
     1345          ((address*)param)[1] = base_addr + size;
     1346          return 1;
     1347    }
     1348    return 0;
     1349 }
     1350 
     1351 address vm_lib_location[2];    // start and end address of jvm.dll
     1352 
     1353 // check if addr is inside jvm.dll
     1354 bool os::address_is_in_vm(address addr) {
     1355   if (!vm_lib_location[0] || !vm_lib_location[1]) {
     1356     int pid = os::current_process_id();
     1357     if (!enumerate_modules(pid, _locate_jvm_dll, (void *)vm_lib_location)) {
     1358       assert(false, "Can't find jvm module.");
     1359       return false;
     1360     }
     1361   }
     1362 
     1363   return (vm_lib_location[0] <= addr) && (addr < vm_lib_location[1]);
     1364 }
     1365 
     1366 // print module info; param is outputStream*
     1367 static int _print_module(int pid, char* fname, address base,
     1368                          unsigned size, void* param) {
     1369    if (!param) return -1;
     1370 
     1371    outputStream* st = (outputStream*)param;
     1372 
     1373    address end_addr = base + size;
     1374    st->print(PTR_FORMAT " - " PTR_FORMAT " \t%s\n", base, end_addr, fname);
     1375    return 0;
     1376 }
     1377 
     1378 // Loads .dll/.so and
     1379 // in case of error it checks if .dll/.so was built for the
     1380 // same architecture as Hotspot is running on
     1381 void * os::dll_load(const char *name, char *ebuf, int ebuflen)
     1382 {
     1383   void * result = LoadLibrary(name);
     1384   if (result != NULL)
     1385   {
     1386     return result;
     1387   }
     1388 
     1389   long errcode = GetLastError();
     1390   if (errcode == ERROR_MOD_NOT_FOUND) {
     1391     strncpy(ebuf, "Can't find dependent libraries", ebuflen-1);
     1392     ebuf[ebuflen-1]='\0';
     1393     return NULL;
     1394   }
     1395 
     1396   // Parsing dll below
     1397   // If we can read dll-info and find that dll was built
     1398   // for an architecture other than Hotspot is running in
     1399   // - then print to buffer "DLL was built for a different architecture"
     1400   // else call getLastErrorString to obtain system error message
     1401 
     1402   // Read system error message into ebuf
     1403   // It may or may not be overwritten below (in the for loop and just above)
     1404   getLastErrorString(ebuf, (size_t) ebuflen);
     1405   ebuf[ebuflen-1]='\0';
     1406   int file_descriptor=::open(name, O_RDONLY | O_BINARY, 0);
     1407   if (file_descriptor<0)
     1408   {
     1409     return NULL;
     1410   }
     1411 
     1412   uint32_t signature_offset;
     1413   uint16_t lib_arch=0;
     1414   bool failed_to_get_lib_arch=
     1415   (
     1416     //Go to position 3c in the dll
     1417     (os::seek_to_file_offset(file_descriptor,IMAGE_FILE_PTR_TO_SIGNATURE)<0)
     1418     ||
     1419     // Read loacation of signature
     1420     (sizeof(signature_offset)!=
     1421       (os::read(file_descriptor, (void*)&signature_offset,sizeof(signature_offset))))
     1422     ||
     1423     //Go to COFF File Header in dll
     1424     //that is located after"signature" (4 bytes long)
     1425     (os::seek_to_file_offset(file_descriptor,
     1426       signature_offset+IMAGE_FILE_SIGNATURE_LENGTH)<0)
     1427     ||
     1428     //Read field that contains code of architecture
     1429     // that dll was build for
     1430     (sizeof(lib_arch)!=
     1431       (os::read(file_descriptor, (void*)&lib_arch,sizeof(lib_arch))))
     1432   );
     1433 
     1434   ::close(file_descriptor);
     1435   if (failed_to_get_lib_arch)
     1436   {
     1437     // file i/o error - report getLastErrorString(...) msg
     1438     return NULL;
     1439   }
     1440 
     1441   typedef struct
     1442   {
     1443     uint16_t arch_code;
     1444     char* arch_name;
     1445   } arch_t;
     1446 
     1447   static const arch_t arch_array[]={
     1448     {IMAGE_FILE_MACHINE_I386,      (char*)"IA 32"},
     1449     {IMAGE_FILE_MACHINE_AMD64,     (char*)"AMD 64"},
     1450     {IMAGE_FILE_MACHINE_IA64,      (char*)"IA 64"}
     1451   };
     1452   #if   (defined _M_IA64)
     1453     static const uint16_t running_arch=IMAGE_FILE_MACHINE_IA64;
     1454   #elif (defined _M_AMD64)
     1455     static const uint16_t running_arch=IMAGE_FILE_MACHINE_AMD64;
     1456   #elif (defined _M_IX86)
     1457     static const uint16_t running_arch=IMAGE_FILE_MACHINE_I386;
     1458   #else
     1459     #error Method os::dll_load requires that one of following \
     1460            is defined :_M_IA64,_M_AMD64 or _M_IX86
     1461   #endif
     1462 
     1463 
     1464   // Obtain a string for printf operation
     1465   // lib_arch_str shall contain string what platform this .dll was built for
     1466   // running_arch_str shall string contain what platform Hotspot was built for
     1467   char *running_arch_str=NULL,*lib_arch_str=NULL;
     1468   for (unsigned int i=0;i<ARRAY_SIZE(arch_array);i++)
     1469   {
     1470     if (lib_arch==arch_array[i].arch_code)
     1471       lib_arch_str=arch_array[i].arch_name;
     1472     if (running_arch==arch_array[i].arch_code)
     1473       running_arch_str=arch_array[i].arch_name;
     1474   }
     1475 
     1476   assert(running_arch_str,
     1477     "Didn't find runing architecture code in arch_array");
     1478 
     1479   // If the architure is right
     1480   // but some other error took place - report getLastErrorString(...) msg
     1481   if (lib_arch == running_arch)
     1482   {
     1483     return NULL;
     1484   }
     1485 
     1486   if (lib_arch_str!=NULL)
     1487   {
     1488     ::_snprintf(ebuf, ebuflen-1,
     1489       "Can't load %s-bit .dll on a %s-bit platform",
     1490       lib_arch_str,running_arch_str);
     1491   }
     1492   else
     1493   {
     1494     // don't know what architecture this dll was build for
     1495     ::_snprintf(ebuf, ebuflen-1,
     1496       "Can't load this .dll (machine code=0x%x) on a %s-bit platform",
     1497       lib_arch,running_arch_str);
     1498   }
     1499 
     1500   return NULL;
     1501 }
     1502 
     1503 
     1504 void os::print_dll_info(outputStream *st) {
     1505    int pid = os::current_process_id();
     1506    st->print_cr("Dynamic libraries:");
     1507    enumerate_modules(pid, _print_module, (void *)st);
     1508 }
     1509 
     1510 // function pointer to Windows API "GetNativeSystemInfo".
     1511 typedef void (WINAPI *GetNativeSystemInfo_func_type)(LPSYSTEM_INFO);
     1512 static GetNativeSystemInfo_func_type _GetNativeSystemInfo;
     1513 
     1514 void os::print_os_info(outputStream* st) {
     1515   st->print("OS:");
     1516 
     1517   OSVERSIONINFOEX osvi;
     1518   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
     1519   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
     1520 
     1521   if (!GetVersionEx((OSVERSIONINFO *)&osvi)) {
     1522     st->print_cr("N/A");
     1523     return;
     1524   }
     1525 
     1526   int os_vers = osvi.dwMajorVersion * 1000 + osvi.dwMinorVersion;
     1527   if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
     1528     switch (os_vers) {
     1529     case 3051: st->print(" Windows NT 3.51"); break;
     1530     case 4000: st->print(" Windows NT 4.0"); break;
     1531     case 5000: st->print(" Windows 2000"); break;
     1532     case 5001: st->print(" Windows XP"); break;
     1533     case 5002:
     1534     case 6000:
     1535     case 6001: {
     1536       // Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could
     1537       // find out whether we are running on 64 bit processor or not.
     1538       SYSTEM_INFO si;
     1539       ZeroMemory(&si, sizeof(SYSTEM_INFO));
     1540       // Check to see if _GetNativeSystemInfo has been initialized.
     1541       if (_GetNativeSystemInfo == NULL) {
     1542         HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32.dll"));
     1543         _GetNativeSystemInfo =
     1544             CAST_TO_FN_PTR(GetNativeSystemInfo_func_type,
     1545                            GetProcAddress(hKernel32,
     1546                                           "GetNativeSystemInfo"));
     1547         if (_GetNativeSystemInfo == NULL)
     1548           GetSystemInfo(&si);
     1549       } else {
     1550         _GetNativeSystemInfo(&si);
     1551       }
     1552       if (os_vers == 5002) {
     1553         if (osvi.wProductType == VER_NT_WORKSTATION &&
     1554             si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
     1555           st->print(" Windows XP x64 Edition");
     1556         else
     1557             st->print(" Windows Server 2003 family");
     1558       } else if (os_vers == 6000) {
     1559         if (osvi.wProductType == VER_NT_WORKSTATION)
     1560             st->print(" Windows Vista");
     1561         else
     1562             st->print(" Windows Server 2008");
     1563         if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
     1564             st->print(" , 64 bit");
     1565       } else if (os_vers == 6001) {
     1566         if (osvi.wProductType == VER_NT_WORKSTATION) {
     1567             st->print(" Windows 7");
     1568         } else {
     1569             st->print(" Windows Server 2008 R2");
     1570         }
     1571         if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
     1572             st->print(" , 64 bit");
     1573       } else { // future os
     1574         // Unrecognized windows, print out its major and minor versions
     1575         st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
     1576         if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
     1577             st->print(" , 64 bit");
     1578       }
     1579       break;
     1580     }
     1581     default: // future windows, print out its major and minor versions
     1582       st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
     1583     }
     1584   } else {
     1585     switch (os_vers) {
     1586     case 4000: st->print(" Windows 95"); break;
     1587     case 4010: st->print(" Windows 98"); break;
     1588     case 4090: st->print(" Windows Me"); break;
     1589     default: // future windows, print out its major and minor versions
     1590       st->print(" Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
     1591     }
     1592   }
     1593   st->print(" Build %d", osvi.dwBuildNumber);
     1594   st->print(" %s", osvi.szCSDVersion);           // service pack
     1595   st->cr();
     1596 }
     1597 
     1598 void os::print_memory_info(outputStream* st) {
     1599   st->print("Memory:");
     1600   st->print(" %dk page", os::vm_page_size()>>10);
     1601 
     1602   // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
     1603   // value if total memory is larger than 4GB
     1604   MEMORYSTATUSEX ms;
     1605   ms.dwLength = sizeof(ms);
     1606   GlobalMemoryStatusEx(&ms);
     1607 
     1608   st->print(", physical %uk", os::physical_memory() >> 10);
     1609   st->print("(%uk free)", os::available_memory() >> 10);
     1610 
     1611   st->print(", swap %uk", ms.ullTotalPageFile >> 10);
     1612   st->print("(%uk free)", ms.ullAvailPageFile >> 10);
     1613   st->cr();
     1614 }
     1615 
     1616 void os::print_siginfo(outputStream *st, void *siginfo) {
     1617   EXCEPTION_RECORD* er = (EXCEPTION_RECORD*)siginfo;
     1618   st->print("siginfo:");
     1619   st->print(" ExceptionCode=0x%x", er->ExceptionCode);
     1620 
     1621   if (er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
     1622       er->NumberParameters >= 2) {
     1623       switch (er->ExceptionInformation[0]) {
     1624       case 0: st->print(", reading address"); break;
     1625       case 1: st->print(", writing address"); break;
     1626       default: st->print(", ExceptionInformation=" INTPTR_FORMAT,
     1627                             er->ExceptionInformation[0]);
     1628       }
     1629       st->print(" " INTPTR_FORMAT, er->ExceptionInformation[1]);
     1630   } else if (er->ExceptionCode == EXCEPTION_IN_PAGE_ERROR &&
     1631              er->NumberParameters >= 2 && UseSharedSpaces) {
     1632     FileMapInfo* mapinfo = FileMapInfo::current_info();
     1633     if (mapinfo->is_in_shared_space((void*)er->ExceptionInformation[1])) {
     1634       st->print("\n\nError accessing class data sharing archive."       \
     1635                 " Mapped file inaccessible during execution, "          \
     1636                 " possible disk/network problem.");
     1637     }
     1638   } else {
     1639     int num = er->NumberParameters;
     1640     if (num > 0) {
     1641       st->print(", ExceptionInformation=");
     1642       for (int i = 0; i < num; i++) {
     1643         st->print(INTPTR_FORMAT " ", er->ExceptionInformation[i]);
     1644       }
     1645     }
     1646   }
     1647   st->cr();
     1648 }
     1649 
     1650 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
     1651   // do nothing
     1652 }
     1653 
     1654 static char saved_jvm_path[MAX_PATH] = {0};
     1655 
     1656 // Find the full path to the current module, jvm.dll or jvm_g.dll
     1657 void os::jvm_path(char *buf, jint buflen) {
     1658   // Error checking.
     1659   if (buflen < MAX_PATH) {
     1660     assert(false, "must use a large-enough buffer");
     1661     buf[0] = '\0';
     1662     return;
     1663   }
     1664   // Lazy resolve the path to current module.
     1665   if (saved_jvm_path[0] != 0) {
     1666     strcpy(buf, saved_jvm_path);
     1667     return;
     1668   }
     1669 
     1670   GetModuleFileName(vm_lib_handle, buf, buflen);
     1671   strcpy(saved_jvm_path, buf);
     1672 }
     1673 
     1674 
     1675 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
     1676 #ifndef _WIN64
     1677   st->print("_");
     1678 #endif
     1679 }
     1680 
     1681 
     1682 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
     1683 #ifndef _WIN64
     1684   st->print("@%d", args_size  * sizeof(int));
     1685 #endif
     1686 }
     1687 
     1688 // sun.misc.Signal
     1689 // NOTE that this is a workaround for an apparent kernel bug where if
     1690 // a signal handler for SIGBREAK is installed then that signal handler
     1691 // takes priority over the console control handler for CTRL_CLOSE_EVENT.
     1692 // See bug 4416763.
     1693 static void (*sigbreakHandler)(int) = NULL;
     1694 
     1695 static void UserHandler(int sig, void *siginfo, void *context) {
     1696   os::signal_notify(sig);
     1697   // We need to reinstate the signal handler each time...
     1698   os::signal(sig, (void*)UserHandler);
     1699 }
     1700 
     1701 void* os::user_handler() {
     1702   return (void*) UserHandler;
     1703 }
     1704 
     1705 void* os::signal(int signal_number, void* handler) {
     1706   if ((signal_number == SIGBREAK) && (!ReduceSignalUsage)) {
     1707     void (*oldHandler)(int) = sigbreakHandler;
     1708     sigbreakHandler = (void (*)(int)) handler;
     1709     return (void*) oldHandler;
     1710   } else {
     1711     return (void*)::signal(signal_number, (void (*)(int))handler);
     1712   }
     1713 }
     1714 
     1715 void os::signal_raise(int signal_number) {
     1716   raise(signal_number);
     1717 }
     1718 
     1719 // The Win32 C runtime library maps all console control events other than ^C
     1720 // into SIGBREAK, which makes it impossible to distinguish ^BREAK from close,
     1721 // logoff, and shutdown events.  We therefore install our own console handler
     1722 // that raises SIGTERM for the latter cases.
     1723 //
     1724 static BOOL WINAPI consoleHandler(DWORD event) {
     1725   switch(event) {
     1726     case CTRL_C_EVENT:
     1727       if (is_error_reported()) {
     1728         // Ctrl-C is pressed during error reporting, likely because the error
     1729         // handler fails to abort. Let VM die immediately.
     1730         os::die();
     1731       }
     1732 
     1733       os::signal_raise(SIGINT);
     1734       return TRUE;
     1735       break;
     1736     case CTRL_BREAK_EVENT:
     1737       if (sigbreakHandler != NULL) {
     1738         (*sigbreakHandler)(SIGBREAK);
     1739       }
     1740       return TRUE;
     1741       break;
     1742     case CTRL_CLOSE_EVENT:
     1743     case CTRL_LOGOFF_EVENT:
     1744     case CTRL_SHUTDOWN_EVENT:
     1745       os::signal_raise(SIGTERM);
     1746       return TRUE;
     1747       break;
     1748     default:
     1749       break;
     1750   }
     1751   return FALSE;
     1752 }
     1753 
     1754 /*
     1755  * The following code is moved from os.cpp for making this
     1756  * code platform specific, which it is by its very nature.
     1757  */
     1758 
     1759 // Return maximum OS signal used + 1 for internal use only
     1760 // Used as exit signal for signal_thread
     1761 int os::sigexitnum_pd(){
     1762   return NSIG;
     1763 }
     1764 
     1765 // a counter for each possible signal value, including signal_thread exit signal
     1766 static volatile jint pending_signals[NSIG+1] = { 0 };
     1767 static HANDLE sig_sem;
     1768 
     1769 void os::signal_init_pd() {
     1770   // Initialize signal structures
     1771   memset((void*)pending_signals, 0, sizeof(pending_signals));
     1772 
     1773   sig_sem = ::CreateSemaphore(NULL, 0, NSIG+1, NULL);
     1774 
     1775   // Programs embedding the VM do not want it to attempt to receive
     1776   // events like CTRL_LOGOFF_EVENT, which are used to implement the
     1777   // shutdown hooks mechanism introduced in 1.3.  For example, when
     1778   // the VM is run as part of a Windows NT service (i.e., a servlet
     1779   // engine in a web server), the correct behavior is for any console
     1780   // control handler to return FALSE, not TRUE, because the OS's
     1781   // "final" handler for such events allows the process to continue if
     1782   // it is a service (while terminating it if it is not a service).
     1783   // To make this behavior uniform and the mechanism simpler, we
     1784   // completely disable the VM's usage of these console events if -Xrs
     1785   // (=ReduceSignalUsage) is specified.  This means, for example, that
     1786   // the CTRL-BREAK thread dump mechanism is also disabled in this
     1787   // case.  See bugs 4323062, 4345157, and related bugs.
     1788 
     1789   if (!ReduceSignalUsage) {
     1790     // Add a CTRL-C handler
     1791     SetConsoleCtrlHandler(consoleHandler, TRUE);
     1792   }
     1793 }
     1794 
     1795 void os::signal_notify(int signal_number) {
     1796   BOOL ret;
     1797 
     1798   Atomic::inc(&pending_signals[signal_number]);
     1799   ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
     1800   assert(ret != 0, "ReleaseSemaphore() failed");
     1801 }
     1802 
     1803 static int check_pending_signals(bool wait_for_signal) {
     1804   DWORD ret;
     1805   while (true) {
     1806     for (int i = 0; i < NSIG + 1; i++) {
     1807       jint n = pending_signals[i];
     1808       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
     1809         return i;
     1810       }
     1811     }
     1812     if (!wait_for_signal) {
     1813       return -1;
     1814     }
     1815 
     1816     JavaThread *thread = JavaThread::current();
     1817 
     1818     ThreadBlockInVM tbivm(thread);
     1819 
     1820     bool threadIsSuspended;
     1821     do {
     1822       thread->set_suspend_equivalent();
     1823       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
     1824       ret = ::WaitForSingleObject(sig_sem, INFINITE);
     1825       assert(ret == WAIT_OBJECT_0, "WaitForSingleObject() failed");
     1826 
     1827       // were we externally suspended while we were waiting?
     1828       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
     1829       if (threadIsSuspended) {
     1830         //
     1831         // The semaphore has been incremented, but while we were waiting
     1832         // another thread suspended us. We don't want to continue running
     1833         // while suspended because that would surprise the thread that
     1834         // suspended us.
     1835         //
     1836         ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
     1837         assert(ret != 0, "ReleaseSemaphore() failed");
     1838 
     1839         thread->java_suspend_self();
     1840       }
     1841     } while (threadIsSuspended);
     1842   }
     1843 }
     1844 
     1845 int os::signal_lookup() {
     1846   return check_pending_signals(false);
     1847 }
     1848 
     1849 int os::signal_wait() {
     1850   return check_pending_signals(true);
     1851 }
     1852 
     1853 // Implicit OS exception handling
     1854 
     1855 LONG Handle_Exception(struct _EXCEPTION_POINTERS* exceptionInfo, address handler) {
     1856   JavaThread* thread = JavaThread::current();
     1857   // Save pc in thread
     1858 #ifdef _M_IA64
     1859   thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->StIIP);
     1860   // Set pc to handler
     1861   exceptionInfo->ContextRecord->StIIP = (DWORD64)handler;
     1862 #elif _M_AMD64
     1863   thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Rip);
     1864   // Set pc to handler
     1865   exceptionInfo->ContextRecord->Rip = (DWORD64)handler;
     1866 #else
     1867   thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Eip);
     1868   // Set pc to handler
     1869   exceptionInfo->ContextRecord->Eip = (LONG)handler;
     1870 #endif
     1871 
     1872   // Continue the execution
     1873   return EXCEPTION_CONTINUE_EXECUTION;
     1874 }
     1875 
     1876 
     1877 // Used for PostMortemDump
     1878 extern "C" void safepoints();
     1879 extern "C" void find(int x);
     1880 extern "C" void events();
     1881 
     1882 // According to Windows API documentation, an illegal instruction sequence should generate
     1883 // the 0xC000001C exception code. However, real world experience shows that occasionnaly
     1884 // the execution of an illegal instruction can generate the exception code 0xC000001E. This
     1885 // seems to be an undocumented feature of Win NT 4.0 (and probably other Windows systems).
     1886 
     1887 #define EXCEPTION_ILLEGAL_INSTRUCTION_2 0xC000001E
     1888 
     1889 // From "Execution Protection in the Windows Operating System" draft 0.35
     1890 // Once a system header becomes available, the "real" define should be
     1891 // included or copied here.
     1892 #define EXCEPTION_INFO_EXEC_VIOLATION 0x08
     1893 
     1894 #define def_excpt(val) #val, val
     1895 
     1896 struct siglabel {
     1897   char *name;
     1898   int   number;
     1899 };
     1900 
     1901 struct siglabel exceptlabels[] = {
     1902     def_excpt(EXCEPTION_ACCESS_VIOLATION),
     1903     def_excpt(EXCEPTION_DATATYPE_MISALIGNMENT),
     1904     def_excpt(EXCEPTION_BREAKPOINT),
     1905     def_excpt(EXCEPTION_SINGLE_STEP),
     1906     def_excpt(EXCEPTION_ARRAY_BOUNDS_EXCEEDED),
     1907     def_excpt(EXCEPTION_FLT_DENORMAL_OPERAND),
     1908     def_excpt(EXCEPTION_FLT_DIVIDE_BY_ZERO),
     1909     def_excpt(EXCEPTION_FLT_INEXACT_RESULT),
     1910     def_excpt(EXCEPTION_FLT_INVALID_OPERATION),
     1911     def_excpt(EXCEPTION_FLT_OVERFLOW),
     1912     def_excpt(EXCEPTION_FLT_STACK_CHECK),
     1913     def_excpt(EXCEPTION_FLT_UNDERFLOW),
     1914     def_excpt(EXCEPTION_INT_DIVIDE_BY_ZERO),
     1915     def_excpt(EXCEPTION_INT_OVERFLOW),
     1916     def_excpt(EXCEPTION_PRIV_INSTRUCTION),
     1917     def_excpt(EXCEPTION_IN_PAGE_ERROR),
     1918     def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION),
     1919     def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION_2),
     1920     def_excpt(EXCEPTION_NONCONTINUABLE_EXCEPTION),
     1921     def_excpt(EXCEPTION_STACK_OVERFLOW),
     1922     def_excpt(EXCEPTION_INVALID_DISPOSITION),
     1923     def_excpt(EXCEPTION_GUARD_PAGE),
     1924     def_excpt(EXCEPTION_INVALID_HANDLE),
     1925     NULL, 0
     1926 };
     1927 
     1928 const char* os::exception_name(int exception_code, char *buf, size_t size) {
     1929   for (int i = 0; exceptlabels[i].name != NULL; i++) {
     1930     if (exceptlabels[i].number == exception_code) {
     1931        jio_snprintf(buf, size, "%s", exceptlabels[i].name);
     1932        return buf;
     1933     }
     1934   }
     1935 
     1936   return NULL;
     1937 }
     1938 
     1939 //-----------------------------------------------------------------------------
     1940 LONG Handle_IDiv_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
     1941   // handle exception caused by idiv; should only happen for -MinInt/-1
     1942   // (division by zero is handled explicitly)
     1943 #ifdef _M_IA64
     1944   assert(0, "Fix Handle_IDiv_Exception");
     1945 #elif _M_AMD64
     1946   PCONTEXT ctx = exceptionInfo->ContextRecord;
     1947   address pc = (address)ctx->Rip;
     1948   NOT_PRODUCT(Events::log("idiv overflow exception at " INTPTR_FORMAT , pc));
     1949   assert(pc[0] == 0xF7, "not an idiv opcode");
     1950   assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
     1951   assert(ctx->Rax == min_jint, "unexpected idiv exception");
     1952   // set correct result values and continue after idiv instruction
     1953   ctx->Rip = (DWORD)pc + 2;        // idiv reg, reg  is 2 bytes
     1954   ctx->Rax = (DWORD)min_jint;      // result
     1955   ctx->Rdx = (DWORD)0;             // remainder
     1956   // Continue the execution
     1957 #else
     1958   PCONTEXT ctx = exceptionInfo->ContextRecord;
     1959   address pc = (address)ctx->Eip;
     1960   NOT_PRODUCT(Events::log("idiv overflow exception at " INTPTR_FORMAT , pc));
     1961   assert(pc[0] == 0xF7, "not an idiv opcode");
     1962   assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
     1963   assert(ctx->Eax == min_jint, "unexpected idiv exception");
     1964   // set correct result values and continue after idiv instruction
     1965   ctx->Eip = (DWORD)pc + 2;        // idiv reg, reg  is 2 bytes
     1966   ctx->Eax = (DWORD)min_jint;      // result
     1967   ctx->Edx = (DWORD)0;             // remainder
     1968   // Continue the execution
     1969 #endif
     1970   return EXCEPTION_CONTINUE_EXECUTION;
     1971 }
     1972 
     1973 #ifndef  _WIN64
     1974 //-----------------------------------------------------------------------------
     1975 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
     1976   // handle exception caused by native method modifying control word
     1977   PCONTEXT ctx = exceptionInfo->ContextRecord;
     1978   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
     1979 
     1980   switch (exception_code) {
     1981     case EXCEPTION_FLT_DENORMAL_OPERAND:
     1982     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
     1983     case EXCEPTION_FLT_INEXACT_RESULT:
     1984     case EXCEPTION_FLT_INVALID_OPERATION:
     1985     case EXCEPTION_FLT_OVERFLOW:
     1986     case EXCEPTION_FLT_STACK_CHECK:
     1987     case EXCEPTION_FLT_UNDERFLOW:
     1988       jint fp_control_word = (* (jint*) StubRoutines::addr_fpu_cntrl_wrd_std());
     1989       if (fp_control_word != ctx->FloatSave.ControlWord) {
     1990         // Restore FPCW and mask out FLT exceptions
     1991         ctx->FloatSave.ControlWord = fp_control_word | 0xffffffc0;
     1992         // Mask out pending FLT exceptions
     1993         ctx->FloatSave.StatusWord &=  0xffffff00;
     1994         return EXCEPTION_CONTINUE_EXECUTION;
     1995       }
     1996   }
     1997 
     1998   if (prev_uef_handler != NULL) {
     1999     // We didn't handle this exception so pass it to the previous
     2000     // UnhandledExceptionFilter.
     2001     return (prev_uef_handler)(exceptionInfo);
     2002   }
     2003 
     2004   return EXCEPTION_CONTINUE_SEARCH;
     2005 }
     2006 #else //_WIN64
     2007 /*
     2008   On Windows, the mxcsr control bits are non-volatile across calls
     2009   See also CR 6192333
     2010   If EXCEPTION_FLT_* happened after some native method modified
     2011   mxcsr - it is not a jvm fault.
     2012   However should we decide to restore of mxcsr after a faulty
     2013   native method we can uncomment following code
     2014       jint MxCsr = INITIAL_MXCSR;
     2015         // we can't use StubRoutines::addr_mxcsr_std()
     2016         // because in Win64 mxcsr is not saved there
     2017       if (MxCsr != ctx->MxCsr) {
     2018         ctx->MxCsr = MxCsr;
     2019         return EXCEPTION_CONTINUE_EXECUTION;
     2020       }
     2021 
     2022 */
     2023 #endif //_WIN64
     2024 
     2025 
     2026 // Fatal error reporting is single threaded so we can make this a
     2027 // static and preallocated.  If it's more than MAX_PATH silently ignore
     2028 // it.
     2029 static char saved_error_file[MAX_PATH] = {0};
     2030 
     2031 void os::set_error_file(const char *logfile) {
     2032   if (strlen(logfile) <= MAX_PATH) {
     2033     strncpy(saved_error_file, logfile, MAX_PATH);
     2034   }
     2035 }
     2036 
     2037 static inline void report_error(Thread* t, DWORD exception_code,
     2038                                 address addr, void* siginfo, void* context) {
     2039   VMError err(t, exception_code, addr, siginfo, context);
     2040   err.report_and_die();
     2041 
     2042   // If UseOsErrorReporting, this will return here and save the error file
     2043   // somewhere where we can find it in the minidump.
     2044 }
     2045 
     2046 //-----------------------------------------------------------------------------
     2047 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
     2048   if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH;
     2049   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
     2050 #ifdef _M_IA64
     2051   address pc = (address) exceptionInfo->ContextRecord->StIIP;
     2052 #elif _M_AMD64
     2053   address pc = (address) exceptionInfo->ContextRecord->Rip;
     2054 #else
     2055   address pc = (address) exceptionInfo->ContextRecord->Eip;
     2056 #endif
     2057   Thread* t = ThreadLocalStorage::get_thread_slow();          // slow & steady
     2058 
     2059 #ifndef _WIN64
     2060   // Execution protection violation - win32 running on AMD64 only
     2061   // Handled first to avoid misdiagnosis as a "normal" access violation;
     2062   // This is safe to do because we have a new/unique ExceptionInformation
     2063   // code for this condition.
     2064   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
     2065     PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
     2066     int exception_subcode = (int) exceptionRecord->ExceptionInformation[0];
     2067     address addr = (address) exceptionRecord->ExceptionInformation[1];
     2068 
     2069     if (exception_subcode == EXCEPTION_INFO_EXEC_VIOLATION) {
     2070       int page_size = os::vm_page_size();
     2071 
     2072       // Make sure the pc and the faulting address are sane.
     2073       //
     2074       // If an instruction spans a page boundary, and the page containing
     2075       // the beginning of the instruction is executable but the following
     2076       // page is not, the pc and the faulting address might be slightly
     2077       // different - we still want to unguard the 2nd page in this case.
     2078       //
     2079       // 15 bytes seems to be a (very) safe value for max instruction size.
     2080       bool pc_is_near_addr =
     2081         (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15);
     2082       bool instr_spans_page_boundary =
     2083         (align_size_down((intptr_t) pc ^ (intptr_t) addr,
     2084                          (intptr_t) page_size) > 0);
     2085 
     2086       if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) {
     2087         static volatile address last_addr =
     2088           (address) os::non_memory_address_word();
     2089 
     2090         // In conservative mode, don't unguard unless the address is in the VM
     2091         if (UnguardOnExecutionViolation > 0 && addr != last_addr &&
     2092             (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) {
     2093 
     2094           // Set memory to RWX and retry
     2095           address page_start =
     2096             (address) align_size_down((intptr_t) addr, (intptr_t) page_size);
     2097           bool res = os::protect_memory((char*) page_start, page_size,
     2098                                         os::MEM_PROT_RWX);
     2099 
     2100           if (PrintMiscellaneous && Verbose) {
     2101             char buf[256];
     2102             jio_snprintf(buf, sizeof(buf), "Execution protection violation "
     2103                          "at " INTPTR_FORMAT
     2104                          ", unguarding " INTPTR_FORMAT ": %s", addr,
     2105                          page_start, (res ? "success" : strerror(errno)));
     2106             tty->print_raw_cr(buf);
     2107           }
     2108 
     2109           // Set last_addr so if we fault again at the same address, we don't
     2110           // end up in an endless loop.
     2111           //
     2112           // There are two potential complications here.  Two threads trapping
     2113           // at the same address at the same time could cause one of the
     2114           // threads to think it already unguarded, and abort the VM.  Likely
     2115           // very rare.
     2116           //
     2117           // The other race involves two threads alternately trapping at
     2118           // different addresses and failing to unguard the page, resulting in
     2119           // an endless loop.  This condition is probably even more unlikely
     2120           // than the first.
     2121           //
     2122           // Although both cases could be avoided by using locks or thread
     2123           // local last_addr, these solutions are unnecessary complication:
     2124           // this handler is a best-effort safety net, not a complete solution.
     2125           // It is disabled by default and should only be used as a workaround
     2126           // in case we missed any no-execute-unsafe VM code.
     2127 
     2128           last_addr = addr;
     2129 
     2130           return EXCEPTION_CONTINUE_EXECUTION;
     2131         }
     2132       }
     2133 
     2134       // Last unguard failed or not unguarding
     2135       tty->print_raw_cr("Execution protection violation");
     2136       report_error(t, exception_code, addr, exceptionInfo->ExceptionRecord,
     2137                    exceptionInfo->ContextRecord);
     2138       return EXCEPTION_CONTINUE_SEARCH;
     2139     }
     2140   }
     2141 #endif // _WIN64
     2142 
     2143   // Check to see if we caught the safepoint code in the
     2144   // process of write protecting the memory serialization page.
     2145   // It write enables the page immediately after protecting it
     2146   // so just return.
     2147   if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) {
     2148     JavaThread* thread = (JavaThread*) t;
     2149     PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
     2150     address addr = (address) exceptionRecord->ExceptionInformation[1];
     2151     if ( os::is_memory_serialize_page(thread, addr) ) {
     2152       // Block current thread until the memory serialize page permission restored.
     2153       os::block_on_serialize_page_trap();
     2154       return EXCEPTION_CONTINUE_EXECUTION;
     2155     }
     2156   }
     2157 
     2158 
     2159   if (t != NULL && t->is_Java_thread()) {
     2160     JavaThread* thread = (JavaThread*) t;
     2161     bool in_java = thread->thread_state() == _thread_in_Java;
     2162 
     2163     // Handle potential stack overflows up front.
     2164     if (exception_code == EXCEPTION_STACK_OVERFLOW) {
     2165       if (os::uses_stack_guard_pages()) {
     2166 #ifdef _M_IA64
     2167         //
     2168         // If it's a legal stack address continue, Windows will map it in.
     2169         //
     2170         PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
     2171         address addr = (address) exceptionRecord->ExceptionInformation[1];
     2172         if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() )
     2173           return EXCEPTION_CONTINUE_EXECUTION;
     2174 
     2175         // The register save area is the same size as the memory stack
     2176         // and starts at the page just above the start of the memory stack.
     2177         // If we get a fault in this area, we've run out of register
     2178         // stack.  If we are in java, try throwing a stack overflow exception.
     2179         if (addr > thread->stack_base() &&
     2180                       addr <= (thread->stack_base()+thread->stack_size()) ) {
     2181           char buf[256];
     2182           jio_snprintf(buf, sizeof(buf),
     2183                        "Register stack overflow, addr:%p, stack_base:%p\n",
     2184                        addr, thread->stack_base() );
     2185           tty->print_raw_cr(buf);
     2186           // If not in java code, return and hope for the best.
     2187           return in_java ? Handle_Exception(exceptionInfo,
     2188             SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW))
     2189             :  EXCEPTION_CONTINUE_EXECUTION;
     2190         }
     2191 #endif
     2192         if (thread->stack_yellow_zone_enabled()) {
     2193           // Yellow zone violation.  The o/s has unprotected the first yellow
     2194           // zone page for us.  Note:  must call disable_stack_yellow_zone to
     2195           // update the enabled status, even if the zone contains only one page.
     2196           thread->disable_stack_yellow_zone();
     2197           // If not in java code, return and hope for the best.
     2198           return in_java ? Handle_Exception(exceptionInfo,
     2199             SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW))
     2200             :  EXCEPTION_CONTINUE_EXECUTION;
     2201         } else {
     2202           // Fatal red zone violation.
     2203           thread->disable_stack_red_zone();
     2204           tty->print_raw_cr("An unrecoverable stack overflow has occurred.");
     2205           report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
     2206                        exceptionInfo->ContextRecord);
     2207           return EXCEPTION_CONTINUE_SEARCH;
     2208         }
     2209       } else if (in_java) {
     2210         // JVM-managed guard pages cannot be used on win95/98.  The o/s provides
     2211         // a one-time-only guard page, which it has released to us.  The next
     2212         // stack overflow on this thread will result in an ACCESS_VIOLATION.
     2213         return Handle_Exception(exceptionInfo,
     2214           SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
     2215       } else {
     2216         // Can only return and hope for the best.  Further stack growth will
     2217         // result in an ACCESS_VIOLATION.
     2218         return EXCEPTION_CONTINUE_EXECUTION;
     2219       }
     2220     } else if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
     2221       // Either stack overflow or null pointer exception.
     2222       if (in_java) {
     2223         PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
     2224         address addr = (address) exceptionRecord->ExceptionInformation[1];
     2225         address stack_end = thread->stack_base() - thread->stack_size();
     2226         if (addr < stack_end && addr >= stack_end - os::vm_page_size()) {
     2227           // Stack overflow.
     2228           assert(!os::uses_stack_guard_pages(),
     2229             "should be caught by red zone code above.");
     2230           return Handle_Exception(exceptionInfo,
     2231             SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
     2232         }
     2233         //
     2234         // Check for safepoint polling and implicit null
     2235         // We only expect null pointers in the stubs (vtable)
     2236         // the rest are checked explicitly now.
     2237         //
     2238         CodeBlob* cb = CodeCache::find_blob(pc);
     2239         if (cb != NULL) {
     2240           if (os::is_poll_address(addr)) {
     2241             address stub = SharedRuntime::get_poll_stub(pc);
     2242             return Handle_Exception(exceptionInfo, stub);
     2243           }
     2244         }
     2245         {
     2246 #ifdef _WIN64
     2247           //
     2248           // If it's a legal stack address map the entire region in
     2249           //
     2250           PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
     2251           address addr = (address) exceptionRecord->ExceptionInformation[1];
     2252           if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) {
     2253                   addr = (address)((uintptr_t)addr &
     2254                          (~((uintptr_t)os::vm_page_size() - (uintptr_t)1)));
     2255                   os::commit_memory((char *)addr, thread->stack_base() - addr,
     2256                                     false );
     2257                   return EXCEPTION_CONTINUE_EXECUTION;
     2258           }
     2259           else
     2260 #endif
     2261           {
     2262             // Null pointer exception.
     2263 #ifdef _M_IA64
     2264             // We catch register stack overflows in compiled code by doing
     2265             // an explicit compare and executing a st8(G0, G0) if the
     2266             // BSP enters into our guard area.  We test for the overflow
     2267             // condition and fall into the normal null pointer exception
     2268             // code if BSP hasn't overflowed.
     2269             if ( in_java ) {
     2270               if(thread->register_stack_overflow()) {
     2271                 assert((address)exceptionInfo->ContextRecord->IntS3 ==
     2272                                 thread->register_stack_limit(),
     2273                                "GR7 doesn't contain register_stack_limit");
     2274                 // Disable the yellow zone which sets the state that
     2275                 // we've got a stack overflow problem.
     2276                 if (thread->stack_yellow_zone_enabled()) {
     2277                   thread->disable_stack_yellow_zone();
     2278                 }
     2279                 // Give us some room to process the exception
     2280                 thread->disable_register_stack_guard();
     2281                 // Update GR7 with the new limit so we can continue running
     2282                 // compiled code.
     2283                 exceptionInfo->ContextRecord->IntS3 =
     2284                                (ULONGLONG)thread->register_stack_limit();
     2285                 return Handle_Exception(exceptionInfo,
     2286                        SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
     2287               } else {
     2288                 //
     2289                 // Check for implicit null
     2290                 // We only expect null pointers in the stubs (vtable)
     2291                 // the rest are checked explicitly now.
     2292                 //
     2293                 if (((uintptr_t)addr) < os::vm_page_size() ) {
     2294                   // an access to the first page of VM--assume it is a null pointer
     2295                   address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
     2296                   if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
     2297                 }
     2298               }
     2299             } // in_java
     2300 
     2301             // IA64 doesn't use implicit null checking yet. So we shouldn't
     2302             // get here.
     2303             tty->print_raw_cr("Access violation, possible null pointer exception");
     2304             report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
     2305                          exceptionInfo->ContextRecord);
     2306             return EXCEPTION_CONTINUE_SEARCH;
     2307 #else /* !IA64 */
     2308 
     2309             // Windows 98 reports faulting addresses incorrectly
     2310             if (!MacroAssembler::needs_explicit_null_check((intptr_t)addr) ||
     2311                 !os::win32::is_nt()) {
     2312               address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
     2313               if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
     2314             }
     2315             report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
     2316                          exceptionInfo->ContextRecord);
     2317             return EXCEPTION_CONTINUE_SEARCH;
     2318 #endif
     2319           }
     2320         }
     2321       }
     2322 
     2323 #ifdef _WIN64
     2324       // Special care for fast JNI field accessors.
     2325       // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks
     2326       // in and the heap gets shrunk before the field access.
     2327       if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
     2328         address addr = JNI_FastGetField::find_slowcase_pc(pc);
     2329         if (addr != (address)-1) {
     2330           return Handle_Exception(exceptionInfo, addr);
     2331         }
     2332       }
     2333 #endif
     2334 
     2335 #ifdef _WIN64
     2336       // Windows will sometimes generate an access violation
     2337       // when we call malloc.  Since we use VectoredExceptions
     2338       // on 64 bit platforms, we see this exception.  We must
     2339       // pass this exception on so Windows can recover.
     2340       // We check to see if the pc of the fault is in NTDLL.DLL
     2341       // if so, we pass control on to Windows for handling.
     2342       if (UseVectoredExceptions && _addr_in_ntdll(pc)) return EXCEPTION_CONTINUE_SEARCH;
     2343 #endif
     2344 
     2345       // Stack overflow or null pointer exception in native code.
     2346       report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
     2347                    exceptionInfo->ContextRecord);
     2348       return EXCEPTION_CONTINUE_SEARCH;
     2349     }
     2350 
     2351     if (in_java) {
     2352       switch (exception_code) {
     2353       case EXCEPTION_INT_DIVIDE_BY_ZERO:
     2354         return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO));
     2355 
     2356       case EXCEPTION_INT_OVERFLOW:
     2357         return Handle_IDiv_Exception(exceptionInfo);
     2358 
     2359       } // switch
     2360     }
     2361 #ifndef _WIN64
     2362     if ((thread->thread_state() == _thread_in_Java) ||
     2363         (thread->thread_state() == _thread_in_native) )
     2364     {
     2365       LONG result=Handle_FLT_Exception(exceptionInfo);
     2366       if (result==EXCEPTION_CONTINUE_EXECUTION) return result;
     2367     }
     2368 #endif //_WIN64
     2369   }
     2370 
     2371   if (exception_code != EXCEPTION_BREAKPOINT) {
     2372 #ifndef _WIN64
     2373     report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
     2374                  exceptionInfo->ContextRecord);
     2375 #else
     2376     // Itanium Windows uses a VectoredExceptionHandler
     2377     // Which means that C++ programatic exception handlers (try/except)
     2378     // will get here.  Continue the search for the right except block if
     2379     // the exception code is not a fatal code.
     2380     switch ( exception_code ) {
     2381       case EXCEPTION_ACCESS_VIOLATION:
     2382       case EXCEPTION_STACK_OVERFLOW:
     2383       case EXCEPTION_ILLEGAL_INSTRUCTION:
     2384       case EXCEPTION_ILLEGAL_INSTRUCTION_2:
     2385       case EXCEPTION_INT_OVERFLOW:
     2386       case EXCEPTION_INT_DIVIDE_BY_ZERO:
     2387       {  report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
     2388                        exceptionInfo->ContextRecord);
     2389       }
     2390         break;
     2391       default:
     2392         break;
     2393     }
     2394 #endif
     2395   }
     2396   return EXCEPTION_CONTINUE_SEARCH;
     2397 }
     2398 
     2399 #ifndef _WIN64
     2400 // Special care for fast JNI accessors.
     2401 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and
     2402 // the heap gets shrunk before the field access.
     2403 // Need to install our own structured exception handler since native code may
     2404 // install its own.
     2405 LONG WINAPI fastJNIAccessorExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
     2406   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
     2407   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
     2408     address pc = (address) exceptionInfo->ContextRecord->Eip;
     2409     address addr = JNI_FastGetField::find_slowcase_pc(pc);
     2410     if (addr != (address)-1) {
     2411       return Handle_Exception(exceptionInfo, addr);
     2412     }
     2413   }
     2414   return EXCEPTION_CONTINUE_SEARCH;
     2415 }
     2416 
     2417 #define DEFINE_FAST_GETFIELD(Return,Fieldname,Result) \
     2418 Return JNICALL jni_fast_Get##Result##Field_wrapper(JNIEnv *env, jobject obj, jfieldID fieldID) { \
     2419   __try { \
     2420     return (*JNI_FastGetField::jni_fast_Get##Result##Field_fp)(env, obj, fieldID); \
     2421   } __except(fastJNIAccessorExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) { \
     2422   } \
     2423   return 0; \
     2424 }
     2425 
     2426 DEFINE_FAST_GETFIELD(jboolean, bool,   Boolean)
     2427 DEFINE_FAST_GETFIELD(jbyte,    byte,   Byte)
     2428 DEFINE_FAST_GETFIELD(jchar,    char,   Char)
     2429 DEFINE_FAST_GETFIELD(jshort,   short,  Short)
     2430 DEFINE_FAST_GETFIELD(jint,     int,    Int)
     2431 DEFINE_FAST_GETFIELD(jlong,    long,   Long)
     2432 DEFINE_FAST_GETFIELD(jfloat,   float,  Float)
     2433 DEFINE_FAST_GETFIELD(jdouble,  double, Double)
     2434 
     2435 address os::win32::fast_jni_accessor_wrapper(BasicType type) {
     2436   switch (type) {
     2437     case T_BOOLEAN: return (address)jni_fast_GetBooleanField_wrapper;
     2438     case T_BYTE:    return (address)jni_fast_GetByteField_wrapper;
     2439     case T_CHAR:    return (address)jni_fast_GetCharField_wrapper;
     2440     case T_SHORT:   return (address)jni_fast_GetShortField_wrapper;
     2441     case T_INT:     return (address)jni_fast_GetIntField_wrapper;
     2442     case T_LONG:    return (address)jni_fast_GetLongField_wrapper;
     2443     case T_FLOAT:   return (address)jni_fast_GetFloatField_wrapper;
     2444     case T_DOUBLE:  return (address)jni_fast_GetDoubleField_wrapper;
     2445     default:        ShouldNotReachHere();
     2446   }
     2447   return (address)-1;
     2448 }
     2449 #endif
     2450 
     2451 // Virtual Memory
     2452 
     2453 int os::vm_page_size() { return os::win32::vm_page_size(); }
     2454 int os::vm_allocation_granularity() {
     2455   return os::win32::vm_allocation_granularity();
     2456 }
     2457 
     2458 // Windows large page support is available on Windows 2003. In order to use
     2459 // large page memory, the administrator must first assign additional privilege
     2460 // to the user:
     2461 //   + select Control Panel -> Administrative Tools -> Local Security Policy
     2462 //   + select Local Policies -> User Rights Assignment
     2463 //   + double click "Lock pages in memory", add users and/or groups
     2464 //   + reboot
     2465 // Note the above steps are needed for administrator as well, as administrators
     2466 // by default do not have the privilege to lock pages in memory.
     2467 //
     2468 // Note about Windows 2003: although the API supports committing large page
     2469 // memory on a page-by-page basis and VirtualAlloc() returns success under this
     2470 // scenario, I found through experiment it only uses large page if the entire
     2471 // memory region is reserved and committed in a single VirtualAlloc() call.
     2472 // This makes Windows large page support more or less like Solaris ISM, in
     2473 // that the entire heap must be committed upfront. This probably will change
     2474 // in the future, if so the code below needs to be revisited.
     2475 
     2476 #ifndef MEM_LARGE_PAGES
     2477 #define MEM_LARGE_PAGES 0x20000000
     2478 #endif
     2479 
     2480 // GetLargePageMinimum is only available on Windows 2003. The other functions
     2481 // are available on NT but not on Windows 98/Me. We have to resolve them at
     2482 // runtime.
     2483 typedef SIZE_T (WINAPI *GetLargePageMinimum_func_type) (void);
     2484 typedef BOOL (WINAPI *AdjustTokenPrivileges_func_type)
     2485              (HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
     2486 typedef BOOL (WINAPI *OpenProcessToken_func_type) (HANDLE, DWORD, PHANDLE);
     2487 typedef BOOL (WINAPI *LookupPrivilegeValue_func_type) (LPCTSTR, LPCTSTR, PLUID);
     2488 
     2489 static GetLargePageMinimum_func_type   _GetLargePageMinimum;
     2490 static AdjustTokenPrivileges_func_type _AdjustTokenPrivileges;
     2491 static OpenProcessToken_func_type      _OpenProcessToken;
     2492 static LookupPrivilegeValue_func_type  _LookupPrivilegeValue;
     2493 
     2494 static HINSTANCE _kernel32;
     2495 static HINSTANCE _advapi32;
     2496 static HANDLE    _hProcess;
     2497 static HANDLE    _hToken;
     2498 
     2499 static size_t _large_page_size = 0;
     2500 
     2501 static bool resolve_functions_for_large_page_init() {
     2502   _kernel32 = LoadLibrary("kernel32.dll");
     2503   if (_kernel32 == NULL) return false;
     2504 
     2505   _GetLargePageMinimum   = CAST_TO_FN_PTR(GetLargePageMinimum_func_type,
     2506                             GetProcAddress(_kernel32, "GetLargePageMinimum"));
     2507   if (_GetLargePageMinimum == NULL) return false;
     2508 
     2509   _advapi32 = LoadLibrary("advapi32.dll");
     2510   if (_advapi32 == NULL) return false;
     2511 
     2512   _AdjustTokenPrivileges = CAST_TO_FN_PTR(AdjustTokenPrivileges_func_type,
     2513                             GetProcAddress(_advapi32, "AdjustTokenPrivileges"));
     2514   _OpenProcessToken      = CAST_TO_FN_PTR(OpenProcessToken_func_type,
     2515                             GetProcAddress(_advapi32, "OpenProcessToken"));
     2516   _LookupPrivilegeValue  = CAST_TO_FN_PTR(LookupPrivilegeValue_func_type,
     2517                             GetProcAddress(_advapi32, "LookupPrivilegeValueA"));
     2518   return _AdjustTokenPrivileges != NULL &&
     2519          _OpenProcessToken      != NULL &&
     2520          _LookupPrivilegeValue  != NULL;
     2521 }
     2522 
     2523 static bool request_lock_memory_privilege() {
     2524   _hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
     2525                                 os::current_process_id());
     2526 
     2527   LUID luid;
     2528   if (_hProcess != NULL &&
     2529       _OpenProcessToken(_hProcess, TOKEN_ADJUST_PRIVILEGES, &_hToken) &&
     2530       _LookupPrivilegeValue(NULL, "SeLockMemoryPrivilege", &luid)) {
     2531 
     2532     TOKEN_PRIVILEGES tp;
     2533     tp.PrivilegeCount = 1;
     2534     tp.Privileges[0].Luid = luid;
     2535     tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
     2536 
     2537     // AdjustTokenPrivileges() may return TRUE even when it couldn't change the
     2538     // privilege. Check GetLastError() too. See MSDN document.
     2539     if (_AdjustTokenPrivileges(_hToken, false, &tp, sizeof(tp), NULL, NULL) &&
     2540         (GetLastError() == ERROR_SUCCESS)) {
     2541       return true;
     2542     }
     2543   }
     2544 
     2545   return false;
     2546 }
     2547 
     2548 static void cleanup_after_large_page_init() {
     2549   _GetLargePageMinimum = NULL;
     2550   _AdjustTokenPrivileges = NULL;
     2551   _OpenProcessToken = NULL;
     2552   _LookupPrivilegeValue = NULL;
     2553   if (_kernel32) FreeLibrary(_kernel32);
     2554   _kernel32 = NULL;
     2555   if (_advapi32) FreeLibrary(_advapi32);
     2556   _advapi32 = NULL;
     2557   if (_hProcess) CloseHandle(_hProcess);
     2558   _hProcess = NULL;
     2559   if (_hToken) CloseHandle(_hToken);
     2560   _hToken = NULL;
     2561 }
     2562 
     2563 bool os::large_page_init() {
     2564   if (!UseLargePages) return false;
     2565 
     2566   // print a warning if any large page related flag is specified on command line
     2567   bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) ||
     2568                          !FLAG_IS_DEFAULT(LargePageSizeInBytes);
     2569   bool success = false;
     2570 
     2571 # define WARN(msg) if (warn_on_failure) { warning(msg); }
     2572   if (resolve_functions_for_large_page_init()) {
     2573     if (request_lock_memory_privilege()) {
     2574       size_t s = _GetLargePageMinimum();
     2575       if (s) {
     2576 #if defined(IA32) || defined(AMD64)
     2577         if (s > 4*M || LargePageSizeInBytes > 4*M) {
     2578           WARN("JVM cannot use large pages bigger than 4mb.");
     2579         } else {
     2580 #endif
     2581           if (LargePageSizeInBytes && LargePageSizeInBytes % s == 0) {
     2582             _large_page_size = LargePageSizeInBytes;
     2583           } else {
     2584             _large_page_size = s;
     2585           }
     2586           success = true;
     2587 #if defined(IA32) || defined(AMD64)
     2588         }
     2589 #endif
     2590       } else {
     2591         WARN("Large page is not supported by the processor.");
     2592       }
     2593     } else {
     2594       WARN("JVM cannot use large page memory because it does not have enough privilege to lock pages in memory.");
     2595     }
     2596   } else {
     2597     WARN("Large page is not supported by the operating system.");
     2598   }
     2599 #undef WARN
     2600 
     2601   const size_t default_page_size = (size_t) vm_page_size();
     2602   if (success && _large_page_size > default_page_size) {
     2603     _page_sizes[0] = _large_page_size;
     2604     _page_sizes[1] = default_page_size;
     2605     _page_sizes[2] = 0;
     2606   }
     2607 
     2608   cleanup_after_large_page_init();
     2609   return success;
     2610 }
     2611 
     2612 // On win32, one cannot release just a part of reserved memory, it's an
     2613 // all or nothing deal.  When we split a reservation, we must break the
     2614 // reservation into two reservations.
     2615 void os::split_reserved_memory(char *base, size_t size, size_t split,
     2616                               bool realloc) {
     2617   if (size > 0) {
     2618     release_memory(base, size);
     2619     if (realloc) {
     2620       reserve_memory(split, base);
     2621     }
     2622     if (size != split) {
     2623       reserve_memory(size - split, base + split);
     2624     }
     2625   }
     2626 }
     2627 
     2628 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
     2629   assert((size_t)addr % os::vm_allocation_granularity() == 0,
     2630          "reserve alignment");
     2631   assert(bytes % os::vm_allocation_granularity() == 0, "reserve block size");
     2632   char* res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE, PAGE_READWRITE);
     2633   assert(res == NULL || addr == NULL || addr == res,
     2634          "Unexpected address from reserve.");
     2635   return res;
     2636 }
     2637 
     2638 // Reserve memory at an arbitrary address, only if that area is
     2639 // available (and not reserved for something else).
     2640 char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
     2641   // Windows os::reserve_memory() fails of the requested address range is
     2642   // not avilable.
     2643   return reserve_memory(bytes, requested_addr);
     2644 }
     2645 
     2646 size_t os::large_page_size() {
     2647   return _large_page_size;
     2648 }
     2649 
     2650 bool os::can_commit_large_page_memory() {
     2651   // Windows only uses large page memory when the entire region is reserved
     2652   // and committed in a single VirtualAlloc() call. This may change in the
     2653   // future, but with Windows 2003 it's not possible to commit on demand.
     2654   return false;
     2655 }
     2656 
     2657 bool os::can_execute_large_page_memory() {
     2658   return true;
     2659 }
     2660 
     2661 char* os::reserve_memory_special(size_t bytes, char* addr, bool exec) {
     2662 
     2663   const DWORD prot = exec ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
     2664 
     2665   if (UseLargePagesIndividualAllocation) {
     2666     if (TracePageSizes && Verbose) {
     2667        tty->print_cr("Reserving large pages individually.");
     2668     }
     2669     char * p_buf;
     2670     // first reserve enough address space in advance since we want to be
     2671     // able to break a single contiguous virtual address range into multiple
     2672     // large page commits but WS2003 does not allow reserving large page space
     2673     // so we just use 4K pages for reserve, this gives us a legal contiguous
     2674     // address space. then we will deallocate that reservation, and re alloc
     2675     // using large pages
     2676     const size_t size_of_reserve = bytes + _large_page_size;
     2677     if (bytes > size_of_reserve) {
     2678       // Overflowed.
     2679       warning("Individually allocated large pages failed, "
     2680         "use -XX:-UseLargePagesIndividualAllocation to turn off");
     2681       return NULL;
     2682     }
     2683     p_buf = (char *) VirtualAlloc(addr,
     2684                                  size_of_reserve,  // size of Reserve
     2685                                  MEM_RESERVE,
     2686                                  PAGE_READWRITE);
     2687     // If reservation failed, return NULL
     2688     if (p_buf == NULL) return NULL;
     2689 
     2690     release_memory(p_buf, bytes + _large_page_size);
     2691     // round up to page boundary.  If the size_of_reserve did not
     2692     // overflow and the reservation did not fail, this align up
     2693     // should not overflow.
     2694     p_buf = (char *) align_size_up((size_t)p_buf, _large_page_size);
     2695 
     2696     // now go through and allocate one page at a time until all bytes are
     2697     // allocated
     2698     size_t  bytes_remaining = align_size_up(bytes, _large_page_size);
     2699     // An overflow of align_size_up() would have been caught above
     2700     // in the calculation of size_of_reserve.
     2701     char * next_alloc_addr = p_buf;
     2702 
     2703 #ifdef ASSERT
     2704     // Variable for the failure injection
     2705     long ran_num = os::random();
     2706     size_t fail_after = ran_num % bytes;
     2707 #endif
     2708 
     2709     while (bytes_remaining) {
     2710       size_t bytes_to_rq = MIN2(bytes_remaining, _large_page_size);
     2711       // Note allocate and commit
     2712       char * p_new;
     2713 
     2714 #ifdef ASSERT
     2715       bool inject_error = LargePagesIndividualAllocationInjectError &&
     2716           (bytes_remaining <= fail_after);
     2717 #else
     2718       const bool inject_error = false;
     2719 #endif
     2720 
     2721       if (inject_error) {
     2722         p_new = NULL;
     2723       } else {
     2724         p_new = (char *) VirtualAlloc(next_alloc_addr,
     2725                                     bytes_to_rq,
     2726                                     MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
     2727                                     prot);
     2728       }
     2729 
     2730       if (p_new == NULL) {
     2731         // Free any allocated pages
     2732         if (next_alloc_addr > p_buf) {
     2733           // Some memory was committed so release it.
     2734           size_t bytes_to_release = bytes - bytes_remaining;
     2735           release_memory(p_buf, bytes_to_release);
     2736         }
     2737 #ifdef ASSERT
     2738         if (UseLargePagesIndividualAllocation &&
     2739             LargePagesIndividualAllocationInjectError) {
     2740           if (TracePageSizes && Verbose) {
     2741              tty->print_cr("Reserving large pages individually failed.");
     2742           }
     2743         }
     2744 #endif
     2745         return NULL;
     2746       }
     2747       bytes_remaining -= bytes_to_rq;
     2748       next_alloc_addr += bytes_to_rq;
     2749     }
     2750 
     2751     return p_buf;
     2752 
     2753   } else {
     2754     // normal policy just allocate it all at once
     2755     DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES;
     2756     char * res = (char *)VirtualAlloc(NULL, bytes, flag, prot);
     2757     return res;
     2758   }
     2759 }
     2760 
     2761 bool os::release_memory_special(char* base, size_t bytes) {
     2762   return release_memory(base, bytes);
     2763 }
     2764 
     2765 void os::print_statistics() {
     2766 }
     2767 
     2768 bool os::commit_memory(char* addr, size_t bytes, bool exec) {
     2769   if (bytes == 0) {
     2770     // Don't bother the OS with noops.
     2771     return true;
     2772   }
     2773   assert((size_t) addr % os::vm_page_size() == 0, "commit on page boundaries");
     2774   assert(bytes % os::vm_page_size() == 0, "commit in page-sized chunks");
     2775   // Don't attempt to print anything if the OS call fails. We're
     2776   // probably low on resources, so the print itself may cause crashes.
     2777   bool result = VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) != 0;
     2778   if (result != NULL && exec) {
     2779     DWORD oldprot;
     2780     // Windows doc says to use VirtualProtect to get execute permissions
     2781     return VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot) != 0;
     2782   } else {
     2783     return result;
     2784   }
     2785 }
     2786 
     2787 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
     2788                        bool exec) {
     2789   return commit_memory(addr, size, exec);
     2790 }
     2791 
     2792 bool os::uncommit_memory(char* addr, size_t bytes) {
     2793   if (bytes == 0) {
     2794     // Don't bother the OS with noops.
     2795     return true;
     2796   }
     2797   assert((size_t) addr % os::vm_page_size() == 0, "uncommit on page boundaries");
     2798   assert(bytes % os::vm_page_size() == 0, "uncommit in page-sized chunks");
     2799   return VirtualFree(addr, bytes, MEM_DECOMMIT) != 0;
     2800 }
     2801 
     2802 bool os::release_memory(char* addr, size_t bytes) {
     2803   return VirtualFree(addr, 0, MEM_RELEASE) != 0;
     2804 }
     2805 
     2806 bool os::create_stack_guard_pages(char* addr, size_t size) {
     2807   return os::commit_memory(addr, size);
     2808 }
     2809 
     2810 bool os::remove_stack_guard_pages(char* addr, size_t size) {
     2811   return os::uncommit_memory(addr, size);
     2812 }
     2813 
     2814 // Set protections specified
     2815 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
     2816                         bool is_committed) {
     2817   unsigned int p = 0;
     2818   switch (prot) {
     2819   case MEM_PROT_NONE: p = PAGE_NOACCESS; break;
     2820   case MEM_PROT_READ: p = PAGE_READONLY; break;
     2821   case MEM_PROT_RW:   p = PAGE_READWRITE; break;
     2822   case MEM_PROT_RWX:  p = PAGE_EXECUTE_READWRITE; break;
     2823   default:
     2824     ShouldNotReachHere();
     2825   }
     2826 
     2827   DWORD old_status;
     2828 
     2829   // Strange enough, but on Win32 one can change protection only for committed
     2830   // memory, not a big deal anyway, as bytes less or equal than 64K
     2831   if (!is_committed && !commit_memory(addr, bytes, prot == MEM_PROT_RWX)) {
     2832     fatal("cannot commit protection page");
     2833   }
     2834   // One cannot use os::guard_memory() here, as on Win32 guard page
     2835   // have different (one-shot) semantics, from MSDN on PAGE_GUARD:
     2836   //
     2837   // Pages in the region become guard pages. Any attempt to access a guard page
     2838   // causes the system to raise a STATUS_GUARD_PAGE exception and turn off
     2839   // the guard page status. Guard pages thus act as a one-time access alarm.
     2840   return VirtualProtect(addr, bytes, p, &old_status) != 0;
     2841 }
     2842 
     2843 bool os::guard_memory(char* addr, size_t bytes) {
     2844   DWORD old_status;
     2845   return VirtualProtect(addr, bytes, PAGE_READWRITE | PAGE_GUARD, &old_status) != 0;
     2846 }
     2847 
     2848 bool os::unguard_memory(char* addr, size_t bytes) {
     2849   DWORD old_status;
     2850   return VirtualProtect(addr, bytes, PAGE_READWRITE, &old_status) != 0;
     2851 }
     2852 
     2853 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { }
     2854 void os::free_memory(char *addr, size_t bytes)         { }
     2855 void os::numa_make_global(char *addr, size_t bytes)    { }
     2856 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint)    { }
     2857 bool os::numa_topology_changed()                       { return false; }
     2858 size_t os::numa_get_groups_num()                       { return 1; }
     2859 int os::numa_get_group_id()                            { return 0; }
     2860 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
     2861   if (size > 0) {
     2862     ids[0] = 0;
     2863     return 1;
     2864   }
     2865   return 0;
     2866 }
     2867 
     2868 bool os::get_page_info(char *start, page_info* info) {
     2869   return false;
     2870 }
     2871 
     2872 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
     2873   return end;
     2874 }
     2875 
     2876 char* os::non_memory_address_word() {
     2877   // Must never look like an address returned by reserve_memory,
     2878   // even in its subfields (as defined by the CPU immediate fields,
     2879   // if the CPU splits constants across multiple instructions).
     2880   return (char*)-1;
     2881 }
     2882 
     2883 #define MAX_ERROR_COUNT 100
     2884 #define SYS_THREAD_ERROR 0xffffffffUL
     2885 
     2886 void os::pd_start_thread(Thread* thread) {
     2887   DWORD ret = ResumeThread(thread->osthread()->thread_handle());
     2888   // Returns previous suspend state:
     2889   // 0:  Thread was not suspended
     2890   // 1:  Thread is running now
     2891   // >1: Thread is still suspended.
     2892   assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back
     2893 }
     2894 
     2895 size_t os::read(int fd, void *buf, unsigned int nBytes) {
     2896   return ::read(fd, buf, nBytes);
     2897 }
     2898 
     2899 class HighResolutionInterval {
     2900   // The default timer resolution seems to be 10 milliseconds.
     2901   // (Where is this written down?)
     2902   // If someone wants to sleep for only a fraction of the default,
     2903   // then we set the timer resolution down to 1 millisecond for
     2904   // the duration of their interval.
     2905   // We carefully set the resolution back, since otherwise we
     2906   // seem to incur an overhead (3%?) that we don't need.
     2907   // CONSIDER: if ms is small, say 3, then we should run with a high resolution time.
     2908   // Buf if ms is large, say 500, or 503, we should avoid the call to timeBeginPeriod().
     2909   // Alternatively, we could compute the relative error (503/500 = .6%) and only use
     2910   // timeBeginPeriod() if the relative error exceeded some threshold.
     2911   // timeBeginPeriod() has been linked to problems with clock drift on win32 systems and
     2912   // to decreased efficiency related to increased timer "tick" rates.  We want to minimize
     2913   // (a) calls to timeBeginPeriod() and timeEndPeriod() and (b) time spent with high
     2914   // resolution timers running.
     2915 private:
     2916     jlong resolution;
     2917 public:
     2918   HighResolutionInterval(jlong ms) {
     2919     resolution = ms % 10L;
     2920     if (resolution != 0) {
     2921       MMRESULT result = timeBeginPeriod(1L);
     2922     }
     2923   }
     2924   ~HighResolutionInterval() {
     2925     if (resolution != 0) {
     2926       MMRESULT result = timeEndPeriod(1L);
     2927     }
     2928     resolution = 0L;
     2929   }
     2930 };
     2931 
     2932 int os::sleep(Thread* thread, jlong ms, bool interruptable) {
     2933   jlong limit = (jlong) MAXDWORD;
     2934 
     2935   while(ms > limit) {
     2936     int res;
     2937     if ((res = sleep(thread, limit, interruptable)) != OS_TIMEOUT)
     2938       return res;
     2939     ms -= limit;
     2940   }
     2941 
     2942   assert(thread == Thread::current(),  "thread consistency check");
     2943   OSThread* osthread = thread->osthread();
     2944   OSThreadWaitState osts(osthread, false /* not Object.wait() */);
     2945   int result;
     2946   if (interruptable) {
     2947     assert(thread->is_Java_thread(), "must be java thread");
     2948     JavaThread *jt = (JavaThread *) thread;
     2949     ThreadBlockInVM tbivm(jt);
     2950 
     2951     jt->set_suspend_equivalent();
     2952     // cleared by handle_special_suspend_equivalent_condition() or
     2953     // java_suspend_self() via check_and_wait_while_suspended()
     2954 
     2955     HANDLE events[1];
     2956     events[0] = osthread->interrupt_event();
     2957     HighResolutionInterval *phri=NULL;
     2958     if(!ForceTimeHighResolution)
     2959       phri = new HighResolutionInterval( ms );
     2960     if (WaitForMultipleObjects(1, events, FALSE, (DWORD)ms) == WAIT_TIMEOUT) {
     2961       result = OS_TIMEOUT;
     2962     } else {
     2963       ResetEvent(osthread->interrupt_event());
     2964       osthread->set_interrupted(false);
     2965       result = OS_INTRPT;
     2966     }
     2967     delete phri; //if it is NULL, harmless
     2968 
     2969     // were we externally suspended while we were waiting?
     2970     jt->check_and_wait_while_suspended();
     2971   } else {
     2972     assert(!thread->is_Java_thread(), "must not be java thread");
     2973     Sleep((long) ms);
     2974     result = OS_TIMEOUT;
     2975   }
     2976   return result;
     2977 }
     2978 
     2979 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
     2980 void os::infinite_sleep() {
     2981   while (true) {    // sleep forever ...
     2982     Sleep(100000);  // ... 100 seconds at a time
     2983   }
     2984 }
     2985 
     2986 typedef BOOL (WINAPI * STTSignature)(void) ;
     2987 
     2988 os::YieldResult os::NakedYield() {
     2989   // Use either SwitchToThread() or Sleep(0)
     2990   // Consider passing back the return value from SwitchToThread().
     2991   // We use GetProcAddress() as ancient Win9X versions of windows doen't support SwitchToThread.
     2992   // In that case we revert to Sleep(0).
     2993   static volatile STTSignature stt = (STTSignature) 1 ;
     2994 
     2995   if (stt == ((STTSignature) 1)) {
     2996     stt = (STTSignature) ::GetProcAddress (LoadLibrary ("Kernel32.dll"), "SwitchToThread") ;
     2997     // It's OK if threads race during initialization as the operation above is idempotent.
     2998   }
     2999   if (stt != NULL) {
     3000     return (*stt)() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ;
     3001   } else {
     3002     Sleep (0) ;
     3003   }
     3004   return os::YIELD_UNKNOWN ;
     3005 }
     3006 
     3007 void os::yield() {  os::NakedYield(); }
     3008 
     3009 void os::yield_all(int attempts) {
     3010   // Yields to all threads, including threads with lower priorities
     3011   Sleep(1);
     3012 }
     3013 
     3014 // Win32 only gives you access to seven real priorities at a time,
     3015 // so we compress Java's ten down to seven.  It would be better
     3016 // if we dynamically adjusted relative priorities.
     3017 
     3018 int os::java_to_os_priority[MaxPriority + 1] = {
     3019   THREAD_PRIORITY_IDLE,                         // 0  Entry should never be used
     3020   THREAD_PRIORITY_LOWEST,                       // 1  MinPriority
     3021   THREAD_PRIORITY_LOWEST,                       // 2
     3022   THREAD_PRIORITY_BELOW_NORMAL,                 // 3
     3023   THREAD_PRIORITY_BELOW_NORMAL,                 // 4
     3024   THREAD_PRIORITY_NORMAL,                       // 5  NormPriority
     3025   THREAD_PRIORITY_NORMAL,                       // 6
     3026   THREAD_PRIORITY_ABOVE_NORMAL,                 // 7
     3027   THREAD_PRIORITY_ABOVE_NORMAL,                 // 8
     3028   THREAD_PRIORITY_HIGHEST,                      // 9  NearMaxPriority
     3029   THREAD_PRIORITY_HIGHEST                       // 10 MaxPriority
     3030 };
     3031 
     3032 int prio_policy1[MaxPriority + 1] = {
     3033   THREAD_PRIORITY_IDLE,                         // 0  Entry should never be used
     3034   THREAD_PRIORITY_LOWEST,                       // 1  MinPriority
     3035   THREAD_PRIORITY_LOWEST,                       // 2
     3036   THREAD_PRIORITY_BELOW_NORMAL,                 // 3
     3037   THREAD_PRIORITY_BELOW_NORMAL,                 // 4
     3038   THREAD_PRIORITY_NORMAL,                       // 5  NormPriority
     3039   THREAD_PRIORITY_ABOVE_NORMAL,                 // 6
     3040   THREAD_PRIORITY_ABOVE_NORMAL,                 // 7
     3041   THREAD_PRIORITY_HIGHEST,                      // 8
     3042   THREAD_PRIORITY_HIGHEST,                      // 9  NearMaxPriority
     3043   THREAD_PRIORITY_TIME_CRITICAL                 // 10 MaxPriority
     3044 };
     3045 
     3046 static int prio_init() {
     3047   // If ThreadPriorityPolicy is 1, switch tables
     3048   if (ThreadPriorityPolicy == 1) {
     3049     int i;
     3050     for (i = 0; i < MaxPriority + 1; i++) {
     3051       os::java_to_os_priority[i] = prio_policy1[i];
     3052     }
     3053   }
     3054   return 0;
     3055 }
     3056 
     3057 OSReturn os::set_native_priority(Thread* thread, int priority) {
     3058   if (!UseThreadPriorities) return OS_OK;
     3059   bool ret = SetThreadPriority(thread->osthread()->thread_handle(), priority) != 0;
     3060   return ret ? OS_OK : OS_ERR;
     3061 }
     3062 
     3063 OSReturn os::get_native_priority(const Thread* const thread, int* priority_ptr) {
     3064   if ( !UseThreadPriorities ) {
     3065     *priority_ptr = java_to_os_priority[NormPriority];
     3066     return OS_OK;
     3067   }
     3068   int os_prio = GetThreadPriority(thread->osthread()->thread_handle());
     3069   if (os_prio == THREAD_PRIORITY_ERROR_RETURN) {
     3070     assert(false, "GetThreadPriority failed");
     3071     return OS_ERR;
     3072   }
     3073   *priority_ptr = os_prio;
     3074   return OS_OK;
     3075 }
     3076 
     3077 
     3078 // Hint to the underlying OS that a task switch would not be good.
     3079 // Void return because it's a hint and can fail.
     3080 void os::hint_no_preempt() {}
     3081 
     3082 void os::interrupt(Thread* thread) {
     3083   assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
     3084          "possibility of dangling Thread pointer");
     3085 
     3086   OSThread* osthread = thread->osthread();
     3087   osthread->set_interrupted(true);
     3088   // More than one thread can get here with the same value of osthread,
     3089   // resulting in multiple notifications.  We do, however, want the store
     3090   // to interrupted() to be visible to other threads before we post
     3091   // the interrupt event.
     3092   OrderAccess::release();
     3093   SetEvent(osthread->interrupt_event());
     3094   // For JSR166:  unpark after setting status
     3095   if (thread->is_Java_thread())
     3096     ((JavaThread*)thread)->parker()->unpark();
     3097 
     3098   ParkEvent * ev = thread->_ParkEvent ;
     3099   if (ev != NULL) ev->unpark() ;
     3100 
     3101 }
     3102 
     3103 
     3104 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
     3105   assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
     3106          "possibility of dangling Thread pointer");
     3107 
     3108   OSThread* osthread = thread->osthread();
     3109   bool interrupted;
     3110   interrupted = osthread->interrupted();
     3111   if (clear_interrupted == true) {
     3112     osthread->set_interrupted(false);
     3113     ResetEvent(osthread->interrupt_event());
     3114   } // Otherwise leave the interrupted state alone
     3115 
     3116   return interrupted;
     3117 }
     3118 
     3119 // Get's a pc (hint) for a running thread. Currently used only for profiling.
     3120 ExtendedPC os::get_thread_pc(Thread* thread) {
     3121   CONTEXT context;
     3122   context.ContextFlags = CONTEXT_CONTROL;
     3123   HANDLE handle = thread->osthread()->thread_handle();
     3124 #ifdef _M_IA64
     3125   assert(0, "Fix get_thread_pc");
     3126   return ExtendedPC(NULL);
     3127 #else
     3128   if (GetThreadContext(handle, &context)) {
     3129 #ifdef _M_AMD64
     3130     return ExtendedPC((address) context.Rip);
     3131 #else
     3132     return ExtendedPC((address) context.Eip);
     3133 #endif
     3134   } else {
     3135     return ExtendedPC(NULL);
     3136   }
     3137 #endif
     3138 }
     3139 
     3140 // GetCurrentThreadId() returns DWORD
     3141 intx os::current_thread_id()          { return GetCurrentThreadId(); }
     3142 
     3143 static int _initial_pid = 0;
     3144 
     3145 int os::current_process_id()
     3146 {
     3147   return (_initial_pid ? _initial_pid : _getpid());
     3148 }
     3149 
     3150 int    os::win32::_vm_page_size       = 0;
     3151 int    os::win32::_vm_allocation_granularity = 0;
     3152 int    os::win32::_processor_type     = 0;
     3153 // Processor level is not available on non-NT systems, use vm_version instead
     3154 int    os::win32::_processor_level    = 0;
     3155 julong os::win32::_physical_memory    = 0;
     3156 size_t os::win32::_default_stack_size = 0;
     3157 
     3158          intx os::win32::_os_thread_limit    = 0;
     3159 volatile intx os::win32::_os_thread_count    = 0;
     3160 
     3161 bool   os::win32::_is_nt              = false;
     3162 bool   os::win32::_is_windows_2003    = false;
     3163 
     3164 
     3165 void os::win32::initialize_system_info() {
     3166   SYSTEM_INFO si;
     3167   GetSystemInfo(&si);
     3168   _vm_page_size    = si.dwPageSize;
     3169   _vm_allocation_granularity = si.dwAllocationGranularity;
     3170   _processor_type  = si.dwProcessorType;
     3171   _processor_level = si.wProcessorLevel;
     3172   set_processor_count(si.dwNumberOfProcessors);
     3173 
     3174   MEMORYSTATUSEX ms;
     3175   ms.dwLength = sizeof(ms);
     3176 
     3177   // also returns dwAvailPhys (free physical memory bytes), dwTotalVirtual, dwAvailVirtual,
     3178   // dwMemoryLoad (% of memory in use)
     3179   GlobalMemoryStatusEx(&ms);
     3180   _physical_memory = ms.ullTotalPhys;
     3181 
     3182   OSVERSIONINFO oi;
     3183   oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
     3184   GetVersionEx(&oi);
     3185   switch(oi.dwPlatformId) {
     3186     case VER_PLATFORM_WIN32_WINDOWS: _is_nt = false; break;
     3187     case VER_PLATFORM_WIN32_NT:
     3188       _is_nt = true;
     3189       {
     3190         int os_vers = oi.dwMajorVersion * 1000 + oi.dwMinorVersion;
     3191         if (os_vers == 5002) {
     3192           _is_windows_2003 = true;
     3193         }
     3194       }
     3195       break;
     3196     default: fatal("Unknown platform");
     3197   }
     3198 
     3199   _default_stack_size = os::current_stack_size();
     3200   assert(_default_stack_size > (size_t) _vm_page_size, "invalid stack size");
     3201   assert((_default_stack_size & (_vm_page_size - 1)) == 0,
     3202     "stack size not a multiple of page size");
     3203 
     3204   initialize_performance_counter();
     3205 
     3206   // Win95/Win98 scheduler bug work-around. The Win95/98 scheduler is
     3207   // known to deadlock the system, if the VM issues to thread operations with
     3208   // a too high frequency, e.g., such as changing the priorities.
     3209   // The 6000 seems to work well - no deadlocks has been notices on the test
     3210   // programs that we have seen experience this problem.
     3211   if (!os::win32::is_nt()) {
     3212     StarvationMonitorInterval = 6000;
     3213   }
     3214 }
     3215 
     3216 
     3217 void os::win32::setmode_streams() {
     3218   _setmode(_fileno(stdin), _O_BINARY);
     3219   _setmode(_fileno(stdout), _O_BINARY);
     3220   _setmode(_fileno(stderr), _O_BINARY);
     3221 }
     3222 
     3223 
     3224 int os::message_box(const char* title, const char* message) {
     3225   int result = MessageBox(NULL, message, title,
     3226                           MB_YESNO | MB_ICONERROR | MB_SYSTEMMODAL | MB_DEFAULT_DESKTOP_ONLY);
     3227   return result == IDYES;
     3228 }
     3229 
     3230 int os::allocate_thread_local_storage() {
     3231   return TlsAlloc();
     3232 }
     3233 
     3234 
     3235 void os::free_thread_local_storage(int index) {
     3236   TlsFree(index);
     3237 }
     3238 
     3239 
     3240 void os::thread_local_storage_at_put(int index, void* value) {
     3241   TlsSetValue(index, value);
     3242   assert(thread_local_storage_at(index) == value, "Just checking");
     3243 }
     3244 
     3245 
     3246 void* os::thread_local_storage_at(int index) {
     3247   return TlsGetValue(index);
     3248 }
     3249 
     3250 
     3251 #ifndef PRODUCT
     3252 #ifndef _WIN64
     3253 // Helpers to check whether NX protection is enabled
     3254 int nx_exception_filter(_EXCEPTION_POINTERS *pex) {
     3255   if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
     3256       pex->ExceptionRecord->NumberParameters > 0 &&
     3257       pex->ExceptionRecord->ExceptionInformation[0] ==
     3258       EXCEPTION_INFO_EXEC_VIOLATION) {
     3259     return EXCEPTION_EXECUTE_HANDLER;
     3260   }
     3261   return EXCEPTION_CONTINUE_SEARCH;
     3262 }
     3263 
     3264 void nx_check_protection() {
     3265   // If NX is enabled we'll get an exception calling into code on the stack
     3266   char code[] = { (char)0xC3 }; // ret
     3267   void *code_ptr = (void *)code;
     3268   __try {
     3269     __asm call code_ptr
     3270   } __except(nx_exception_filter((_EXCEPTION_POINTERS*)_exception_info())) {
     3271     tty->print_raw_cr("NX protection detected.");
     3272   }
     3273 }
     3274 #endif // _WIN64
     3275 #endif // PRODUCT
     3276 
     3277 // this is called _before_ the global arguments have been parsed
     3278 void os::init(void) {
     3279   _initial_pid = _getpid();
     3280 
     3281   init_random(1234567);
     3282 
     3283   win32::initialize_system_info();
     3284   win32::setmode_streams();
     3285   init_page_sizes((size_t) win32::vm_page_size());
     3286 
     3287   // For better scalability on MP systems (must be called after initialize_system_info)
     3288 #ifndef PRODUCT
     3289   if (is_MP()) {
     3290     NoYieldsInMicrolock = true;
     3291   }
     3292 #endif
     3293   // This may be overridden later when argument processing is done.
     3294   FLAG_SET_ERGO(bool, UseLargePagesIndividualAllocation,
     3295     os::win32::is_windows_2003());
     3296 
     3297   // Initialize main_process and main_thread
     3298   main_process = GetCurrentProcess();  // Remember main_process is a pseudo handle
     3299  if (!DuplicateHandle(main_process, GetCurrentThread(), main_process,
     3300                        &main_thread, THREAD_ALL_ACCESS, false, 0)) {
     3301     fatal("DuplicateHandle failed\n");
     3302   }
     3303   main_thread_id = (int) GetCurrentThreadId();
     3304 }
     3305 
     3306 // To install functions for atexit processing
     3307 extern "C" {
     3308   static void perfMemory_exit_helper() {
     3309     perfMemory_exit();
     3310   }
     3311 }
     3312 
     3313 
     3314 // this is called _after_ the global arguments have been parsed
     3315 jint os::init_2(void) {
     3316   // Allocate a single page and mark it as readable for safepoint polling
     3317   address polling_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READONLY);
     3318   guarantee( polling_page != NULL, "Reserve Failed for polling page");
     3319 
     3320   address return_page  = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY);
     3321   guarantee( return_page != NULL, "Commit Failed for polling page");
     3322 
     3323   os::set_polling_page( polling_page );
     3324 
     3325 #ifndef PRODUCT
     3326   if( Verbose && PrintMiscellaneous )
     3327     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
     3328 #endif
     3329 
     3330   if (!UseMembar) {
     3331     address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE);
     3332     guarantee( mem_serialize_page != NULL, "Reserve Failed for memory serialize page");
     3333 
     3334     return_page  = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE);
     3335     guarantee( return_page != NULL, "Commit Failed for memory serialize page");
     3336 
     3337     os::set_memory_serialize_page( mem_serialize_page );
     3338 
     3339 #ifndef PRODUCT
     3340     if(Verbose && PrintMiscellaneous)
     3341       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
     3342 #endif
     3343 }
     3344 
     3345   FLAG_SET_DEFAULT(UseLargePages, os::large_page_init());
     3346 
     3347   // Setup Windows Exceptions
     3348 
     3349   // On Itanium systems, Structured Exception Handling does not
     3350   // work since stack frames must be walkable by the OS.  Since
     3351   // much of our code is dynamically generated, and we do not have
     3352   // proper unwind .xdata sections, the system simply exits
     3353   // rather than delivering the exception.  To work around
     3354   // this we use VectorExceptions instead.
     3355 #ifdef _WIN64
     3356   if (UseVectoredExceptions) {
     3357     topLevelVectoredExceptionHandler = AddVectoredExceptionHandler( 1, topLevelExceptionFilter);
     3358   }
     3359 #endif
     3360 
     3361   // for debugging float code generation bugs
     3362   if (ForceFloatExceptions) {
     3363 #ifndef  _WIN64
     3364     static long fp_control_word = 0;
     3365     __asm { fstcw fp_control_word }
     3366     // see Intel PPro Manual, Vol. 2, p 7-16
     3367     const long precision = 0x20;
     3368     const long underflow = 0x10;
     3369     const long overflow  = 0x08;
     3370     const long zero_div  = 0x04;
     3371     const long denorm    = 0x02;
     3372     const long invalid   = 0x01;
     3373     fp_control_word |= invalid;
     3374     __asm { fldcw fp_control_word }
     3375 #endif
     3376   }
     3377 
     3378   // Initialize HPI.
     3379   jint hpi_result = hpi::initialize();
     3380   if (hpi_result != JNI_OK) { return hpi_result; }
     3381 
     3382   // If stack_commit_size is 0, windows will reserve the default size,
     3383   // but only commit a small portion of it.
     3384   size_t stack_commit_size = round_to(ThreadStackSize*K, os::vm_page_size());
     3385   size_t default_reserve_size = os::win32::default_stack_size();
     3386   size_t actual_reserve_size = stack_commit_size;
     3387   if (stack_commit_size < default_reserve_size) {
     3388     // If stack_commit_size == 0, we want this too
     3389     actual_reserve_size = default_reserve_size;
     3390   }
     3391 
     3392   JavaThread::set_stack_size_at_create(stack_commit_size);
     3393 
     3394   // Calculate theoretical max. size of Threads to guard gainst artifical
     3395   // out-of-memory situations, where all available address-space has been
     3396   // reserved by thread stacks.
     3397   assert(actual_reserve_size != 0, "Must have a stack");
     3398 
     3399   // Calculate the thread limit when we should start doing Virtual Memory
     3400   // banging. Currently when the threads will have used all but 200Mb of space.
     3401   //
     3402   // TODO: consider performing a similar calculation for commit size instead
     3403   // as reserve size, since on a 64-bit platform we'll run into that more
     3404   // often than running out of virtual memory space.  We can use the
     3405   // lower value of the two calculations as the os_thread_limit.
     3406   size_t max_address_space = ((size_t)1 << (BitsPerWord - 1)) - (200 * K * K);
     3407   win32::_os_thread_limit = (intx)(max_address_space / actual_reserve_size);
     3408 
     3409   // at exit methods are called in the reverse order of their registration.
     3410   // there is no limit to the number of functions registered. atexit does
     3411   // not set errno.
     3412 
     3413   if (PerfAllowAtExitRegistration) {
     3414     // only register atexit functions if PerfAllowAtExitRegistration is set.
     3415     // atexit functions can be delayed until process exit time, which
     3416     // can be problematic for embedded VM situations. Embedded VMs should
     3417     // call DestroyJavaVM() to assure that VM resources are released.
     3418 
     3419     // note: perfMemory_exit_helper atexit function may be removed in
     3420     // the future if the appropriate cleanup code can be added to the
     3421     // VM_Exit VMOperation's doit method.
     3422     if (atexit(perfMemory_exit_helper) != 0) {
     3423       warning("os::init_2 atexit(perfMemory_exit_helper) failed");
     3424     }
     3425   }
     3426 
     3427   // initialize PSAPI or ToolHelp for fatal error handler
     3428   if (win32::is_nt()) _init_psapi();
     3429   else _init_toolhelp();
     3430 
     3431 #ifndef _WIN64
     3432   // Print something if NX is enabled (win32 on AMD64)
     3433   NOT_PRODUCT(if (PrintMiscellaneous && Verbose) nx_check_protection());
     3434 #endif
     3435 
     3436   // initialize thread priority policy
     3437   prio_init();
     3438 
     3439   if (UseNUMA && !ForceNUMA) {
     3440     UseNUMA = false; // Currently unsupported.
     3441   }
     3442 
     3443   return JNI_OK;
     3444 }
     3445 
     3446 void os::init_3(void) {
     3447   return;
     3448 }
     3449 
     3450 // Mark the polling page as unreadable
     3451 void os::make_polling_page_unreadable(void) {
     3452   DWORD old_status;
     3453   if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_NOACCESS, &old_status) )
     3454     fatal("Could not disable polling page");
     3455 };
     3456 
     3457 // Mark the polling page as readable
     3458 void os::make_polling_page_readable(void) {
     3459   DWORD old_status;
     3460   if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_READONLY, &old_status) )
     3461     fatal("Could not enable polling page");
     3462 };
     3463 
     3464 
     3465 int os::stat(const char *path, struct stat *sbuf) {
     3466   char pathbuf[MAX_PATH];
     3467   if (strlen(path) > MAX_PATH - 1) {
     3468     errno = ENAMETOOLONG;
     3469     return -1;
     3470   }
     3471   hpi::native_path(strcpy(pathbuf, path));
     3472   int ret = ::stat(pathbuf, sbuf);
     3473   if (sbuf != NULL && UseUTCFileTimestamp) {
     3474     // Fix for 6539723.  st_mtime returned from stat() is dependent on
     3475     // the system timezone and so can return different values for the
     3476     // same file if/when daylight savings time changes.  This adjustment
     3477     // makes sure the same timestamp is returned regardless of the TZ.
     3478     //
     3479     // See:
     3480     // http://msdn.microsoft.com/library/
     3481     //   default.asp?url=/library/en-us/sysinfo/base/
     3482     //   time_zone_information_str.asp
     3483     // and
     3484     // http://msdn.microsoft.com/library/default.asp?url=
     3485     //   /library/en-us/sysinfo/base/settimezoneinformation.asp
     3486     //
     3487     // NOTE: there is a insidious bug here:  If the timezone is changed
     3488     // after the call to stat() but before 'GetTimeZoneInformation()', then
     3489     // the adjustment we do here will be wrong and we'll return the wrong
     3490     // value (which will likely end up creating an invalid class data
     3491     // archive).  Absent a better API for this, or some time zone locking
     3492     // mechanism, we'll have to live with this risk.
     3493     TIME_ZONE_INFORMATION tz;
     3494     DWORD tzid = GetTimeZoneInformation(&tz);
     3495     int daylightBias =
     3496       (tzid == TIME_ZONE_ID_DAYLIGHT) ?  tz.DaylightBias : tz.StandardBias;
     3497     sbuf->st_mtime += (tz.Bias + daylightBias) * 60;
     3498   }
     3499   return ret;
     3500 }
     3501 
     3502 
     3503 #define FT2INT64(ft) \
     3504   ((jlong)((jlong)(ft).dwHighDateTime << 32 | (julong)(ft).dwLowDateTime))
     3505 
     3506 
     3507 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
     3508 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
     3509 // of a thread.
     3510 //
     3511 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
     3512 // the fast estimate available on the platform.
     3513 
     3514 // current_thread_cpu_time() is not optimized for Windows yet
     3515 jlong os::current_thread_cpu_time() {
     3516   // return user + sys since the cost is the same
     3517   return os::thread_cpu_time(Thread::current(), true /* user+sys */);
     3518 }
     3519 
     3520 jlong os::thread_cpu_time(Thread* thread) {
     3521   // consistent with what current_thread_cpu_time() returns.
     3522   return os::thread_cpu_time(thread, true /* user+sys */);
     3523 }
     3524 
     3525 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
     3526   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
     3527 }
     3528 
     3529 jlong os::thread_cpu_time(Thread* thread, bool user_sys_cpu_time) {
     3530   // This code is copy from clasic VM -> hpi::sysThreadCPUTime
     3531   // If this function changes, os::is_thread_cpu_time_supported() should too
     3532   if (os::win32::is_nt()) {
     3533     FILETIME CreationTime;
     3534     FILETIME ExitTime;
     3535     FILETIME KernelTime;
     3536     FILETIME UserTime;
     3537 
     3538     if ( GetThreadTimes(thread->osthread()->thread_handle(),
     3539                     &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0)
     3540       return -1;
     3541     else
     3542       if (user_sys_cpu_time) {
     3543         return (FT2INT64(UserTime) + FT2INT64(KernelTime)) * 100;
     3544       } else {
     3545         return FT2INT64(UserTime) * 100;
     3546       }
     3547   } else {
     3548     return (jlong) timeGetTime() * 1000000;
     3549   }
     3550 }
     3551 
     3552 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
     3553   info_ptr->max_value = ALL_64_BITS;        // the max value -- all 64 bits
     3554   info_ptr->may_skip_backward = false;      // GetThreadTimes returns absolute time
     3555   info_ptr->may_skip_forward = false;       // GetThreadTimes returns absolute time
     3556   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;   // user+system time is returned
     3557 }
     3558 
     3559 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
     3560   info_ptr->max_value = ALL_64_BITS;        // the max value -- all 64 bits
     3561   info_ptr->may_skip_backward = false;      // GetThreadTimes returns absolute time
     3562   info_ptr->may_skip_forward = false;       // GetThreadTimes returns absolute time
     3563   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;   // user+system time is returned
     3564 }
     3565 
     3566 bool os::is_thread_cpu_time_supported() {
     3567   // see os::thread_cpu_time
     3568   if (os::win32::is_nt()) {
     3569     FILETIME CreationTime;
     3570     FILETIME ExitTime;
     3571     FILETIME KernelTime;
     3572     FILETIME UserTime;
     3573 
     3574     if ( GetThreadTimes(GetCurrentThread(),
     3575                     &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0)
     3576       return false;
     3577     else
     3578       return true;
     3579   } else {
     3580     return false;
     3581   }
     3582 }
     3583 
     3584 // Windows does't provide a loadavg primitive so this is stubbed out for now.
     3585 // It does have primitives (PDH API) to get CPU usage and run queue length.
     3586 // "\\Processor(_Total)\\% Processor Time", "\\System\\Processor Queue Length"
     3587 // If we wanted to implement loadavg on Windows, we have a few options:
     3588 //
     3589 // a) Query CPU usage and run queue length and "fake" an answer by
     3590 //    returning the CPU usage if it's under 100%, and the run queue
     3591 //    length otherwise.  It turns out that querying is pretty slow
     3592 //    on Windows, on the order of 200 microseconds on a fast machine.
     3593 //    Note that on the Windows the CPU usage value is the % usage
     3594 //    since the last time the API was called (and the first call
     3595 //    returns 100%), so we'd have to deal with that as well.
     3596 //
     3597 // b) Sample the "fake" answer using a sampling thread and store
     3598 //    the answer in a global variable.  The call to loadavg would
     3599 //    just return the value of the global, avoiding the slow query.
     3600 //
     3601 // c) Sample a better answer using exponential decay to smooth the
     3602 //    value.  This is basically the algorithm used by UNIX kernels.
     3603 //
     3604 // Note that sampling thread starvation could affect both (b) and (c).
     3605 int os::loadavg(double loadavg[], int nelem) {
     3606   return -1;
     3607 }
     3608 
     3609 
     3610 // DontYieldALot=false by default: dutifully perform all yields as requested by JVM_Yield()
     3611 bool os::dont_yield() {
     3612   return DontYieldALot;
     3613 }
     3614 
     3615 // Is a (classpath) directory empty?
     3616 bool os::dir_is_empty(const char* path) {
     3617   WIN32_FIND_DATA fd;
     3618   HANDLE f = FindFirstFile(path, &fd);
     3619   if (f == INVALID_HANDLE_VALUE) {
     3620     return true;
     3621   }
     3622   FindClose(f);
     3623   return false;
     3624 }
     3625 
     3626 // create binary file, rewriting existing file if required
     3627 int os::create_binary_file(const char* path, bool rewrite_existing) {
     3628   int oflags = _O_CREAT | _O_WRONLY | _O_BINARY;
     3629   if (!rewrite_existing) {
     3630     oflags |= _O_EXCL;
     3631   }
     3632   return ::open(path, oflags, _S_IREAD | _S_IWRITE);
     3633 }
     3634 
     3635 // return current position of file pointer
     3636 jlong os::current_file_offset(int fd) {
     3637   return (jlong)::_lseeki64(fd, (__int64)0L, SEEK_CUR);
     3638 }
     3639 
     3640 // move file pointer to the specified offset
     3641 jlong os::seek_to_file_offset(int fd, jlong offset) {
     3642   return (jlong)::_lseeki64(fd, (__int64)offset, SEEK_SET);
     3643 }
     3644 
     3645 
     3646 // Map a block of memory.
     3647 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
     3648                      char *addr, size_t bytes, bool read_only,
     3649                      bool allow_exec) {
     3650   HANDLE hFile;
     3651   char* base;
     3652 
     3653   hFile = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, NULL,
     3654                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     3655   if (hFile == NULL) {
     3656     if (PrintMiscellaneous && Verbose) {
     3657       DWORD err = GetLastError();
     3658       tty->print_cr("CreateFile() failed: GetLastError->%ld.");
     3659     }
     3660     return NULL;
     3661   }
     3662 
     3663   if (allow_exec) {
     3664     // CreateFileMapping/MapViewOfFileEx can't map executable memory
     3665     // unless it comes from a PE image (which the shared archive is not.)
     3666     // Even VirtualProtect refuses to give execute access to mapped memory
     3667     // that was not previously executable.
     3668     //
     3669     // Instead, stick the executable region in anonymous memory.  Yuck.
     3670     // Penalty is that ~4 pages will not be shareable - in the future
     3671     // we might consider DLLizing the shared archive with a proper PE
     3672     // header so that mapping executable + sharing is possible.
     3673 
     3674     base = (char*) VirtualAlloc(addr, bytes, MEM_COMMIT | MEM_RESERVE,
     3675                                 PAGE_READWRITE);
     3676     if (base == NULL) {
     3677       if (PrintMiscellaneous && Verbose) {
     3678         DWORD err = GetLastError();
     3679         tty->print_cr("VirtualAlloc() failed: GetLastError->%ld.", err);
     3680       }
     3681       CloseHandle(hFile);
     3682       return NULL;
     3683     }
     3684 
     3685     DWORD bytes_read;
     3686     OVERLAPPED overlapped;
     3687     overlapped.Offset = (DWORD)file_offset;
     3688     overlapped.OffsetHigh = 0;
     3689     overlapped.hEvent = NULL;
     3690     // ReadFile guarantees that if the return value is true, the requested
     3691     // number of bytes were read before returning.
     3692     bool res = ReadFile(hFile, base, (DWORD)bytes, &bytes_read, &overlapped) != 0;
     3693     if (!res) {
     3694       if (PrintMiscellaneous && Verbose) {
     3695         DWORD err = GetLastError();
     3696         tty->print_cr("ReadFile() failed: GetLastError->%ld.", err);
     3697       }
     3698       release_memory(base, bytes);
     3699       CloseHandle(hFile);
     3700       return NULL;
     3701     }
     3702   } else {
     3703     HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0,
     3704                                     NULL /*file_name*/);
     3705     if (hMap == NULL) {
     3706       if (PrintMiscellaneous && Verbose) {
     3707         DWORD err = GetLastError();
     3708         tty->print_cr("CreateFileMapping() failed: GetLastError->%ld.");
     3709       }
     3710       CloseHandle(hFile);
     3711       return NULL;
     3712     }
     3713 
     3714     DWORD access = read_only ? FILE_MAP_READ : FILE_MAP_COPY;
     3715     base = (char*)MapViewOfFileEx(hMap, access, 0, (DWORD)file_offset,
     3716                                   (DWORD)bytes, addr);
     3717     if (base == NULL) {
     3718       if (PrintMiscellaneous && Verbose) {
     3719         DWORD err = GetLastError();
     3720         tty->print_cr("MapViewOfFileEx() failed: GetLastError->%ld.", err);
     3721       }
     3722       CloseHandle(hMap);
     3723       CloseHandle(hFile);
     3724       return NULL;
     3725     }
     3726 
     3727     if (CloseHandle(hMap) == 0) {
     3728       if (PrintMiscellaneous && Verbose) {
     3729         DWORD err = GetLastError();
     3730         tty->print_cr("CloseHandle(hMap) failed: GetLastError->%ld.", err);
     3731       }
     3732       CloseHandle(hFile);
     3733       return base;
     3734     }
     3735   }
     3736 
     3737   if (allow_exec) {
     3738     DWORD old_protect;
     3739     DWORD exec_access = read_only ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE;
     3740     bool res = VirtualProtect(base, bytes, exec_access, &old_protect) != 0;
     3741 
     3742     if (!res) {
     3743       if (PrintMiscellaneous && Verbose) {
     3744         DWORD err = GetLastError();
     3745         tty->print_cr("VirtualProtect() failed: GetLastError->%ld.", err);
     3746       }
     3747       // Don't consider this a hard error, on IA32 even if the
     3748       // VirtualProtect fails, we should still be able to execute
     3749       CloseHandle(hFile);
     3750       return base;
     3751     }
     3752   }
     3753 
     3754   if (CloseHandle(hFile) == 0) {
     3755     if (PrintMiscellaneous && Verbose) {
     3756       DWORD err = GetLastError();
     3757       tty->print_cr("CloseHandle(hFile) failed: GetLastError->%ld.", err);
     3758     }
     3759     return base;
     3760   }
     3761 
     3762   return base;
     3763 }
     3764 
     3765 
     3766 // Remap a block of memory.
     3767 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
     3768                        char *addr, size_t bytes, bool read_only,
     3769                        bool allow_exec) {
     3770   // This OS does not allow existing memory maps to be remapped so we
     3771   // have to unmap the memory before we remap it.
     3772   if (!os::unmap_memory(addr, bytes)) {
     3773     return NULL;
     3774   }
     3775 
     3776   // There is a very small theoretical window between the unmap_memory()
     3777   // call above and the map_memory() call below where a thread in native
     3778   // code may be able to access an address that is no longer mapped.
     3779 
     3780   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
     3781                         allow_exec);
     3782 }
     3783 
     3784 
     3785 // Unmap a block of memory.
     3786 // Returns true=success, otherwise false.
     3787 
     3788 bool os::unmap_memory(char* addr, size_t bytes) {
     3789   BOOL result = UnmapViewOfFile(addr);
     3790   if (result == 0) {
     3791     if (PrintMiscellaneous && Verbose) {
     3792       DWORD err = GetLastError();
     3793       tty->print_cr("UnmapViewOfFile() failed: GetLastError->%ld.", err);
     3794     }
     3795     return false;
     3796   }
     3797   return true;
     3798 }
     3799 
     3800 void os::pause() {
     3801   char filename[MAX_PATH];
     3802   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
     3803     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
     3804   } else {
     3805     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
     3806   }
     3807 
     3808   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
     3809   if (fd != -1) {
     3810     struct stat buf;
     3811     close(fd);
     3812     while (::stat(filename, &buf) == 0) {
     3813       Sleep(100);
     3814     }
     3815   } else {
     3816     jio_fprintf(stderr,
     3817       "Could not open pause file '%s', continuing immediately.\n", filename);
     3818   }
     3819 }
     3820 
     3821 // An Event wraps a win32 "CreateEvent" kernel handle.
     3822 //
     3823 // We have a number of choices regarding "CreateEvent" win32 handle leakage:
     3824 //
     3825 // 1:  When a thread dies return the Event to the EventFreeList, clear the ParkHandle
     3826 //     field, and call CloseHandle() on the win32 event handle.  Unpark() would
     3827 //     need to be modified to tolerate finding a NULL (invalid) win32 event handle.
     3828 //     In addition, an unpark() operation might fetch the handle field, but the
     3829 //     event could recycle between the fetch and the SetEvent() operation.
     3830 //     SetEvent() would either fail because the handle was invalid, or inadvertently work,
     3831 //     as the win32 handle value had been recycled.  In an ideal world calling SetEvent()
     3832 //     on an stale but recycled handle would be harmless, but in practice this might
     3833 //     confuse other non-Sun code, so it's not a viable approach.
     3834 //
     3835 // 2:  Once a win32 event handle is associated with an Event, it remains associated
     3836 //     with the Event.  The event handle is never closed.  This could be construed
     3837 //     as handle leakage, but only up to the maximum # of threads that have been extant
     3838 //     at any one time.  This shouldn't be an issue, as windows platforms typically
     3839 //     permit a process to have hundreds of thousands of open handles.
     3840 //
     3841 // 3:  Same as (1), but periodically, at stop-the-world time, rundown the EventFreeList
     3842 //     and release unused handles.
     3843 //
     3844 // 4:  Add a CRITICAL_SECTION to the Event to protect LD+SetEvent from LD;ST(null);CloseHandle.
     3845 //     It's not clear, however, that we wouldn't be trading one type of leak for another.
     3846 //
     3847 // 5.  Use an RCU-like mechanism (Read-Copy Update).
     3848 //     Or perhaps something similar to Maged Michael's "Hazard pointers".
     3849 //
     3850 // We use (2).
     3851 //
     3852 // TODO-FIXME:
     3853 // 1.  Reconcile Doug's JSR166 j.u.c park-unpark with the objectmonitor implementation.
     3854 // 2.  Consider wrapping the WaitForSingleObject(Ex) calls in SEH try/finally blocks
     3855 //     to recover from (or at least detect) the dreaded Windows 841176 bug.
     3856 // 3.  Collapse the interrupt_event, the JSR166 parker event, and the objectmonitor ParkEvent
     3857 //     into a single win32 CreateEvent() handle.
     3858 //
     3859 // _Event transitions in park()
     3860 //   -1 => -1 : illegal
     3861 //    1 =>  0 : pass - return immediately
     3862 //    0 => -1 : block
     3863 //
     3864 // _Event serves as a restricted-range semaphore :
     3865 //    -1 : thread is blocked
     3866 //     0 : neutral  - thread is running or ready
     3867 //     1 : signaled - thread is running or ready
     3868 //
     3869 // Another possible encoding of _Event would be
     3870 // with explicit "PARKED" and "SIGNALED" bits.
     3871 
     3872 int os::PlatformEvent::park (jlong Millis) {
     3873     guarantee (_ParkHandle != NULL , "Invariant") ;
     3874     guarantee (Millis > 0          , "Invariant") ;
     3875     int v ;
     3876 
     3877     // CONSIDER: defer assigning a CreateEvent() handle to the Event until
     3878     // the initial park() operation.
     3879 
     3880     for (;;) {
     3881         v = _Event ;
     3882         if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
     3883     }
     3884     guarantee ((v == 0) || (v == 1), "invariant") ;
     3885     if (v != 0) return OS_OK ;
     3886 
     3887     // Do this the hard way by blocking ...
     3888     // TODO: consider a brief spin here, gated on the success of recent
     3889     // spin attempts by this thread.
     3890     //
     3891     // We decompose long timeouts into series of shorter timed waits.
     3892     // Evidently large timo values passed in WaitForSingleObject() are problematic on some
     3893     // versions of Windows.  See EventWait() for details.  This may be superstition.  Or not.
     3894     // We trust the WAIT_TIMEOUT indication and don't track the elapsed wait time
     3895     // with os::javaTimeNanos().  Furthermore, we assume that spurious returns from
     3896     // ::WaitForSingleObject() caused by latent ::setEvent() operations will tend
     3897     // to happen early in the wait interval.  Specifically, after a spurious wakeup (rv ==
     3898     // WAIT_OBJECT_0 but _Event is still < 0) we don't bother to recompute Millis to compensate
     3899     // for the already waited time.  This policy does not admit any new outcomes.
     3900     // In the future, however, we might want to track the accumulated wait time and
     3901     // adjust Millis accordingly if we encounter a spurious wakeup.
     3902 
     3903     const int MAXTIMEOUT = 0x10000000 ;
     3904     DWORD rv = WAIT_TIMEOUT ;
     3905     while (_Event < 0 && Millis > 0) {
     3906        DWORD prd = Millis ;     // set prd = MAX (Millis, MAXTIMEOUT)
     3907        if (Millis > MAXTIMEOUT) {
     3908           prd = MAXTIMEOUT ;
     3909        }
     3910        rv = ::WaitForSingleObject (_ParkHandle, prd) ;
     3911        assert (rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed") ;
     3912        if (rv == WAIT_TIMEOUT) {
     3913            Millis -= prd ;
     3914        }
     3915     }
     3916     v = _Event ;
     3917     _Event = 0 ;
     3918     OrderAccess::fence() ;
     3919     // If we encounter a nearly simultanous timeout expiry and unpark()
     3920     // we return OS_OK indicating we awoke via unpark().
     3921     // Implementor's license -- returning OS_TIMEOUT would be equally valid, however.
     3922     return (v >= 0) ? OS_OK : OS_TIMEOUT ;
     3923 }
     3924 
     3925 void os::PlatformEvent::park () {
     3926     guarantee (_ParkHandle != NULL, "Invariant") ;
     3927     // Invariant: Only the thread associated with the Event/PlatformEvent
     3928     // may call park().
     3929     int v ;
     3930     for (;;) {
     3931         v = _Event ;
     3932         if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
     3933     }
     3934     guarantee ((v == 0) || (v == 1), "invariant") ;
     3935     if (v != 0) return ;
     3936 
     3937     // Do this the hard way by blocking ...
     3938     // TODO: consider a brief spin here, gated on the success of recent
     3939     // spin attempts by this thread.
     3940     while (_Event < 0) {
     3941        DWORD rv = ::WaitForSingleObject (_ParkHandle, INFINITE) ;
     3942        assert (rv == WAIT_OBJECT_0, "WaitForSingleObject failed") ;
     3943     }
     3944 
     3945     // Usually we'll find _Event == 0 at this point, but as
     3946     // an optional optimization we clear it, just in case can
     3947     // multiple unpark() operations drove _Event up to 1.
     3948     _Event = 0 ;
     3949     OrderAccess::fence() ;
     3950     guarantee (_Event >= 0, "invariant") ;
     3951 }
     3952 
     3953 void os::PlatformEvent::unpark() {
     3954   guarantee (_ParkHandle != NULL, "Invariant") ;
     3955   int v ;
     3956   for (;;) {
     3957       v = _Event ;      // Increment _Event if it's < 1.
     3958       if (v > 0) {
     3959          // If it's already signaled just return.
     3960          // The LD of _Event could have reordered or be satisfied
     3961          // by a read-aside from this processor's write buffer.
     3962          // To avoid problems execute a barrier and then
     3963          // ratify the value.  A degenerate CAS() would also work.
     3964          // Viz., CAS (v+0, &_Event, v) == v).
     3965          OrderAccess::fence() ;
     3966          if (_Event == v) return ;
     3967          continue ;
     3968       }
     3969       if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
     3970   }
     3971   if (v < 0) {
     3972      ::SetEvent (_ParkHandle) ;
     3973   }
     3974 }
     3975 
     3976 
     3977 // JSR166
     3978 // -------------------------------------------------------
     3979 
     3980 /*
     3981  * The Windows implementation of Park is very straightforward: Basic
     3982  * operations on Win32 Events turn out to have the right semantics to
     3983  * use them directly. We opportunistically resuse the event inherited
     3984  * from Monitor.
     3985  */
     3986 
     3987 
     3988 void Parker::park(bool isAbsolute, jlong time) {
     3989   guarantee (_ParkEvent != NULL, "invariant") ;
     3990   // First, demultiplex/decode time arguments
     3991   if (time < 0) { // don't wait
     3992     return;
     3993   }
     3994   else if (time == 0) {
     3995     time = INFINITE;
     3996   }
     3997   else if  (isAbsolute) {
     3998     time -= os::javaTimeMillis(); // convert to relative time
     3999     if (time <= 0) // already elapsed
     4000       return;
     4001   }
     4002   else { // relative
     4003     time /= 1000000; // Must coarsen from nanos to millis
     4004     if (time == 0)   // Wait for the minimal time unit if zero
     4005       time = 1;
     4006   }
     4007 
     4008   JavaThread* thread = (JavaThread*)(Thread::current());
     4009   assert(thread->is_Java_thread(), "Must be JavaThread");
     4010   JavaThread *jt = (JavaThread *)thread;
     4011 
     4012   // Don't wait if interrupted or already triggered
     4013   if (Thread::is_interrupted(thread, false) ||
     4014     WaitForSingleObject(_ParkEvent, 0) == WAIT_OBJECT_0) {
     4015     ResetEvent(_ParkEvent);
     4016     return;
     4017   }
     4018   else {
     4019     ThreadBlockInVM tbivm(jt);
     4020     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
     4021     jt->set_suspend_equivalent();
     4022 
     4023     WaitForSingleObject(_ParkEvent,  time);
     4024     ResetEvent(_ParkEvent);
     4025 
     4026     // If externally suspended while waiting, re-suspend
     4027     if (jt->handle_special_suspend_equivalent_condition()) {
     4028       jt->java_suspend_self();
     4029     }
     4030   }
     4031 }
     4032 
     4033 void Parker::unpark() {
     4034   guarantee (_ParkEvent != NULL, "invariant") ;
     4035   SetEvent(_ParkEvent);
     4036 }
     4037 
     4038 // Run the specified command in a separate process. Return its exit value,
     4039 // or -1 on failure (e.g. can't create a new process).
     4040 int os::fork_and_exec(char* cmd) {
     4041   STARTUPINFO si;
     4042   PROCESS_INFORMATION pi;
     4043 
     4044   memset(&si, 0, sizeof(si));
     4045   si.cb = sizeof(si);
     4046   memset(&pi, 0, sizeof(pi));
     4047   BOOL rslt = CreateProcess(NULL,   // executable name - use command line
     4048                             cmd,    // command line
     4049                             NULL,   // process security attribute
     4050                             NULL,   // thread security attribute
     4051                             TRUE,   // inherits system handles
     4052                             0,      // no creation flags
     4053                             NULL,   // use parent's environment block
     4054                             NULL,   // use parent's starting directory
     4055                             &si,    // (in) startup information
     4056                             &pi);   // (out) process information
     4057 
     4058   if (rslt) {
     4059     // Wait until child process exits.
     4060     WaitForSingleObject(pi.hProcess, INFINITE);
     4061 
     4062     DWORD exit_code;
     4063     GetExitCodeProcess(pi.hProcess, &exit_code);
     4064 
     4065     // Close process and thread handles.
     4066     CloseHandle(pi.hProcess);
     4067     CloseHandle(pi.hThread);
     4068 
     4069     return (int)exit_code;
     4070   } else {
     4071     return -1;
     4072   }
     4073 }
     4074 
     4075 //--------------------------------------------------------------------------------------------------
     4076 // Non-product code
     4077 
     4078 static int mallocDebugIntervalCounter = 0;
     4079 static int mallocDebugCounter = 0;
     4080 bool os::check_heap(bool force) {
     4081   if (++mallocDebugCounter < MallocVerifyStart && !force) return true;
     4082   if (++mallocDebugIntervalCounter >= MallocVerifyInterval || force) {
     4083     // Note: HeapValidate executes two hardware breakpoints when it finds something
     4084     // wrong; at these points, eax contains the address of the offending block (I think).
     4085     // To get to the exlicit error message(s) below, just continue twice.
     4086     HANDLE heap = GetProcessHeap();
     4087     { HeapLock(heap);
     4088       PROCESS_HEAP_ENTRY phe;
     4089       phe.lpData = NULL;
     4090       while (HeapWalk(heap, &phe) != 0) {
     4091         if ((phe.wFlags & PROCESS_HEAP_ENTRY_BUSY) &&
     4092             !HeapValidate(heap, 0, phe.lpData)) {
     4093           tty->print_cr("C heap has been corrupted (time: %d allocations)", mallocDebugCounter);
     4094           tty->print_cr("corrupted block near address %#x, length %d", phe.lpData, phe.cbData);
     4095           fatal("corrupted C heap");
     4096         }
     4097       }
     4098       int err = GetLastError();
     4099       if (err != ERROR_NO_MORE_ITEMS && err != ERROR_CALL_NOT_IMPLEMENTED) {
     4100         fatal(err_msg("heap walk aborted with error %d", err));
     4101       }
     4102       HeapUnlock(heap);
     4103     }
     4104     mallocDebugIntervalCounter = 0;
     4105   }
     4106   return true;
     4107 }
     4108 
     4109 
     4110 bool os::find(address addr, outputStream* st) {
     4111   // Nothing yet
     4112   return false;
     4113 }
     4114 
     4115 LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) {
     4116   DWORD exception_code = e->ExceptionRecord->ExceptionCode;
     4117 
     4118   if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) {
     4119     JavaThread* thread = (JavaThread*)ThreadLocalStorage::get_thread_slow();
     4120     PEXCEPTION_RECORD exceptionRecord = e->ExceptionRecord;
     4121     address addr = (address) exceptionRecord->ExceptionInformation[1];
     4122 
     4123     if (os::is_memory_serialize_page(thread, addr))
     4124       return EXCEPTION_CONTINUE_EXECUTION;
     4125   }
     4126 
     4127   return EXCEPTION_CONTINUE_SEARCH;
     4128 }
     4129 
     4130 static int getLastErrorString(char *buf, size_t len)
     4131 {
     4132     long errval;
     4133 
     4134     if ((errval = GetLastError()) != 0)
     4135     {
     4136       /* DOS error */
     4137       size_t n = (size_t)FormatMessage(
     4138             FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
     4139             NULL,
     4140             errval,
     4141             0,
     4142             buf,
     4143             (DWORD)len,
     4144             NULL);
     4145       if (n > 3) {
     4146         /* Drop final '.', CR, LF */
     4147         if (buf[n - 1] == '\n') n--;
     4148         if (buf[n - 1] == '\r') n--;
     4149         if (buf[n - 1] == '.') n--;
     4150         buf[n] = '\0';
     4151       }
     4152       return (int)n;
     4153     }
     4154 
     4155     if (errno != 0)
     4156     {
     4157       /* C runtime error that has no corresponding DOS error code */
     4158       const char *s = strerror(errno);
     4159       size_t n = strlen(s);
     4160       if (n >= len) n = len - 1;
     4161       strncpy(buf, s, n);
     4162       buf[n] = '\0';
     4163       return (int)n;
     4164     }
     4165     return 0;
     4166 }
     4167 
     4168 
     4169 // We don't build a headless jre for Windows
     4170 bool os::is_headless_jre() { return false; }
     4171