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