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