1 /*
   2  * Copyright (c) 1997, 2014, 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::getenv(const char* name, char* buffer, int len) {
 157   int result = GetEnvironmentVariable(name, buffer, len);
 158   return result > 0 && result < len;
 159 }
 160 
 161 bool os::unsetenv(const char* name) {
 162   assert(name != NULL, "Null pointer");
 163   return (SetEnvironmentVariable(name, NULL) == TRUE);
 164 }
 165 
 166 // No setuid programs under Windows.
 167 bool os::have_special_privileges() {
 168   return false;
 169 }
 170 
 171 
 172 // This method is  a periodic task to check for misbehaving JNI applications
 173 // under CheckJNI, we can add any periodic checks here.
 174 // For Windows at the moment does nothing
 175 void os::run_periodic_checks() {
 176   return;
 177 }
 178 
 179 // previous UnhandledExceptionFilter, if there is one
 180 static LPTOP_LEVEL_EXCEPTION_FILTER prev_uef_handler = NULL;
 181 
 182 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo);
 183 
 184 void os::init_system_properties_values() {
 185   // sysclasspath, java_home, dll_dir
 186   {
 187     char *home_path;
 188     char *dll_path;
 189     char *pslash;
 190     char *bin = "\\bin";
 191     char home_dir[MAX_PATH];
 192 
 193     if (!getenv("_ALT_JAVA_HOME_DIR", home_dir, MAX_PATH)) {
 194       os::jvm_path(home_dir, sizeof(home_dir));
 195       // Found the full path to jvm.dll.
 196       // Now cut the path to <java_home>/jre if we can.
 197       *(strrchr(home_dir, '\\')) = '\0';  // get rid of \jvm.dll
 198       pslash = strrchr(home_dir, '\\');
 199       if (pslash != NULL) {
 200         *pslash = '\0';                   // get rid of \{client|server}
 201         pslash = strrchr(home_dir, '\\');
 202         if (pslash != NULL) {
 203           *pslash = '\0';                 // get rid of \bin
 204         }
 205       }
 206     }
 207 
 208     home_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + 1, mtInternal);
 209     if (home_path == NULL) {
 210       return;
 211     }
 212     strcpy(home_path, home_dir);
 213     Arguments::set_java_home(home_path);
 214     FREE_C_HEAP_ARRAY(char, home_path, mtInternal);
 215 
 216     dll_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + strlen(bin) + 1,
 217                                 mtInternal);
 218     if (dll_path == NULL) {
 219       return;
 220     }
 221     strcpy(dll_path, home_dir);
 222     strcat(dll_path, bin);
 223     Arguments::set_dll_dir(dll_path);
 224     FREE_C_HEAP_ARRAY(char, dll_path, mtInternal);
 225 
 226     if (!set_boot_path('\\', ';')) {
 227       return;
 228     }
 229   }
 230 
 231 // library_path
 232 #define EXT_DIR "\\lib\\ext"
 233 #define BIN_DIR "\\bin"
 234 #define PACKAGE_DIR "\\Sun\\Java"
 235   {
 236     // Win32 library search order (See the documentation for LoadLibrary):
 237     //
 238     // 1. The directory from which application is loaded.
 239     // 2. The system wide Java Extensions directory (Java only)
 240     // 3. System directory (GetSystemDirectory)
 241     // 4. Windows directory (GetWindowsDirectory)
 242     // 5. The PATH environment variable
 243     // 6. The current directory
 244 
 245     char *library_path;
 246     char tmp[MAX_PATH];
 247     char *path_str = ::getenv("PATH");
 248 
 249     library_path = NEW_C_HEAP_ARRAY(char, MAX_PATH * 5 + sizeof(PACKAGE_DIR) +
 250                                     sizeof(BIN_DIR) + (path_str ? strlen(path_str) : 0) + 10, mtInternal);
 251 
 252     library_path[0] = '\0';
 253 
 254     GetModuleFileName(NULL, tmp, sizeof(tmp));
 255     *(strrchr(tmp, '\\')) = '\0';
 256     strcat(library_path, tmp);
 257 
 258     GetWindowsDirectory(tmp, sizeof(tmp));
 259     strcat(library_path, ";");
 260     strcat(library_path, tmp);
 261     strcat(library_path, PACKAGE_DIR BIN_DIR);
 262 
 263     GetSystemDirectory(tmp, sizeof(tmp));
 264     strcat(library_path, ";");
 265     strcat(library_path, tmp);
 266 
 267     GetWindowsDirectory(tmp, sizeof(tmp));
 268     strcat(library_path, ";");
 269     strcat(library_path, tmp);
 270 
 271     if (path_str) {
 272       strcat(library_path, ";");
 273       strcat(library_path, path_str);
 274     }
 275 
 276     strcat(library_path, ";.");
 277 
 278     Arguments::set_library_path(library_path);
 279     FREE_C_HEAP_ARRAY(char, library_path, mtInternal);
 280   }
 281 
 282   // Default extensions directory
 283   {
 284     char path[MAX_PATH];
 285     char buf[2 * MAX_PATH + 2 * sizeof(EXT_DIR) + sizeof(PACKAGE_DIR) + 1];
 286     GetWindowsDirectory(path, MAX_PATH);
 287     sprintf(buf, "%s%s;%s%s%s", Arguments::get_java_home(), EXT_DIR,
 288             path, PACKAGE_DIR, EXT_DIR);
 289     Arguments::set_ext_dirs(buf);
 290   }
 291   #undef EXT_DIR
 292   #undef BIN_DIR
 293   #undef PACKAGE_DIR
 294 
 295   // Default endorsed standards directory.
 296   {
 297 #define ENDORSED_DIR "\\lib\\endorsed"
 298     size_t len = strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR);
 299     char * buf = NEW_C_HEAP_ARRAY(char, len, mtInternal);
 300     sprintf(buf, "%s%s", Arguments::get_java_home(), ENDORSED_DIR);
 301     Arguments::set_endorsed_dirs(buf);
 302     // (Arguments::set_endorsed_dirs() calls SystemProperty::set_value(), which
 303     //  duplicates the input.)
 304     FREE_C_HEAP_ARRAY(char, buf, mtInternal);
 305 #undef ENDORSED_DIR
 306   }
 307 
 308 #ifndef _WIN64
 309   // set our UnhandledExceptionFilter and save any previous one
 310   prev_uef_handler = SetUnhandledExceptionFilter(Handle_FLT_Exception);
 311 #endif
 312 
 313   // Done
 314   return;
 315 }
 316 
 317 void os::breakpoint() {
 318   DebugBreak();
 319 }
 320 
 321 // Invoked from the BREAKPOINT Macro
 322 extern "C" void breakpoint() {
 323   os::breakpoint();
 324 }
 325 
 326 // RtlCaptureStackBackTrace Windows API may not exist prior to Windows XP.
 327 // So far, this method is only used by Native Memory Tracking, which is
 328 // only supported on Windows XP or later.
 329 //
 330 int os::get_native_stack(address* stack, int frames, int toSkip) {
 331 #ifdef _NMT_NOINLINE_
 332   toSkip++;
 333 #endif
 334   int captured = Kernel32Dll::RtlCaptureStackBackTrace(toSkip + 1, frames,
 335                                                        (PVOID*)stack, NULL);
 336   for (int index = captured; index < frames; index ++) {
 337     stack[index] = NULL;
 338   }
 339   return captured;
 340 }
 341 
 342 
 343 // os::current_stack_base()
 344 //
 345 //   Returns the base of the stack, which is the stack's
 346 //   starting address.  This function must be called
 347 //   while running on the stack of the thread being queried.
 348 
 349 address os::current_stack_base() {
 350   MEMORY_BASIC_INFORMATION minfo;
 351   address stack_bottom;
 352   size_t stack_size;
 353 
 354   VirtualQuery(&minfo, &minfo, sizeof(minfo));
 355   stack_bottom =  (address)minfo.AllocationBase;
 356   stack_size = minfo.RegionSize;
 357 
 358   // Add up the sizes of all the regions with the same
 359   // AllocationBase.
 360   while (1) {
 361     VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo));
 362     if (stack_bottom == (address)minfo.AllocationBase) {
 363       stack_size += minfo.RegionSize;
 364     } else {
 365       break;
 366     }
 367   }
 368 
 369 #ifdef _M_IA64
 370   // IA64 has memory and register stacks
 371   //
 372   // This is the stack layout you get on NT/IA64 if you specify 1MB stack limit
 373   // at thread creation (1MB backing store growing upwards, 1MB memory stack
 374   // growing downwards, 2MB summed up)
 375   //
 376   // ...
 377   // ------- top of stack (high address) -----
 378   // |
 379   // |      1MB
 380   // |      Backing Store (Register Stack)
 381   // |
 382   // |         / \
 383   // |          |
 384   // |          |
 385   // |          |
 386   // ------------------------ stack base -----
 387   // |      1MB
 388   // |      Memory Stack
 389   // |
 390   // |          |
 391   // |          |
 392   // |          |
 393   // |         \ /
 394   // |
 395   // ----- bottom of stack (low address) -----
 396   // ...
 397 
 398   stack_size = stack_size / 2;
 399 #endif
 400   return stack_bottom + stack_size;
 401 }
 402 
 403 size_t os::current_stack_size() {
 404   size_t sz;
 405   MEMORY_BASIC_INFORMATION minfo;
 406   VirtualQuery(&minfo, &minfo, sizeof(minfo));
 407   sz = (size_t)os::current_stack_base() - (size_t)minfo.AllocationBase;
 408   return sz;
 409 }
 410 
 411 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
 412   const struct tm* time_struct_ptr = localtime(clock);
 413   if (time_struct_ptr != NULL) {
 414     *res = *time_struct_ptr;
 415     return res;
 416   }
 417   return NULL;
 418 }
 419 
 420 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo);
 421 
 422 // Thread start routine for all new Java threads
 423 static unsigned __stdcall java_start(Thread* thread) {
 424   // Try to randomize the cache line index of hot stack frames.
 425   // This helps when threads of the same stack traces evict each other's
 426   // cache lines. The threads can be either from the same JVM instance, or
 427   // from different JVM instances. The benefit is especially true for
 428   // processors with hyperthreading technology.
 429   static int counter = 0;
 430   int pid = os::current_process_id();
 431   _alloca(((pid ^ counter++) & 7) * 128);
 432 
 433   OSThread* osthr = thread->osthread();
 434   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
 435 
 436   if (UseNUMA) {
 437     int lgrp_id = os::numa_get_group_id();
 438     if (lgrp_id != -1) {
 439       thread->set_lgrp_id(lgrp_id);
 440     }
 441   }
 442 
 443   // Diagnostic code to investigate JDK-6573254
 444   int res = 50115;  // non-java thread
 445   if (thread->is_Java_thread()) {
 446     res = 40115;    // java thread
 447   }
 448 
 449   // Install a win32 structured exception handler around every thread created
 450   // by VM, so VM can generate error dump when an exception occurred in non-
 451   // Java thread (e.g. VM thread).
 452   __try {
 453     thread->run();
 454   } __except(topLevelExceptionFilter(
 455                                      (_EXCEPTION_POINTERS*)_exception_info())) {
 456     // Nothing to do.
 457   }
 458 
 459   // One less thread is executing
 460   // When the VMThread gets here, the main thread may have already exited
 461   // which frees the CodeHeap containing the Atomic::add code
 462   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
 463     Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count);
 464   }
 465 
 466   // Thread must not return from exit_process_or_thread(), but if it does,
 467   // let it proceed to exit normally
 468   return (unsigned)os::win32::exit_process_or_thread(os::win32::EPT_THREAD, res);
 469 }
 470 
 471 static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle,
 472                                   int thread_id) {
 473   // Allocate the OSThread object
 474   OSThread* osthread = new OSThread(NULL, NULL);
 475   if (osthread == NULL) return NULL;
 476 
 477   // Initialize support for Java interrupts
 478   HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
 479   if (interrupt_event == NULL) {
 480     delete osthread;
 481     return NULL;
 482   }
 483   osthread->set_interrupt_event(interrupt_event);
 484 
 485   // Store info on the Win32 thread into the OSThread
 486   osthread->set_thread_handle(thread_handle);
 487   osthread->set_thread_id(thread_id);
 488 
 489   if (UseNUMA) {
 490     int lgrp_id = os::numa_get_group_id();
 491     if (lgrp_id != -1) {
 492       thread->set_lgrp_id(lgrp_id);
 493     }
 494   }
 495 
 496   // Initial thread state is INITIALIZED, not SUSPENDED
 497   osthread->set_state(INITIALIZED);
 498 
 499   return osthread;
 500 }
 501 
 502 
 503 bool os::create_attached_thread(JavaThread* thread) {
 504 #ifdef ASSERT
 505   thread->verify_not_published();
 506 #endif
 507   HANDLE thread_h;
 508   if (!DuplicateHandle(main_process, GetCurrentThread(), GetCurrentProcess(),
 509                        &thread_h, THREAD_ALL_ACCESS, false, 0)) {
 510     fatal("DuplicateHandle failed\n");
 511   }
 512   OSThread* osthread = create_os_thread(thread, thread_h,
 513                                         (int)current_thread_id());
 514   if (osthread == NULL) {
 515     return false;
 516   }
 517 
 518   // Initial thread state is RUNNABLE
 519   osthread->set_state(RUNNABLE);
 520 
 521   thread->set_osthread(osthread);
 522   return true;
 523 }
 524 
 525 bool os::create_main_thread(JavaThread* thread) {
 526 #ifdef ASSERT
 527   thread->verify_not_published();
 528 #endif
 529   if (_starting_thread == NULL) {
 530     _starting_thread = create_os_thread(thread, main_thread, main_thread_id);
 531     if (_starting_thread == NULL) {
 532       return false;
 533     }
 534   }
 535 
 536   // The primordial thread is runnable from the start)
 537   _starting_thread->set_state(RUNNABLE);
 538 
 539   thread->set_osthread(_starting_thread);
 540   return true;
 541 }
 542 
 543 // Allocate and initialize a new OSThread
 544 bool os::create_thread(Thread* thread, ThreadType thr_type,
 545                        size_t stack_size) {
 546   unsigned thread_id;
 547 
 548   // Allocate the OSThread object
 549   OSThread* osthread = new OSThread(NULL, NULL);
 550   if (osthread == NULL) {
 551     return false;
 552   }
 553 
 554   // Initialize support for Java interrupts
 555   HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
 556   if (interrupt_event == NULL) {
 557     delete osthread;
 558     return NULL;
 559   }
 560   osthread->set_interrupt_event(interrupt_event);
 561   osthread->set_interrupted(false);
 562 
 563   thread->set_osthread(osthread);
 564 
 565   if (stack_size == 0) {
 566     switch (thr_type) {
 567     case os::java_thread:
 568       // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
 569       if (JavaThread::stack_size_at_create() > 0) {
 570         stack_size = JavaThread::stack_size_at_create();
 571       }
 572       break;
 573     case os::compiler_thread:
 574       if (CompilerThreadStackSize > 0) {
 575         stack_size = (size_t)(CompilerThreadStackSize * K);
 576         break;
 577       } // else fall through:
 578         // use VMThreadStackSize if CompilerThreadStackSize is not defined
 579     case os::vm_thread:
 580     case os::pgc_thread:
 581     case os::cgc_thread:
 582     case os::watcher_thread:
 583       if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
 584       break;
 585     }
 586   }
 587 
 588   // Create the Win32 thread
 589   //
 590   // Contrary to what MSDN document says, "stack_size" in _beginthreadex()
 591   // does not specify stack size. Instead, it specifies the size of
 592   // initially committed space. The stack size is determined by
 593   // PE header in the executable. If the committed "stack_size" is larger
 594   // than default value in the PE header, the stack is rounded up to the
 595   // nearest multiple of 1MB. For example if the launcher has default
 596   // stack size of 320k, specifying any size less than 320k does not
 597   // affect the actual stack size at all, it only affects the initial
 598   // commitment. On the other hand, specifying 'stack_size' larger than
 599   // default value may cause significant increase in memory usage, because
 600   // not only the stack space will be rounded up to MB, but also the
 601   // entire space is committed upfront.
 602   //
 603   // Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION'
 604   // for CreateThread() that can treat 'stack_size' as stack size. However we
 605   // are not supposed to call CreateThread() directly according to MSDN
 606   // document because JVM uses C runtime library. The good news is that the
 607   // flag appears to work with _beginthredex() as well.
 608 
 609 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
 610   #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
 611 #endif
 612 
 613   HANDLE thread_handle =
 614     (HANDLE)_beginthreadex(NULL,
 615                            (unsigned)stack_size,
 616                            (unsigned (__stdcall *)(void*)) java_start,
 617                            thread,
 618                            CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
 619                            &thread_id);
 620   if (thread_handle == NULL) {
 621     // perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again
 622     // without the flag.
 623     thread_handle =
 624       (HANDLE)_beginthreadex(NULL,
 625                              (unsigned)stack_size,
 626                              (unsigned (__stdcall *)(void*)) java_start,
 627                              thread,
 628                              CREATE_SUSPENDED,
 629                              &thread_id);
 630   }
 631   if (thread_handle == NULL) {
 632     // Need to clean up stuff we've allocated so far
 633     CloseHandle(osthread->interrupt_event());
 634     thread->set_osthread(NULL);
 635     delete osthread;
 636     return NULL;
 637   }
 638 
 639   Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count);
 640 
 641   // Store info on the Win32 thread into the OSThread
 642   osthread->set_thread_handle(thread_handle);
 643   osthread->set_thread_id(thread_id);
 644 
 645   // Initial thread state is INITIALIZED, not SUSPENDED
 646   osthread->set_state(INITIALIZED);
 647 
 648   // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
 649   return true;
 650 }
 651 
 652 
 653 // Free Win32 resources related to the OSThread
 654 void os::free_thread(OSThread* osthread) {
 655   assert(osthread != NULL, "osthread not set");
 656   CloseHandle(osthread->thread_handle());
 657   CloseHandle(osthread->interrupt_event());
 658   delete osthread;
 659 }
 660 
 661 static jlong first_filetime;
 662 static jlong initial_performance_count;
 663 static jlong performance_frequency;
 664 
 665 
 666 jlong as_long(LARGE_INTEGER x) {
 667   jlong result = 0; // initialization to avoid warning
 668   set_high(&result, x.HighPart);
 669   set_low(&result, x.LowPart);
 670   return result;
 671 }
 672 
 673 
 674 jlong os::elapsed_counter() {
 675   LARGE_INTEGER count;
 676   if (win32::_has_performance_count) {
 677     QueryPerformanceCounter(&count);
 678     return as_long(count) - initial_performance_count;
 679   } else {
 680     FILETIME wt;
 681     GetSystemTimeAsFileTime(&wt);
 682     return (jlong_from(wt.dwHighDateTime, wt.dwLowDateTime) - first_filetime);
 683   }
 684 }
 685 
 686 
 687 jlong os::elapsed_frequency() {
 688   if (win32::_has_performance_count) {
 689     return performance_frequency;
 690   } else {
 691     // the FILETIME time is the number of 100-nanosecond intervals since January 1,1601.
 692     return 10000000;
 693   }
 694 }
 695 
 696 
 697 julong os::available_memory() {
 698   return win32::available_memory();
 699 }
 700 
 701 julong os::win32::available_memory() {
 702   // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
 703   // value if total memory is larger than 4GB
 704   MEMORYSTATUSEX ms;
 705   ms.dwLength = sizeof(ms);
 706   GlobalMemoryStatusEx(&ms);
 707 
 708   return (julong)ms.ullAvailPhys;
 709 }
 710 
 711 julong os::physical_memory() {
 712   return win32::physical_memory();
 713 }
 714 
 715 bool os::has_allocatable_memory_limit(julong* limit) {
 716   MEMORYSTATUSEX ms;
 717   ms.dwLength = sizeof(ms);
 718   GlobalMemoryStatusEx(&ms);
 719 #ifdef _LP64
 720   *limit = (julong)ms.ullAvailVirtual;
 721   return true;
 722 #else
 723   // Limit to 1400m because of the 2gb address space wall
 724   *limit = MIN2((julong)1400*M, (julong)ms.ullAvailVirtual);
 725   return true;
 726 #endif
 727 }
 728 
 729 // VC6 lacks DWORD_PTR
 730 #if _MSC_VER < 1300
 731 typedef UINT_PTR DWORD_PTR;
 732 #endif
 733 
 734 int os::active_processor_count() {
 735   DWORD_PTR lpProcessAffinityMask = 0;
 736   DWORD_PTR lpSystemAffinityMask = 0;
 737   int proc_count = processor_count();
 738   if (proc_count <= sizeof(UINT_PTR) * BitsPerByte &&
 739       GetProcessAffinityMask(GetCurrentProcess(), &lpProcessAffinityMask, &lpSystemAffinityMask)) {
 740     // Nof active processors is number of bits in process affinity mask
 741     int bitcount = 0;
 742     while (lpProcessAffinityMask != 0) {
 743       lpProcessAffinityMask = lpProcessAffinityMask & (lpProcessAffinityMask-1);
 744       bitcount++;
 745     }
 746     return bitcount;
 747   } else {
 748     return proc_count;
 749   }
 750 }
 751 
 752 void os::set_native_thread_name(const char *name) {
 753 
 754   // See: http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
 755   //
 756   // Note that unfortunately this only works if the process
 757   // is already attached to a debugger; debugger must observe
 758   // the exception below to show the correct name.
 759 
 760   const DWORD MS_VC_EXCEPTION = 0x406D1388;
 761   struct {
 762     DWORD dwType;     // must be 0x1000
 763     LPCSTR szName;    // pointer to name (in user addr space)
 764     DWORD dwThreadID; // thread ID (-1=caller thread)
 765     DWORD dwFlags;    // reserved for future use, must be zero
 766   } info;
 767 
 768   info.dwType = 0x1000;
 769   info.szName = name;
 770   info.dwThreadID = -1;
 771   info.dwFlags = 0;
 772 
 773   __try {
 774     RaiseException (MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(DWORD), (const ULONG_PTR*)&info );
 775   } __except(EXCEPTION_CONTINUE_EXECUTION) {}
 776 }
 777 
 778 bool os::distribute_processes(uint length, uint* distribution) {
 779   // Not yet implemented.
 780   return false;
 781 }
 782 
 783 bool os::bind_to_processor(uint processor_id) {
 784   // Not yet implemented.
 785   return false;
 786 }
 787 
 788 void os::win32::initialize_performance_counter() {
 789   LARGE_INTEGER count;
 790   if (QueryPerformanceFrequency(&count)) {
 791     win32::_has_performance_count = 1;
 792     performance_frequency = as_long(count);
 793     QueryPerformanceCounter(&count);
 794     initial_performance_count = as_long(count);
 795   } else {
 796     win32::_has_performance_count = 0;
 797     FILETIME wt;
 798     GetSystemTimeAsFileTime(&wt);
 799     first_filetime = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
 800   }
 801 }
 802 
 803 
 804 double os::elapsedTime() {
 805   return (double) elapsed_counter() / (double) elapsed_frequency();
 806 }
 807 
 808 
 809 // Windows format:
 810 //   The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
 811 // Java format:
 812 //   Java standards require the number of milliseconds since 1/1/1970
 813 
 814 // Constant offset - calculated using offset()
 815 static jlong  _offset   = 116444736000000000;
 816 // Fake time counter for reproducible results when debugging
 817 static jlong  fake_time = 0;
 818 
 819 #ifdef ASSERT
 820 // Just to be safe, recalculate the offset in debug mode
 821 static jlong _calculated_offset = 0;
 822 static int   _has_calculated_offset = 0;
 823 
 824 jlong offset() {
 825   if (_has_calculated_offset) return _calculated_offset;
 826   SYSTEMTIME java_origin;
 827   java_origin.wYear          = 1970;
 828   java_origin.wMonth         = 1;
 829   java_origin.wDayOfWeek     = 0; // ignored
 830   java_origin.wDay           = 1;
 831   java_origin.wHour          = 0;
 832   java_origin.wMinute        = 0;
 833   java_origin.wSecond        = 0;
 834   java_origin.wMilliseconds  = 0;
 835   FILETIME jot;
 836   if (!SystemTimeToFileTime(&java_origin, &jot)) {
 837     fatal(err_msg("Error = %d\nWindows error", GetLastError()));
 838   }
 839   _calculated_offset = jlong_from(jot.dwHighDateTime, jot.dwLowDateTime);
 840   _has_calculated_offset = 1;
 841   assert(_calculated_offset == _offset, "Calculated and constant time offsets must be equal");
 842   return _calculated_offset;
 843 }
 844 #else
 845 jlong offset() {
 846   return _offset;
 847 }
 848 #endif
 849 
 850 jlong windows_to_java_time(FILETIME wt) {
 851   jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
 852   return (a - offset()) / 10000;
 853 }
 854 
 855 FILETIME java_to_windows_time(jlong l) {
 856   jlong a = (l * 10000) + offset();
 857   FILETIME result;
 858   result.dwHighDateTime = high(a);
 859   result.dwLowDateTime  = low(a);
 860   return result;
 861 }
 862 
 863 bool os::supports_vtime() { return true; }
 864 bool os::enable_vtime() { return false; }
 865 bool os::vtime_enabled() { return false; }
 866 
 867 double os::elapsedVTime() {
 868   FILETIME created;
 869   FILETIME exited;
 870   FILETIME kernel;
 871   FILETIME user;
 872   if (GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user) != 0) {
 873     // the resolution of windows_to_java_time() should be sufficient (ms)
 874     return (double) (windows_to_java_time(kernel) + windows_to_java_time(user)) / MILLIUNITS;
 875   } else {
 876     return elapsedTime();
 877   }
 878 }
 879 
 880 jlong os::javaTimeMillis() {
 881   if (UseFakeTimers) {
 882     return fake_time++;
 883   } else {
 884     FILETIME wt;
 885     GetSystemTimeAsFileTime(&wt);
 886     return windows_to_java_time(wt);
 887   }
 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, mtInternal);
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, mtInternal);
1148     free(dirp, mtInternal);
1149     errno = ENOENT;
1150     return 0;
1151   } else if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1152     free(dirp->path, mtInternal);
1153     free(dirp, mtInternal);
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, mtInternal);
1172       free(dirp, mtInternal);
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, mtInternal);
1211   free(dirp, mtInternal);
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], mtInternal);
1279       }
1280     }
1281     if (pelements != NULL) {
1282       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
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 6004:
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, mtInternal);
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_allocation_granularity() == 0, "reserve block 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 MAX_EXIT_HANDLES    16
3785 #define EXIT_TIMEOUT      1000 /* 1 sec */
3786 
3787 static BOOL CALLBACK init_crit_sect_call(PINIT_ONCE, PVOID pcrit_sect, PVOID*) {
3788   InitializeCriticalSection((CRITICAL_SECTION*)pcrit_sect);
3789   return TRUE;
3790 }
3791 
3792 int os::win32::exit_process_or_thread(Ept what, int exit_code) {
3793   // Basic approach:
3794   //  - Each exiting thread registers its intent to exit and then does so.
3795   //  - A thread trying to terminate the process must wait for all
3796   //    threads currently exiting to complete their exit.
3797 
3798   if (os::win32::has_exit_bug()) {
3799     // The array holds handles of the threads that have started exiting by calling
3800     // _endthreadex().
3801     // Should be large enough to avoid blocking the exiting thread due to lack of
3802     // a free slot.
3803     static HANDLE handles[MAX_EXIT_HANDLES];
3804     static int handle_count = 0;
3805 
3806     static INIT_ONCE init_once_crit_sect = INIT_ONCE_STATIC_INIT;
3807     static CRITICAL_SECTION crit_sect;
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 {
3816       EnterCriticalSection(&crit_sect);
3817 
3818       if (what == EPT_THREAD) {
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_OBJECT_0) {
3826               warning("WaitForSingleObject failed in %s: %d\n", __FILE__, __LINE__);
3827               // Don't keep the handle, if we failed waiting for it.
3828             }
3829             CloseHandle(handles[i]);
3830           }
3831         }
3832 
3833         // If there's no free slot in the array of the kept handles, we'll have to
3834         // wait until at least one thread completes exiting.
3835         if ((handle_count = j) == MAX_EXIT_HANDLES) {
3836           res = WaitForMultipleObjects(MAX_EXIT_HANDLES, handles, FALSE, EXIT_TIMEOUT);
3837           if (res >= WAIT_OBJECT_0 && res < (WAIT_OBJECT_0 + MAX_EXIT_HANDLES)) {
3838             i = (res - WAIT_OBJECT_0);
3839             handle_count = MAX_EXIT_HANDLES - 1;
3840             for (; i < handle_count; ++i) {
3841               handles[i] = handles[i + 1];
3842             }
3843           } else {
3844             warning("WaitForMultipleObjects failed in %s: %d\n", __FILE__, __LINE__);
3845             // Don't keep handles, if we failed waiting for them.
3846             for (i = 0; i < MAX_EXIT_HANDLES; ++i) {
3847               CloseHandle(handles[i]);
3848             }
3849             handle_count = 0;
3850           }
3851         }
3852 
3853         // Store a duplicate of the current thread handle in the array of handles.
3854         hproc = GetCurrentProcess();
3855         hthr = GetCurrentThread();
3856         if (!DuplicateHandle(hproc, hthr, hproc, &handles[handle_count],
3857                              0, FALSE, DUPLICATE_SAME_ACCESS)) {
3858           warning("DuplicateHandle failed in %s: %d\n", __FILE__, __LINE__);
3859         } else {
3860           ++handle_count;
3861         }
3862 
3863         // The current exiting thread has stored its handle in the array, and now
3864         // should leave the critical section before calling _endthreadex().
3865 
3866       } else { // what != EPT_THREAD
3867         if (handle_count > 0) {
3868           // Before ending the process, make sure all the threads that had called
3869           // _endthreadex() completed.
3870           res = WaitForMultipleObjects(handle_count, handles, TRUE, EXIT_TIMEOUT);
3871           if (res == WAIT_FAILED) {
3872             warning("WaitForMultipleObjects failed in %s: %d\n", __FILE__, __LINE__);
3873           }
3874           for (i = 0; i < handle_count; ++i) {
3875             CloseHandle(handles[i]);
3876           }
3877           handle_count = 0;
3878         }
3879 
3880         // End the process, not leaving critical section.
3881         // This makes sure no other thread executes exit-related code at the same
3882         // time, thus a race is avoided.
3883         if (what == EPT_PROCESS) {
3884           ::exit(exit_code);
3885         } else {
3886           _exit(exit_code);
3887         }
3888       }
3889 
3890       LeaveCriticalSection(&crit_sect);
3891     }
3892   }
3893 
3894   // We are here if either
3895   // - there's no 'race at exit' bug on this OS release;
3896   // - initialization of the critical section failed (unlikely);
3897   // - the current thread has stored its handle and left the critical section.
3898   if (what == EPT_THREAD) {
3899     _endthreadex((unsigned)exit_code);
3900   } else if (what == EPT_PROCESS) {
3901     ::exit(exit_code);
3902   } else {
3903     _exit(exit_code);
3904   }
3905 
3906   // Should not reach here
3907   return exit_code;
3908 }
3909 
3910 #undef MAX_EXIT_HANDLES
3911 #undef EXIT_TIMEOUT
3912 
3913 void os::win32::setmode_streams() {
3914   _setmode(_fileno(stdin), _O_BINARY);
3915   _setmode(_fileno(stdout), _O_BINARY);
3916   _setmode(_fileno(stderr), _O_BINARY);
3917 }
3918 
3919 
3920 bool os::is_debugger_attached() {
3921   return IsDebuggerPresent() ? true : false;
3922 }
3923 
3924 
3925 void os::wait_for_keypress_at_exit(void) {
3926   if (PauseAtExit) {
3927     fprintf(stderr, "Press any key to continue...\n");
3928     fgetc(stdin);
3929   }
3930 }
3931 
3932 
3933 int os::message_box(const char* title, const char* message) {
3934   int result = MessageBox(NULL, message, title,
3935                           MB_YESNO | MB_ICONERROR | MB_SYSTEMMODAL | MB_DEFAULT_DESKTOP_ONLY);
3936   return result == IDYES;
3937 }
3938 
3939 int os::allocate_thread_local_storage() {
3940   return TlsAlloc();
3941 }
3942 
3943 
3944 void os::free_thread_local_storage(int index) {
3945   TlsFree(index);
3946 }
3947 
3948 
3949 void os::thread_local_storage_at_put(int index, void* value) {
3950   TlsSetValue(index, value);
3951   assert(thread_local_storage_at(index) == value, "Just checking");
3952 }
3953 
3954 
3955 void* os::thread_local_storage_at(int index) {
3956   return TlsGetValue(index);
3957 }
3958 
3959 
3960 #ifndef PRODUCT
3961 #ifndef _WIN64
3962 // Helpers to check whether NX protection is enabled
3963 int nx_exception_filter(_EXCEPTION_POINTERS *pex) {
3964   if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
3965       pex->ExceptionRecord->NumberParameters > 0 &&
3966       pex->ExceptionRecord->ExceptionInformation[0] ==
3967       EXCEPTION_INFO_EXEC_VIOLATION) {
3968     return EXCEPTION_EXECUTE_HANDLER;
3969   }
3970   return EXCEPTION_CONTINUE_SEARCH;
3971 }
3972 
3973 void nx_check_protection() {
3974   // If NX is enabled we'll get an exception calling into code on the stack
3975   char code[] = { (char)0xC3 }; // ret
3976   void *code_ptr = (void *)code;
3977   __try {
3978     __asm call code_ptr
3979   } __except(nx_exception_filter((_EXCEPTION_POINTERS*)_exception_info())) {
3980     tty->print_raw_cr("NX protection detected.");
3981   }
3982 }
3983 #endif // _WIN64
3984 #endif // PRODUCT
3985 
3986 // this is called _before_ the global arguments have been parsed
3987 void os::init(void) {
3988   _initial_pid = _getpid();
3989 
3990   init_random(1234567);
3991 
3992   win32::initialize_system_info();
3993   win32::setmode_streams();
3994   init_page_sizes((size_t) win32::vm_page_size());
3995 
3996   // This may be overridden later when argument processing is done.
3997   FLAG_SET_ERGO(bool, UseLargePagesIndividualAllocation,
3998                 os::win32::is_windows_2003());
3999 
4000   // Initialize main_process and main_thread
4001   main_process = GetCurrentProcess();  // Remember main_process is a pseudo handle
4002   if (!DuplicateHandle(main_process, GetCurrentThread(), main_process,
4003                        &main_thread, THREAD_ALL_ACCESS, false, 0)) {
4004     fatal("DuplicateHandle failed\n");
4005   }
4006   main_thread_id = (int) GetCurrentThreadId();
4007 }
4008 
4009 // To install functions for atexit processing
4010 extern "C" {
4011   static void perfMemory_exit_helper() {
4012     perfMemory_exit();
4013   }
4014 }
4015 
4016 static jint initSock();
4017 
4018 // this is called _after_ the global arguments have been parsed
4019 jint os::init_2(void) {
4020   // Allocate a single page and mark it as readable for safepoint polling
4021   address polling_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READONLY);
4022   guarantee(polling_page != NULL, "Reserve Failed for polling page");
4023 
4024   address return_page  = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY);
4025   guarantee(return_page != NULL, "Commit Failed for polling page");
4026 
4027   os::set_polling_page(polling_page);
4028 
4029 #ifndef PRODUCT
4030   if (Verbose && PrintMiscellaneous) {
4031     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n",
4032                (intptr_t)polling_page);
4033   }
4034 #endif
4035 
4036   if (!UseMembar) {
4037     address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE);
4038     guarantee(mem_serialize_page != NULL, "Reserve Failed for memory serialize page");
4039 
4040     return_page  = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE);
4041     guarantee(return_page != NULL, "Commit Failed for memory serialize page");
4042 
4043     os::set_memory_serialize_page(mem_serialize_page);
4044 
4045 #ifndef PRODUCT
4046     if (Verbose && PrintMiscellaneous) {
4047       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n",
4048                  (intptr_t)mem_serialize_page);
4049     }
4050 #endif
4051   }
4052 
4053   // Setup Windows Exceptions
4054 
4055   // for debugging float code generation bugs
4056   if (ForceFloatExceptions) {
4057 #ifndef  _WIN64
4058     static long fp_control_word = 0;
4059     __asm { fstcw fp_control_word }
4060     // see Intel PPro Manual, Vol. 2, p 7-16
4061     const long precision = 0x20;
4062     const long underflow = 0x10;
4063     const long overflow  = 0x08;
4064     const long zero_div  = 0x04;
4065     const long denorm    = 0x02;
4066     const long invalid   = 0x01;
4067     fp_control_word |= invalid;
4068     __asm { fldcw fp_control_word }
4069 #endif
4070   }
4071 
4072   // If stack_commit_size is 0, windows will reserve the default size,
4073   // but only commit a small portion of it.
4074   size_t stack_commit_size = round_to(ThreadStackSize*K, os::vm_page_size());
4075   size_t default_reserve_size = os::win32::default_stack_size();
4076   size_t actual_reserve_size = stack_commit_size;
4077   if (stack_commit_size < default_reserve_size) {
4078     // If stack_commit_size == 0, we want this too
4079     actual_reserve_size = default_reserve_size;
4080   }
4081 
4082   // Check minimum allowable stack size for thread creation and to initialize
4083   // the java system classes, including StackOverflowError - depends on page
4084   // size.  Add a page for compiler2 recursion in main thread.
4085   // Add in 2*BytesPerWord times page size to account for VM stack during
4086   // class initialization depending on 32 or 64 bit VM.
4087   size_t min_stack_allowed =
4088             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
4089                      2*BytesPerWord COMPILER2_PRESENT(+1)) * os::vm_page_size();
4090   if (actual_reserve_size < min_stack_allowed) {
4091     tty->print_cr("\nThe stack size specified is too small, "
4092                   "Specify at least %dk",
4093                   min_stack_allowed / K);
4094     return JNI_ERR;
4095   }
4096 
4097   JavaThread::set_stack_size_at_create(stack_commit_size);
4098 
4099   // Calculate theoretical max. size of Threads to guard gainst artifical
4100   // out-of-memory situations, where all available address-space has been
4101   // reserved by thread stacks.
4102   assert(actual_reserve_size != 0, "Must have a stack");
4103 
4104   // Calculate the thread limit when we should start doing Virtual Memory
4105   // banging. Currently when the threads will have used all but 200Mb of space.
4106   //
4107   // TODO: consider performing a similar calculation for commit size instead
4108   // as reserve size, since on a 64-bit platform we'll run into that more
4109   // often than running out of virtual memory space.  We can use the
4110   // lower value of the two calculations as the os_thread_limit.
4111   size_t max_address_space = ((size_t)1 << (BitsPerWord - 1)) - (200 * K * K);
4112   win32::_os_thread_limit = (intx)(max_address_space / actual_reserve_size);
4113 
4114   // at exit methods are called in the reverse order of their registration.
4115   // there is no limit to the number of functions registered. atexit does
4116   // not set errno.
4117 
4118   if (PerfAllowAtExitRegistration) {
4119     // only register atexit functions if PerfAllowAtExitRegistration is set.
4120     // atexit functions can be delayed until process exit time, which
4121     // can be problematic for embedded VM situations. Embedded VMs should
4122     // call DestroyJavaVM() to assure that VM resources are released.
4123 
4124     // note: perfMemory_exit_helper atexit function may be removed in
4125     // the future if the appropriate cleanup code can be added to the
4126     // VM_Exit VMOperation's doit method.
4127     if (atexit(perfMemory_exit_helper) != 0) {
4128       warning("os::init_2 atexit(perfMemory_exit_helper) failed");
4129     }
4130   }
4131 
4132 #ifndef _WIN64
4133   // Print something if NX is enabled (win32 on AMD64)
4134   NOT_PRODUCT(if (PrintMiscellaneous && Verbose) nx_check_protection());
4135 #endif
4136 
4137   // initialize thread priority policy
4138   prio_init();
4139 
4140   if (UseNUMA && !ForceNUMA) {
4141     UseNUMA = false; // We don't fully support this yet
4142   }
4143 
4144   if (UseNUMAInterleaving) {
4145     // first check whether this Windows OS supports VirtualAllocExNuma, if not ignore this flag
4146     bool success = numa_interleaving_init();
4147     if (!success) UseNUMAInterleaving = false;
4148   }
4149 
4150   if (initSock() != JNI_OK) {
4151     return JNI_ERR;
4152   }
4153 
4154   return JNI_OK;
4155 }
4156 
4157 // Mark the polling page as unreadable
4158 void os::make_polling_page_unreadable(void) {
4159   DWORD old_status;
4160   if (!VirtualProtect((char *)_polling_page, os::vm_page_size(),
4161                       PAGE_NOACCESS, &old_status)) {
4162     fatal("Could not disable polling page");
4163   }
4164 }
4165 
4166 // Mark the polling page as readable
4167 void os::make_polling_page_readable(void) {
4168   DWORD old_status;
4169   if (!VirtualProtect((char *)_polling_page, os::vm_page_size(),
4170                       PAGE_READONLY, &old_status)) {
4171     fatal("Could not enable polling page");
4172   }
4173 }
4174 
4175 
4176 int os::stat(const char *path, struct stat *sbuf) {
4177   char pathbuf[MAX_PATH];
4178   if (strlen(path) > MAX_PATH - 1) {
4179     errno = ENAMETOOLONG;
4180     return -1;
4181   }
4182   os::native_path(strcpy(pathbuf, path));
4183   int ret = ::stat(pathbuf, sbuf);
4184   if (sbuf != NULL && UseUTCFileTimestamp) {
4185     // Fix for 6539723.  st_mtime returned from stat() is dependent on
4186     // the system timezone and so can return different values for the
4187     // same file if/when daylight savings time changes.  This adjustment
4188     // makes sure the same timestamp is returned regardless of the TZ.
4189     //
4190     // See:
4191     // http://msdn.microsoft.com/library/
4192     //   default.asp?url=/library/en-us/sysinfo/base/
4193     //   time_zone_information_str.asp
4194     // and
4195     // http://msdn.microsoft.com/library/default.asp?url=
4196     //   /library/en-us/sysinfo/base/settimezoneinformation.asp
4197     //
4198     // NOTE: there is a insidious bug here:  If the timezone is changed
4199     // after the call to stat() but before 'GetTimeZoneInformation()', then
4200     // the adjustment we do here will be wrong and we'll return the wrong
4201     // value (which will likely end up creating an invalid class data
4202     // archive).  Absent a better API for this, or some time zone locking
4203     // mechanism, we'll have to live with this risk.
4204     TIME_ZONE_INFORMATION tz;
4205     DWORD tzid = GetTimeZoneInformation(&tz);
4206     int daylightBias =
4207       (tzid == TIME_ZONE_ID_DAYLIGHT) ?  tz.DaylightBias : tz.StandardBias;
4208     sbuf->st_mtime += (tz.Bias + daylightBias) * 60;
4209   }
4210   return ret;
4211 }
4212 
4213 
4214 #define FT2INT64(ft) \
4215   ((jlong)((jlong)(ft).dwHighDateTime << 32 | (julong)(ft).dwLowDateTime))
4216 
4217 
4218 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4219 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4220 // of a thread.
4221 //
4222 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
4223 // the fast estimate available on the platform.
4224 
4225 // current_thread_cpu_time() is not optimized for Windows yet
4226 jlong os::current_thread_cpu_time() {
4227   // return user + sys since the cost is the same
4228   return os::thread_cpu_time(Thread::current(), true /* user+sys */);
4229 }
4230 
4231 jlong os::thread_cpu_time(Thread* thread) {
4232   // consistent with what current_thread_cpu_time() returns.
4233   return os::thread_cpu_time(thread, true /* user+sys */);
4234 }
4235 
4236 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
4237   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
4238 }
4239 
4240 jlong os::thread_cpu_time(Thread* thread, bool user_sys_cpu_time) {
4241   // This code is copy from clasic VM -> hpi::sysThreadCPUTime
4242   // If this function changes, os::is_thread_cpu_time_supported() should too
4243   if (os::win32::is_nt()) {
4244     FILETIME CreationTime;
4245     FILETIME ExitTime;
4246     FILETIME KernelTime;
4247     FILETIME UserTime;
4248 
4249     if (GetThreadTimes(thread->osthread()->thread_handle(), &CreationTime,
4250                        &ExitTime, &KernelTime, &UserTime) == 0) {
4251       return -1;
4252     } else if (user_sys_cpu_time) {
4253       return (FT2INT64(UserTime) + FT2INT64(KernelTime)) * 100;
4254     } else {
4255       return FT2INT64(UserTime) * 100;
4256     }
4257   } else {
4258     return (jlong) timeGetTime() * 1000000;
4259   }
4260 }
4261 
4262 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4263   info_ptr->max_value = ALL_64_BITS;        // the max value -- all 64 bits
4264   info_ptr->may_skip_backward = false;      // GetThreadTimes returns absolute time
4265   info_ptr->may_skip_forward = false;       // GetThreadTimes returns absolute time
4266   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;   // user+system time is returned
4267 }
4268 
4269 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4270   info_ptr->max_value = ALL_64_BITS;        // the max value -- all 64 bits
4271   info_ptr->may_skip_backward = false;      // GetThreadTimes returns absolute time
4272   info_ptr->may_skip_forward = false;       // GetThreadTimes returns absolute time
4273   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;   // user+system time is returned
4274 }
4275 
4276 bool os::is_thread_cpu_time_supported() {
4277   // see os::thread_cpu_time
4278   if (os::win32::is_nt()) {
4279     FILETIME CreationTime;
4280     FILETIME ExitTime;
4281     FILETIME KernelTime;
4282     FILETIME UserTime;
4283 
4284     if (GetThreadTimes(GetCurrentThread(), &CreationTime, &ExitTime,
4285                        &KernelTime, &UserTime) == 0) {
4286       return false;
4287     } else {
4288       return true;
4289     }
4290   } else {
4291     return false;
4292   }
4293 }
4294 
4295 // Windows does't provide a loadavg primitive so this is stubbed out for now.
4296 // It does have primitives (PDH API) to get CPU usage and run queue length.
4297 // "\\Processor(_Total)\\% Processor Time", "\\System\\Processor Queue Length"
4298 // If we wanted to implement loadavg on Windows, we have a few options:
4299 //
4300 // a) Query CPU usage and run queue length and "fake" an answer by
4301 //    returning the CPU usage if it's under 100%, and the run queue
4302 //    length otherwise.  It turns out that querying is pretty slow
4303 //    on Windows, on the order of 200 microseconds on a fast machine.
4304 //    Note that on the Windows the CPU usage value is the % usage
4305 //    since the last time the API was called (and the first call
4306 //    returns 100%), so we'd have to deal with that as well.
4307 //
4308 // b) Sample the "fake" answer using a sampling thread and store
4309 //    the answer in a global variable.  The call to loadavg would
4310 //    just return the value of the global, avoiding the slow query.
4311 //
4312 // c) Sample a better answer using exponential decay to smooth the
4313 //    value.  This is basically the algorithm used by UNIX kernels.
4314 //
4315 // Note that sampling thread starvation could affect both (b) and (c).
4316 int os::loadavg(double loadavg[], int nelem) {
4317   return -1;
4318 }
4319 
4320 
4321 // DontYieldALot=false by default: dutifully perform all yields as requested by JVM_Yield()
4322 bool os::dont_yield() {
4323   return DontYieldALot;
4324 }
4325 
4326 // This method is a slightly reworked copy of JDK's sysOpen
4327 // from src/windows/hpi/src/sys_api_md.c
4328 
4329 int os::open(const char *path, int oflag, int mode) {
4330   char pathbuf[MAX_PATH];
4331 
4332   if (strlen(path) > MAX_PATH - 1) {
4333     errno = ENAMETOOLONG;
4334     return -1;
4335   }
4336   os::native_path(strcpy(pathbuf, path));
4337   return ::open(pathbuf, oflag | O_BINARY | O_NOINHERIT, mode);
4338 }
4339 
4340 FILE* os::open(int fd, const char* mode) {
4341   return ::_fdopen(fd, mode);
4342 }
4343 
4344 // Is a (classpath) directory empty?
4345 bool os::dir_is_empty(const char* path) {
4346   WIN32_FIND_DATA fd;
4347   HANDLE f = FindFirstFile(path, &fd);
4348   if (f == INVALID_HANDLE_VALUE) {
4349     return true;
4350   }
4351   FindClose(f);
4352   return false;
4353 }
4354 
4355 // create binary file, rewriting existing file if required
4356 int os::create_binary_file(const char* path, bool rewrite_existing) {
4357   int oflags = _O_CREAT | _O_WRONLY | _O_BINARY;
4358   if (!rewrite_existing) {
4359     oflags |= _O_EXCL;
4360   }
4361   return ::open(path, oflags, _S_IREAD | _S_IWRITE);
4362 }
4363 
4364 // return current position of file pointer
4365 jlong os::current_file_offset(int fd) {
4366   return (jlong)::_lseeki64(fd, (__int64)0L, SEEK_CUR);
4367 }
4368 
4369 // move file pointer to the specified offset
4370 jlong os::seek_to_file_offset(int fd, jlong offset) {
4371   return (jlong)::_lseeki64(fd, (__int64)offset, SEEK_SET);
4372 }
4373 
4374 
4375 jlong os::lseek(int fd, jlong offset, int whence) {
4376   return (jlong) ::_lseeki64(fd, offset, whence);
4377 }
4378 
4379 // This method is a slightly reworked copy of JDK's sysNativePath
4380 // from src/windows/hpi/src/path_md.c
4381 
4382 // Convert a pathname to native format.  On win32, this involves forcing all
4383 // separators to be '\\' rather than '/' (both are legal inputs, but Win95
4384 // sometimes rejects '/') and removing redundant separators.  The input path is
4385 // assumed to have been converted into the character encoding used by the local
4386 // system.  Because this might be a double-byte encoding, care is taken to
4387 // treat double-byte lead characters correctly.
4388 //
4389 // This procedure modifies the given path in place, as the result is never
4390 // longer than the original.  There is no error return; this operation always
4391 // succeeds.
4392 char * os::native_path(char *path) {
4393   char *src = path, *dst = path, *end = path;
4394   char *colon = NULL;  // If a drive specifier is found, this will
4395                        // point to the colon following the drive letter
4396 
4397   // Assumption: '/', '\\', ':', and drive letters are never lead bytes
4398   assert(((!::IsDBCSLeadByte('/')) && (!::IsDBCSLeadByte('\\'))
4399           && (!::IsDBCSLeadByte(':'))), "Illegal lead byte");
4400 
4401   // Check for leading separators
4402 #define isfilesep(c) ((c) == '/' || (c) == '\\')
4403   while (isfilesep(*src)) {
4404     src++;
4405   }
4406 
4407   if (::isalpha(*src) && !::IsDBCSLeadByte(*src) && src[1] == ':') {
4408     // Remove leading separators if followed by drive specifier.  This
4409     // hack is necessary to support file URLs containing drive
4410     // specifiers (e.g., "file://c:/path").  As a side effect,
4411     // "/c:/path" can be used as an alternative to "c:/path".
4412     *dst++ = *src++;
4413     colon = dst;
4414     *dst++ = ':';
4415     src++;
4416   } else {
4417     src = path;
4418     if (isfilesep(src[0]) && isfilesep(src[1])) {
4419       // UNC pathname: Retain first separator; leave src pointed at
4420       // second separator so that further separators will be collapsed
4421       // into the second separator.  The result will be a pathname
4422       // beginning with "\\\\" followed (most likely) by a host name.
4423       src = dst = path + 1;
4424       path[0] = '\\';     // Force first separator to '\\'
4425     }
4426   }
4427 
4428   end = dst;
4429 
4430   // Remove redundant separators from remainder of path, forcing all
4431   // separators to be '\\' rather than '/'. Also, single byte space
4432   // characters are removed from the end of the path because those
4433   // are not legal ending characters on this operating system.
4434   //
4435   while (*src != '\0') {
4436     if (isfilesep(*src)) {
4437       *dst++ = '\\'; src++;
4438       while (isfilesep(*src)) src++;
4439       if (*src == '\0') {
4440         // Check for trailing separator
4441         end = dst;
4442         if (colon == dst - 2) break;  // "z:\\"
4443         if (dst == path + 1) break;   // "\\"
4444         if (dst == path + 2 && isfilesep(path[0])) {
4445           // "\\\\" is not collapsed to "\\" because "\\\\" marks the
4446           // beginning of a UNC pathname.  Even though it is not, by
4447           // itself, a valid UNC pathname, we leave it as is in order
4448           // to be consistent with the path canonicalizer as well
4449           // as the win32 APIs, which treat this case as an invalid
4450           // UNC pathname rather than as an alias for the root
4451           // directory of the current drive.
4452           break;
4453         }
4454         end = --dst;  // Path does not denote a root directory, so
4455                       // remove trailing separator
4456         break;
4457       }
4458       end = dst;
4459     } else {
4460       if (::IsDBCSLeadByte(*src)) {  // Copy a double-byte character
4461         *dst++ = *src++;
4462         if (*src) *dst++ = *src++;
4463         end = dst;
4464       } else {  // Copy a single-byte character
4465         char c = *src++;
4466         *dst++ = c;
4467         // Space is not a legal ending character
4468         if (c != ' ') end = dst;
4469       }
4470     }
4471   }
4472 
4473   *end = '\0';
4474 
4475   // For "z:", add "." to work around a bug in the C runtime library
4476   if (colon == dst - 1) {
4477     path[2] = '.';
4478     path[3] = '\0';
4479   }
4480 
4481   return path;
4482 }
4483 
4484 // This code is a copy of JDK's sysSetLength
4485 // from src/windows/hpi/src/sys_api_md.c
4486 
4487 int os::ftruncate(int fd, jlong length) {
4488   HANDLE h = (HANDLE)::_get_osfhandle(fd);
4489   long high = (long)(length >> 32);
4490   DWORD ret;
4491 
4492   if (h == (HANDLE)(-1)) {
4493     return -1;
4494   }
4495 
4496   ret = ::SetFilePointer(h, (long)(length), &high, FILE_BEGIN);
4497   if ((ret == 0xFFFFFFFF) && (::GetLastError() != NO_ERROR)) {
4498     return -1;
4499   }
4500 
4501   if (::SetEndOfFile(h) == FALSE) {
4502     return -1;
4503   }
4504 
4505   return 0;
4506 }
4507 
4508 
4509 // This code is a copy of JDK's sysSync
4510 // from src/windows/hpi/src/sys_api_md.c
4511 // except for the legacy workaround for a bug in Win 98
4512 
4513 int os::fsync(int fd) {
4514   HANDLE handle = (HANDLE)::_get_osfhandle(fd);
4515 
4516   if ((!::FlushFileBuffers(handle)) &&
4517       (GetLastError() != ERROR_ACCESS_DENIED)) {
4518     // from winerror.h
4519     return -1;
4520   }
4521   return 0;
4522 }
4523 
4524 static int nonSeekAvailable(int, long *);
4525 static int stdinAvailable(int, long *);
4526 
4527 #define S_ISCHR(mode)   (((mode) & _S_IFCHR) == _S_IFCHR)
4528 #define S_ISFIFO(mode)  (((mode) & _S_IFIFO) == _S_IFIFO)
4529 
4530 // This code is a copy of JDK's sysAvailable
4531 // from src/windows/hpi/src/sys_api_md.c
4532 
4533 int os::available(int fd, jlong *bytes) {
4534   jlong cur, end;
4535   struct _stati64 stbuf64;
4536 
4537   if (::_fstati64(fd, &stbuf64) >= 0) {
4538     int mode = stbuf64.st_mode;
4539     if (S_ISCHR(mode) || S_ISFIFO(mode)) {
4540       int ret;
4541       long lpbytes;
4542       if (fd == 0) {
4543         ret = stdinAvailable(fd, &lpbytes);
4544       } else {
4545         ret = nonSeekAvailable(fd, &lpbytes);
4546       }
4547       (*bytes) = (jlong)(lpbytes);
4548       return ret;
4549     }
4550     if ((cur = ::_lseeki64(fd, 0L, SEEK_CUR)) == -1) {
4551       return FALSE;
4552     } else if ((end = ::_lseeki64(fd, 0L, SEEK_END)) == -1) {
4553       return FALSE;
4554     } else if (::_lseeki64(fd, cur, SEEK_SET) == -1) {
4555       return FALSE;
4556     }
4557     *bytes = end - cur;
4558     return TRUE;
4559   } else {
4560     return FALSE;
4561   }
4562 }
4563 
4564 // This code is a copy of JDK's nonSeekAvailable
4565 // from src/windows/hpi/src/sys_api_md.c
4566 
4567 static int nonSeekAvailable(int fd, long *pbytes) {
4568   // This is used for available on non-seekable devices
4569   // (like both named and anonymous pipes, such as pipes
4570   //  connected to an exec'd process).
4571   // Standard Input is a special case.
4572   HANDLE han;
4573 
4574   if ((han = (HANDLE) ::_get_osfhandle(fd)) == (HANDLE)(-1)) {
4575     return FALSE;
4576   }
4577 
4578   if (! ::PeekNamedPipe(han, NULL, 0, NULL, (LPDWORD)pbytes, NULL)) {
4579     // PeekNamedPipe fails when at EOF.  In that case we
4580     // simply make *pbytes = 0 which is consistent with the
4581     // behavior we get on Solaris when an fd is at EOF.
4582     // The only alternative is to raise an Exception,
4583     // which isn't really warranted.
4584     //
4585     if (::GetLastError() != ERROR_BROKEN_PIPE) {
4586       return FALSE;
4587     }
4588     *pbytes = 0;
4589   }
4590   return TRUE;
4591 }
4592 
4593 #define MAX_INPUT_EVENTS 2000
4594 
4595 // This code is a copy of JDK's stdinAvailable
4596 // from src/windows/hpi/src/sys_api_md.c
4597 
4598 static int stdinAvailable(int fd, long *pbytes) {
4599   HANDLE han;
4600   DWORD numEventsRead = 0;  // Number of events read from buffer
4601   DWORD numEvents = 0;      // Number of events in buffer
4602   DWORD i = 0;              // Loop index
4603   DWORD curLength = 0;      // Position marker
4604   DWORD actualLength = 0;   // Number of bytes readable
4605   BOOL error = FALSE;       // Error holder
4606   INPUT_RECORD *lpBuffer;   // Pointer to records of input events
4607 
4608   if ((han = ::GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) {
4609     return FALSE;
4610   }
4611 
4612   // Construct an array of input records in the console buffer
4613   error = ::GetNumberOfConsoleInputEvents(han, &numEvents);
4614   if (error == 0) {
4615     return nonSeekAvailable(fd, pbytes);
4616   }
4617 
4618   // lpBuffer must fit into 64K or else PeekConsoleInput fails
4619   if (numEvents > MAX_INPUT_EVENTS) {
4620     numEvents = MAX_INPUT_EVENTS;
4621   }
4622 
4623   lpBuffer = (INPUT_RECORD *)os::malloc(numEvents * sizeof(INPUT_RECORD), mtInternal);
4624   if (lpBuffer == NULL) {
4625     return FALSE;
4626   }
4627 
4628   error = ::PeekConsoleInput(han, lpBuffer, numEvents, &numEventsRead);
4629   if (error == 0) {
4630     os::free(lpBuffer);
4631     return FALSE;
4632   }
4633 
4634   // Examine input records for the number of bytes available
4635   for (i=0; i<numEvents; i++) {
4636     if (lpBuffer[i].EventType == KEY_EVENT) {
4637 
4638       KEY_EVENT_RECORD *keyRecord = (KEY_EVENT_RECORD *)
4639                                       &(lpBuffer[i].Event);
4640       if (keyRecord->bKeyDown == TRUE) {
4641         CHAR *keyPressed = (CHAR *) &(keyRecord->uChar);
4642         curLength++;
4643         if (*keyPressed == '\r') {
4644           actualLength = curLength;
4645         }
4646       }
4647     }
4648   }
4649 
4650   if (lpBuffer != NULL) {
4651     os::free(lpBuffer);
4652   }
4653 
4654   *pbytes = (long) actualLength;
4655   return TRUE;
4656 }
4657 
4658 // Map a block of memory.
4659 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4660                         char *addr, size_t bytes, bool read_only,
4661                         bool allow_exec) {
4662   HANDLE hFile;
4663   char* base;
4664 
4665   hFile = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, NULL,
4666                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
4667   if (hFile == NULL) {
4668     if (PrintMiscellaneous && Verbose) {
4669       DWORD err = GetLastError();
4670       tty->print_cr("CreateFile() failed: GetLastError->%ld.", err);
4671     }
4672     return NULL;
4673   }
4674 
4675   if (allow_exec) {
4676     // CreateFileMapping/MapViewOfFileEx can't map executable memory
4677     // unless it comes from a PE image (which the shared archive is not.)
4678     // Even VirtualProtect refuses to give execute access to mapped memory
4679     // that was not previously executable.
4680     //
4681     // Instead, stick the executable region in anonymous memory.  Yuck.
4682     // Penalty is that ~4 pages will not be shareable - in the future
4683     // we might consider DLLizing the shared archive with a proper PE
4684     // header so that mapping executable + sharing is possible.
4685 
4686     base = (char*) VirtualAlloc(addr, bytes, MEM_COMMIT | MEM_RESERVE,
4687                                 PAGE_READWRITE);
4688     if (base == NULL) {
4689       if (PrintMiscellaneous && Verbose) {
4690         DWORD err = GetLastError();
4691         tty->print_cr("VirtualAlloc() failed: GetLastError->%ld.", err);
4692       }
4693       CloseHandle(hFile);
4694       return NULL;
4695     }
4696 
4697     DWORD bytes_read;
4698     OVERLAPPED overlapped;
4699     overlapped.Offset = (DWORD)file_offset;
4700     overlapped.OffsetHigh = 0;
4701     overlapped.hEvent = NULL;
4702     // ReadFile guarantees that if the return value is true, the requested
4703     // number of bytes were read before returning.
4704     bool res = ReadFile(hFile, base, (DWORD)bytes, &bytes_read, &overlapped) != 0;
4705     if (!res) {
4706       if (PrintMiscellaneous && Verbose) {
4707         DWORD err = GetLastError();
4708         tty->print_cr("ReadFile() failed: GetLastError->%ld.", err);
4709       }
4710       release_memory(base, bytes);
4711       CloseHandle(hFile);
4712       return NULL;
4713     }
4714   } else {
4715     HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0,
4716                                     NULL /* file_name */);
4717     if (hMap == NULL) {
4718       if (PrintMiscellaneous && Verbose) {
4719         DWORD err = GetLastError();
4720         tty->print_cr("CreateFileMapping() failed: GetLastError->%ld.", err);
4721       }
4722       CloseHandle(hFile);
4723       return NULL;
4724     }
4725 
4726     DWORD access = read_only ? FILE_MAP_READ : FILE_MAP_COPY;
4727     base = (char*)MapViewOfFileEx(hMap, access, 0, (DWORD)file_offset,
4728                                   (DWORD)bytes, addr);
4729     if (base == NULL) {
4730       if (PrintMiscellaneous && Verbose) {
4731         DWORD err = GetLastError();
4732         tty->print_cr("MapViewOfFileEx() failed: GetLastError->%ld.", err);
4733       }
4734       CloseHandle(hMap);
4735       CloseHandle(hFile);
4736       return NULL;
4737     }
4738 
4739     if (CloseHandle(hMap) == 0) {
4740       if (PrintMiscellaneous && Verbose) {
4741         DWORD err = GetLastError();
4742         tty->print_cr("CloseHandle(hMap) failed: GetLastError->%ld.", err);
4743       }
4744       CloseHandle(hFile);
4745       return base;
4746     }
4747   }
4748 
4749   if (allow_exec) {
4750     DWORD old_protect;
4751     DWORD exec_access = read_only ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE;
4752     bool res = VirtualProtect(base, bytes, exec_access, &old_protect) != 0;
4753 
4754     if (!res) {
4755       if (PrintMiscellaneous && Verbose) {
4756         DWORD err = GetLastError();
4757         tty->print_cr("VirtualProtect() failed: GetLastError->%ld.", err);
4758       }
4759       // Don't consider this a hard error, on IA32 even if the
4760       // VirtualProtect fails, we should still be able to execute
4761       CloseHandle(hFile);
4762       return base;
4763     }
4764   }
4765 
4766   if (CloseHandle(hFile) == 0) {
4767     if (PrintMiscellaneous && Verbose) {
4768       DWORD err = GetLastError();
4769       tty->print_cr("CloseHandle(hFile) failed: GetLastError->%ld.", err);
4770     }
4771     return base;
4772   }
4773 
4774   return base;
4775 }
4776 
4777 
4778 // Remap a block of memory.
4779 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4780                           char *addr, size_t bytes, bool read_only,
4781                           bool allow_exec) {
4782   // This OS does not allow existing memory maps to be remapped so we
4783   // have to unmap the memory before we remap it.
4784   if (!os::unmap_memory(addr, bytes)) {
4785     return NULL;
4786   }
4787 
4788   // There is a very small theoretical window between the unmap_memory()
4789   // call above and the map_memory() call below where a thread in native
4790   // code may be able to access an address that is no longer mapped.
4791 
4792   return os::map_memory(fd, file_name, file_offset, addr, bytes,
4793                         read_only, allow_exec);
4794 }
4795 
4796 
4797 // Unmap a block of memory.
4798 // Returns true=success, otherwise false.
4799 
4800 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4801   BOOL result = UnmapViewOfFile(addr);
4802   if (result == 0) {
4803     if (PrintMiscellaneous && Verbose) {
4804       DWORD err = GetLastError();
4805       tty->print_cr("UnmapViewOfFile() failed: GetLastError->%ld.", err);
4806     }
4807     return false;
4808   }
4809   return true;
4810 }
4811 
4812 void os::pause() {
4813   char filename[MAX_PATH];
4814   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4815     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4816   } else {
4817     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4818   }
4819 
4820   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4821   if (fd != -1) {
4822     struct stat buf;
4823     ::close(fd);
4824     while (::stat(filename, &buf) == 0) {
4825       Sleep(100);
4826     }
4827   } else {
4828     jio_fprintf(stderr,
4829                 "Could not open pause file '%s', continuing immediately.\n", filename);
4830   }
4831 }
4832 
4833 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
4834   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
4835 }
4836 
4837 // See the caveats for this class in os_windows.hpp
4838 // Protects the callback call so that raised OS EXCEPTIONS causes a jump back
4839 // into this method and returns false. If no OS EXCEPTION was raised, returns
4840 // true.
4841 // The callback is supposed to provide the method that should be protected.
4842 //
4843 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
4844   assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
4845   assert(!WatcherThread::watcher_thread()->has_crash_protection(),
4846          "crash_protection already set?");
4847 
4848   bool success = true;
4849   __try {
4850     WatcherThread::watcher_thread()->set_crash_protection(this);
4851     cb.call();
4852   } __except(EXCEPTION_EXECUTE_HANDLER) {
4853     // only for protection, nothing to do
4854     success = false;
4855   }
4856   WatcherThread::watcher_thread()->set_crash_protection(NULL);
4857   return success;
4858 }
4859 
4860 // An Event wraps a win32 "CreateEvent" kernel handle.
4861 //
4862 // We have a number of choices regarding "CreateEvent" win32 handle leakage:
4863 //
4864 // 1:  When a thread dies return the Event to the EventFreeList, clear the ParkHandle
4865 //     field, and call CloseHandle() on the win32 event handle.  Unpark() would
4866 //     need to be modified to tolerate finding a NULL (invalid) win32 event handle.
4867 //     In addition, an unpark() operation might fetch the handle field, but the
4868 //     event could recycle between the fetch and the SetEvent() operation.
4869 //     SetEvent() would either fail because the handle was invalid, or inadvertently work,
4870 //     as the win32 handle value had been recycled.  In an ideal world calling SetEvent()
4871 //     on an stale but recycled handle would be harmless, but in practice this might
4872 //     confuse other non-Sun code, so it's not a viable approach.
4873 //
4874 // 2:  Once a win32 event handle is associated with an Event, it remains associated
4875 //     with the Event.  The event handle is never closed.  This could be construed
4876 //     as handle leakage, but only up to the maximum # of threads that have been extant
4877 //     at any one time.  This shouldn't be an issue, as windows platforms typically
4878 //     permit a process to have hundreds of thousands of open handles.
4879 //
4880 // 3:  Same as (1), but periodically, at stop-the-world time, rundown the EventFreeList
4881 //     and release unused handles.
4882 //
4883 // 4:  Add a CRITICAL_SECTION to the Event to protect LD+SetEvent from LD;ST(null);CloseHandle.
4884 //     It's not clear, however, that we wouldn't be trading one type of leak for another.
4885 //
4886 // 5.  Use an RCU-like mechanism (Read-Copy Update).
4887 //     Or perhaps something similar to Maged Michael's "Hazard pointers".
4888 //
4889 // We use (2).
4890 //
4891 // TODO-FIXME:
4892 // 1.  Reconcile Doug's JSR166 j.u.c park-unpark with the objectmonitor implementation.
4893 // 2.  Consider wrapping the WaitForSingleObject(Ex) calls in SEH try/finally blocks
4894 //     to recover from (or at least detect) the dreaded Windows 841176 bug.
4895 // 3.  Collapse the interrupt_event, the JSR166 parker event, and the objectmonitor ParkEvent
4896 //     into a single win32 CreateEvent() handle.
4897 //
4898 // Assumption:
4899 //    Only one parker can exist on an event, which is why we allocate
4900 //    them per-thread. Multiple unparkers can coexist.
4901 //
4902 // _Event transitions in park()
4903 //   -1 => -1 : illegal
4904 //    1 =>  0 : pass - return immediately
4905 //    0 => -1 : block; then set _Event to 0 before returning
4906 //
4907 // _Event transitions in unpark()
4908 //    0 => 1 : just return
4909 //    1 => 1 : just return
4910 //   -1 => either 0 or 1; must signal target thread
4911 //         That is, we can safely transition _Event from -1 to either
4912 //         0 or 1.
4913 //
4914 // _Event serves as a restricted-range semaphore.
4915 //   -1 : thread is blocked, i.e. there is a waiter
4916 //    0 : neutral: thread is running or ready,
4917 //        could have been signaled after a wait started
4918 //    1 : signaled - thread is running or ready
4919 //
4920 // Another possible encoding of _Event would be with
4921 // explicit "PARKED" == 01b and "SIGNALED" == 10b bits.
4922 //
4923 
4924 int os::PlatformEvent::park(jlong Millis) {
4925   // Transitions for _Event:
4926   //   -1 => -1 : illegal
4927   //    1 =>  0 : pass - return immediately
4928   //    0 => -1 : block; then set _Event to 0 before returning
4929 
4930   guarantee(_ParkHandle != NULL , "Invariant");
4931   guarantee(Millis > 0          , "Invariant");
4932 
4933   // CONSIDER: defer assigning a CreateEvent() handle to the Event until
4934   // the initial park() operation.
4935   // Consider: use atomic decrement instead of CAS-loop
4936 
4937   int v;
4938   for (;;) {
4939     v = _Event;
4940     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
4941   }
4942   guarantee((v == 0) || (v == 1), "invariant");
4943   if (v != 0) return OS_OK;
4944 
4945   // Do this the hard way by blocking ...
4946   // TODO: consider a brief spin here, gated on the success of recent
4947   // spin attempts by this thread.
4948   //
4949   // We decompose long timeouts into series of shorter timed waits.
4950   // Evidently large timo values passed in WaitForSingleObject() are problematic on some
4951   // versions of Windows.  See EventWait() for details.  This may be superstition.  Or not.
4952   // We trust the WAIT_TIMEOUT indication and don't track the elapsed wait time
4953   // with os::javaTimeNanos().  Furthermore, we assume that spurious returns from
4954   // ::WaitForSingleObject() caused by latent ::setEvent() operations will tend
4955   // to happen early in the wait interval.  Specifically, after a spurious wakeup (rv ==
4956   // WAIT_OBJECT_0 but _Event is still < 0) we don't bother to recompute Millis to compensate
4957   // for the already waited time.  This policy does not admit any new outcomes.
4958   // In the future, however, we might want to track the accumulated wait time and
4959   // adjust Millis accordingly if we encounter a spurious wakeup.
4960 
4961   const int MAXTIMEOUT = 0x10000000;
4962   DWORD rv = WAIT_TIMEOUT;
4963   while (_Event < 0 && Millis > 0) {
4964     DWORD prd = Millis;     // set prd = MAX (Millis, MAXTIMEOUT)
4965     if (Millis > MAXTIMEOUT) {
4966       prd = MAXTIMEOUT;
4967     }
4968     rv = ::WaitForSingleObject(_ParkHandle, prd);
4969     assert(rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed");
4970     if (rv == WAIT_TIMEOUT) {
4971       Millis -= prd;
4972     }
4973   }
4974   v = _Event;
4975   _Event = 0;
4976   // see comment at end of os::PlatformEvent::park() below:
4977   OrderAccess::fence();
4978   // If we encounter a nearly simultanous timeout expiry and unpark()
4979   // we return OS_OK indicating we awoke via unpark().
4980   // Implementor's license -- returning OS_TIMEOUT would be equally valid, however.
4981   return (v >= 0) ? OS_OK : OS_TIMEOUT;
4982 }
4983 
4984 void os::PlatformEvent::park() {
4985   // Transitions for _Event:
4986   //   -1 => -1 : illegal
4987   //    1 =>  0 : pass - return immediately
4988   //    0 => -1 : block; then set _Event to 0 before returning
4989 
4990   guarantee(_ParkHandle != NULL, "Invariant");
4991   // Invariant: Only the thread associated with the Event/PlatformEvent
4992   // may call park().
4993   // Consider: use atomic decrement instead of CAS-loop
4994   int v;
4995   for (;;) {
4996     v = _Event;
4997     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
4998   }
4999   guarantee((v == 0) || (v == 1), "invariant");
5000   if (v != 0) return;
5001 
5002   // Do this the hard way by blocking ...
5003   // TODO: consider a brief spin here, gated on the success of recent
5004   // spin attempts by this thread.
5005   while (_Event < 0) {
5006     DWORD rv = ::WaitForSingleObject(_ParkHandle, INFINITE);
5007     assert(rv == WAIT_OBJECT_0, "WaitForSingleObject failed");
5008   }
5009 
5010   // Usually we'll find _Event == 0 at this point, but as
5011   // an optional optimization we clear it, just in case can
5012   // multiple unpark() operations drove _Event up to 1.
5013   _Event = 0;
5014   OrderAccess::fence();
5015   guarantee(_Event >= 0, "invariant");
5016 }
5017 
5018 void os::PlatformEvent::unpark() {
5019   guarantee(_ParkHandle != NULL, "Invariant");
5020 
5021   // Transitions for _Event:
5022   //    0 => 1 : just return
5023   //    1 => 1 : just return
5024   //   -1 => either 0 or 1; must signal target thread
5025   //         That is, we can safely transition _Event from -1 to either
5026   //         0 or 1.
5027   // See also: "Semaphores in Plan 9" by Mullender & Cox
5028   //
5029   // Note: Forcing a transition from "-1" to "1" on an unpark() means
5030   // that it will take two back-to-back park() calls for the owning
5031   // thread to block. This has the benefit of forcing a spurious return
5032   // from the first park() call after an unpark() call which will help
5033   // shake out uses of park() and unpark() without condition variables.
5034 
5035   if (Atomic::xchg(1, &_Event) >= 0) return;
5036 
5037   ::SetEvent(_ParkHandle);
5038 }
5039 
5040 
5041 // JSR166
5042 // -------------------------------------------------------
5043 
5044 // The Windows implementation of Park is very straightforward: Basic
5045 // operations on Win32 Events turn out to have the right semantics to
5046 // use them directly. We opportunistically resuse the event inherited
5047 // from Monitor.
5048 
5049 void Parker::park(bool isAbsolute, jlong time) {
5050   guarantee(_ParkEvent != NULL, "invariant");
5051   // First, demultiplex/decode time arguments
5052   if (time < 0) { // don't wait
5053     return;
5054   } else if (time == 0 && !isAbsolute) {
5055     time = INFINITE;
5056   } else if (isAbsolute) {
5057     time -= os::javaTimeMillis(); // convert to relative time
5058     if (time <= 0) {  // already elapsed
5059       return;
5060     }
5061   } else { // relative
5062     time /= 1000000;  // Must coarsen from nanos to millis
5063     if (time == 0) {  // Wait for the minimal time unit if zero
5064       time = 1;
5065     }
5066   }
5067 
5068   JavaThread* thread = (JavaThread*)(Thread::current());
5069   assert(thread->is_Java_thread(), "Must be JavaThread");
5070   JavaThread *jt = (JavaThread *)thread;
5071 
5072   // Don't wait if interrupted or already triggered
5073   if (Thread::is_interrupted(thread, false) ||
5074       WaitForSingleObject(_ParkEvent, 0) == WAIT_OBJECT_0) {
5075     ResetEvent(_ParkEvent);
5076     return;
5077   } else {
5078     ThreadBlockInVM tbivm(jt);
5079     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5080     jt->set_suspend_equivalent();
5081 
5082     WaitForSingleObject(_ParkEvent, time);
5083     ResetEvent(_ParkEvent);
5084 
5085     // If externally suspended while waiting, re-suspend
5086     if (jt->handle_special_suspend_equivalent_condition()) {
5087       jt->java_suspend_self();
5088     }
5089   }
5090 }
5091 
5092 void Parker::unpark() {
5093   guarantee(_ParkEvent != NULL, "invariant");
5094   SetEvent(_ParkEvent);
5095 }
5096 
5097 // Run the specified command in a separate process. Return its exit value,
5098 // or -1 on failure (e.g. can't create a new process).
5099 int os::fork_and_exec(char* cmd) {
5100   STARTUPINFO si;
5101   PROCESS_INFORMATION pi;
5102 
5103   memset(&si, 0, sizeof(si));
5104   si.cb = sizeof(si);
5105   memset(&pi, 0, sizeof(pi));
5106   BOOL rslt = CreateProcess(NULL,   // executable name - use command line
5107                             cmd,    // command line
5108                             NULL,   // process security attribute
5109                             NULL,   // thread security attribute
5110                             TRUE,   // inherits system handles
5111                             0,      // no creation flags
5112                             NULL,   // use parent's environment block
5113                             NULL,   // use parent's starting directory
5114                             &si,    // (in) startup information
5115                             &pi);   // (out) process information
5116 
5117   if (rslt) {
5118     // Wait until child process exits.
5119     WaitForSingleObject(pi.hProcess, INFINITE);
5120 
5121     DWORD exit_code;
5122     GetExitCodeProcess(pi.hProcess, &exit_code);
5123 
5124     // Close process and thread handles.
5125     CloseHandle(pi.hProcess);
5126     CloseHandle(pi.hThread);
5127 
5128     return (int)exit_code;
5129   } else {
5130     return -1;
5131   }
5132 }
5133 
5134 //--------------------------------------------------------------------------------------------------
5135 // Non-product code
5136 
5137 static int mallocDebugIntervalCounter = 0;
5138 static int mallocDebugCounter = 0;
5139 bool os::check_heap(bool force) {
5140   if (++mallocDebugCounter < MallocVerifyStart && !force) return true;
5141   if (++mallocDebugIntervalCounter >= MallocVerifyInterval || force) {
5142     // Note: HeapValidate executes two hardware breakpoints when it finds something
5143     // wrong; at these points, eax contains the address of the offending block (I think).
5144     // To get to the exlicit error message(s) below, just continue twice.
5145     HANDLE heap = GetProcessHeap();
5146 
5147     // If we fail to lock the heap, then gflags.exe has been used
5148     // or some other special heap flag has been set that prevents
5149     // locking. We don't try to walk a heap we can't lock.
5150     if (HeapLock(heap) != 0) {
5151       PROCESS_HEAP_ENTRY phe;
5152       phe.lpData = NULL;
5153       while (HeapWalk(heap, &phe) != 0) {
5154         if ((phe.wFlags & PROCESS_HEAP_ENTRY_BUSY) &&
5155             !HeapValidate(heap, 0, phe.lpData)) {
5156           tty->print_cr("C heap has been corrupted (time: %d allocations)", mallocDebugCounter);
5157           tty->print_cr("corrupted block near address %#x, length %d", phe.lpData, phe.cbData);
5158           fatal("corrupted C heap");
5159         }
5160       }
5161       DWORD err = GetLastError();
5162       if (err != ERROR_NO_MORE_ITEMS && err != ERROR_CALL_NOT_IMPLEMENTED) {
5163         fatal(err_msg("heap walk aborted with error %d", err));
5164       }
5165       HeapUnlock(heap);
5166     }
5167     mallocDebugIntervalCounter = 0;
5168   }
5169   return true;
5170 }
5171 
5172 
5173 bool os::find(address addr, outputStream* st) {
5174   // Nothing yet
5175   return false;
5176 }
5177 
5178 LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) {
5179   DWORD exception_code = e->ExceptionRecord->ExceptionCode;
5180 
5181   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
5182     JavaThread* thread = (JavaThread*)ThreadLocalStorage::get_thread_slow();
5183     PEXCEPTION_RECORD exceptionRecord = e->ExceptionRecord;
5184     address addr = (address) exceptionRecord->ExceptionInformation[1];
5185 
5186     if (os::is_memory_serialize_page(thread, addr)) {
5187       return EXCEPTION_CONTINUE_EXECUTION;
5188     }
5189   }
5190 
5191   return EXCEPTION_CONTINUE_SEARCH;
5192 }
5193 
5194 // We don't build a headless jre for Windows
5195 bool os::is_headless_jre() { return false; }
5196 
5197 static jint initSock() {
5198   WSADATA wsadata;
5199 
5200   if (!os::WinSock2Dll::WinSock2Available()) {
5201     jio_fprintf(stderr, "Could not load Winsock (error: %d)\n",
5202                 ::GetLastError());
5203     return JNI_ERR;
5204   }
5205 
5206   if (os::WinSock2Dll::WSAStartup(MAKEWORD(2,2), &wsadata) != 0) {
5207     jio_fprintf(stderr, "Could not initialize Winsock (error: %d)\n",
5208                 ::GetLastError());
5209     return JNI_ERR;
5210   }
5211   return JNI_OK;
5212 }
5213 
5214 struct hostent* os::get_host_by_name(char* name) {
5215   return (struct hostent*)os::WinSock2Dll::gethostbyname(name);
5216 }
5217 
5218 int os::socket_close(int fd) {
5219   return ::closesocket(fd);
5220 }
5221 
5222 int os::socket(int domain, int type, int protocol) {
5223   return ::socket(domain, type, protocol);
5224 }
5225 
5226 int os::connect(int fd, struct sockaddr* him, socklen_t len) {
5227   return ::connect(fd, him, len);
5228 }
5229 
5230 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5231   return ::recv(fd, buf, (int)nBytes, flags);
5232 }
5233 
5234 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5235   return ::send(fd, buf, (int)nBytes, flags);
5236 }
5237 
5238 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5239   return ::send(fd, buf, (int)nBytes, flags);
5240 }
5241 
5242 // WINDOWS CONTEXT Flags for THREAD_SAMPLING
5243 #if defined(IA32)
5244   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
5245 #elif defined (AMD64)
5246   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
5247 #endif
5248 
5249 // returns true if thread could be suspended,
5250 // false otherwise
5251 static bool do_suspend(HANDLE* h) {
5252   if (h != NULL) {
5253     if (SuspendThread(*h) != ~0) {
5254       return true;
5255     }
5256   }
5257   return false;
5258 }
5259 
5260 // resume the thread
5261 // calling resume on an active thread is a no-op
5262 static void do_resume(HANDLE* h) {
5263   if (h != NULL) {
5264     ResumeThread(*h);
5265   }
5266 }
5267 
5268 // retrieve a suspend/resume context capable handle
5269 // from the tid. Caller validates handle return value.
5270 void get_thread_handle_for_extended_context(HANDLE* h,
5271                                             OSThread::thread_id_t tid) {
5272   if (h != NULL) {
5273     *h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tid);
5274   }
5275 }
5276 
5277 // Thread sampling implementation
5278 //
5279 void os::SuspendedThreadTask::internal_do_task() {
5280   CONTEXT    ctxt;
5281   HANDLE     h = NULL;
5282 
5283   // get context capable handle for thread
5284   get_thread_handle_for_extended_context(&h, _thread->osthread()->thread_id());
5285 
5286   // sanity
5287   if (h == NULL || h == INVALID_HANDLE_VALUE) {
5288     return;
5289   }
5290 
5291   // suspend the thread
5292   if (do_suspend(&h)) {
5293     ctxt.ContextFlags = sampling_context_flags;
5294     // get thread context
5295     GetThreadContext(h, &ctxt);
5296     SuspendedThreadTaskContext context(_thread, &ctxt);
5297     // pass context to Thread Sampling impl
5298     do_task(context);
5299     // resume thread
5300     do_resume(&h);
5301   }
5302 
5303   // close handle
5304   CloseHandle(h);
5305 }
5306 
5307 
5308 // Kernel32 API
5309 typedef SIZE_T (WINAPI* GetLargePageMinimum_Fn)(void);
5310 typedef LPVOID (WINAPI *VirtualAllocExNuma_Fn)(HANDLE, LPVOID, SIZE_T, DWORD, DWORD, DWORD);
5311 typedef BOOL (WINAPI *GetNumaHighestNodeNumber_Fn)(PULONG);
5312 typedef BOOL (WINAPI *GetNumaNodeProcessorMask_Fn)(UCHAR, PULONGLONG);
5313 typedef USHORT (WINAPI* RtlCaptureStackBackTrace_Fn)(ULONG, ULONG, PVOID*, PULONG);
5314 
5315 GetLargePageMinimum_Fn      os::Kernel32Dll::_GetLargePageMinimum = NULL;
5316 VirtualAllocExNuma_Fn       os::Kernel32Dll::_VirtualAllocExNuma = NULL;
5317 GetNumaHighestNodeNumber_Fn os::Kernel32Dll::_GetNumaHighestNodeNumber = NULL;
5318 GetNumaNodeProcessorMask_Fn os::Kernel32Dll::_GetNumaNodeProcessorMask = NULL;
5319 RtlCaptureStackBackTrace_Fn os::Kernel32Dll::_RtlCaptureStackBackTrace = NULL;
5320 
5321 
5322 BOOL                        os::Kernel32Dll::initialized = FALSE;
5323 SIZE_T os::Kernel32Dll::GetLargePageMinimum() {
5324   assert(initialized && _GetLargePageMinimum != NULL,
5325          "GetLargePageMinimumAvailable() not yet called");
5326   return _GetLargePageMinimum();
5327 }
5328 
5329 BOOL os::Kernel32Dll::GetLargePageMinimumAvailable() {
5330   if (!initialized) {
5331     initialize();
5332   }
5333   return _GetLargePageMinimum != NULL;
5334 }
5335 
5336 BOOL os::Kernel32Dll::NumaCallsAvailable() {
5337   if (!initialized) {
5338     initialize();
5339   }
5340   return _VirtualAllocExNuma != NULL;
5341 }
5342 
5343 LPVOID os::Kernel32Dll::VirtualAllocExNuma(HANDLE hProc, LPVOID addr,
5344                                            SIZE_T bytes, DWORD flags,
5345                                            DWORD prot, DWORD node) {
5346   assert(initialized && _VirtualAllocExNuma != NULL,
5347          "NUMACallsAvailable() not yet called");
5348 
5349   return _VirtualAllocExNuma(hProc, addr, bytes, flags, prot, node);
5350 }
5351 
5352 BOOL os::Kernel32Dll::GetNumaHighestNodeNumber(PULONG ptr_highest_node_number) {
5353   assert(initialized && _GetNumaHighestNodeNumber != NULL,
5354          "NUMACallsAvailable() not yet called");
5355 
5356   return _GetNumaHighestNodeNumber(ptr_highest_node_number);
5357 }
5358 
5359 BOOL os::Kernel32Dll::GetNumaNodeProcessorMask(UCHAR node,
5360                                                PULONGLONG proc_mask) {
5361   assert(initialized && _GetNumaNodeProcessorMask != NULL,
5362          "NUMACallsAvailable() not yet called");
5363 
5364   return _GetNumaNodeProcessorMask(node, proc_mask);
5365 }
5366 
5367 USHORT os::Kernel32Dll::RtlCaptureStackBackTrace(ULONG FrameToSkip,
5368                                                  ULONG FrameToCapture,
5369                                                  PVOID* BackTrace,
5370                                                  PULONG BackTraceHash) {
5371   if (!initialized) {
5372     initialize();
5373   }
5374 
5375   if (_RtlCaptureStackBackTrace != NULL) {
5376     return _RtlCaptureStackBackTrace(FrameToSkip, FrameToCapture,
5377                                      BackTrace, BackTraceHash);
5378   } else {
5379     return 0;
5380   }
5381 }
5382 
5383 void os::Kernel32Dll::initializeCommon() {
5384   if (!initialized) {
5385     HMODULE handle = ::GetModuleHandle("Kernel32.dll");
5386     assert(handle != NULL, "Just check");
5387     _GetLargePageMinimum = (GetLargePageMinimum_Fn)::GetProcAddress(handle, "GetLargePageMinimum");
5388     _VirtualAllocExNuma = (VirtualAllocExNuma_Fn)::GetProcAddress(handle, "VirtualAllocExNuma");
5389     _GetNumaHighestNodeNumber = (GetNumaHighestNodeNumber_Fn)::GetProcAddress(handle, "GetNumaHighestNodeNumber");
5390     _GetNumaNodeProcessorMask = (GetNumaNodeProcessorMask_Fn)::GetProcAddress(handle, "GetNumaNodeProcessorMask");
5391     _RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_Fn)::GetProcAddress(handle, "RtlCaptureStackBackTrace");
5392     initialized = TRUE;
5393   }
5394 }
5395 
5396 
5397 
5398 #ifndef JDK6_OR_EARLIER
5399 
5400 void os::Kernel32Dll::initialize() {
5401   initializeCommon();
5402 }
5403 
5404 
5405 // Kernel32 API
5406 inline BOOL os::Kernel32Dll::SwitchToThread() {
5407   return ::SwitchToThread();
5408 }
5409 
5410 inline BOOL os::Kernel32Dll::SwitchToThreadAvailable() {
5411   return true;
5412 }
5413 
5414 // Help tools
5415 inline BOOL os::Kernel32Dll::HelpToolsAvailable() {
5416   return true;
5417 }
5418 
5419 inline HANDLE os::Kernel32Dll::CreateToolhelp32Snapshot(DWORD dwFlags,
5420                                                         DWORD th32ProcessId) {
5421   return ::CreateToolhelp32Snapshot(dwFlags, th32ProcessId);
5422 }
5423 
5424 inline BOOL os::Kernel32Dll::Module32First(HANDLE hSnapshot,
5425                                            LPMODULEENTRY32 lpme) {
5426   return ::Module32First(hSnapshot, lpme);
5427 }
5428 
5429 inline BOOL os::Kernel32Dll::Module32Next(HANDLE hSnapshot,
5430                                           LPMODULEENTRY32 lpme) {
5431   return ::Module32Next(hSnapshot, lpme);
5432 }
5433 
5434 inline void os::Kernel32Dll::GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo) {
5435   ::GetNativeSystemInfo(lpSystemInfo);
5436 }
5437 
5438 // PSAPI API
5439 inline BOOL os::PSApiDll::EnumProcessModules(HANDLE hProcess,
5440                                              HMODULE *lpModule, DWORD cb,
5441                                              LPDWORD lpcbNeeded) {
5442   return ::EnumProcessModules(hProcess, lpModule, cb, lpcbNeeded);
5443 }
5444 
5445 inline DWORD os::PSApiDll::GetModuleFileNameEx(HANDLE hProcess,
5446                                                HMODULE hModule,
5447                                                LPTSTR lpFilename,
5448                                                DWORD nSize) {
5449   return ::GetModuleFileNameEx(hProcess, hModule, lpFilename, nSize);
5450 }
5451 
5452 inline BOOL os::PSApiDll::GetModuleInformation(HANDLE hProcess,
5453                                                HMODULE hModule,
5454                                                LPMODULEINFO lpmodinfo,
5455                                                DWORD cb) {
5456   return ::GetModuleInformation(hProcess, hModule, lpmodinfo, cb);
5457 }
5458 
5459 inline BOOL os::PSApiDll::PSApiAvailable() {
5460   return true;
5461 }
5462 
5463 
5464 // WinSock2 API
5465 inline BOOL os::WinSock2Dll::WSAStartup(WORD wVersionRequested,
5466                                         LPWSADATA lpWSAData) {
5467   return ::WSAStartup(wVersionRequested, lpWSAData);
5468 }
5469 
5470 inline struct hostent* os::WinSock2Dll::gethostbyname(const char *name) {
5471   return ::gethostbyname(name);
5472 }
5473 
5474 inline BOOL os::WinSock2Dll::WinSock2Available() {
5475   return true;
5476 }
5477 
5478 // Advapi API
5479 inline BOOL os::Advapi32Dll::AdjustTokenPrivileges(HANDLE TokenHandle,
5480                                                    BOOL DisableAllPrivileges,
5481                                                    PTOKEN_PRIVILEGES NewState,
5482                                                    DWORD BufferLength,
5483                                                    PTOKEN_PRIVILEGES PreviousState,
5484                                                    PDWORD ReturnLength) {
5485   return ::AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, NewState,
5486                                  BufferLength, PreviousState, ReturnLength);
5487 }
5488 
5489 inline BOOL os::Advapi32Dll::OpenProcessToken(HANDLE ProcessHandle,
5490                                               DWORD DesiredAccess,
5491                                               PHANDLE TokenHandle) {
5492   return ::OpenProcessToken(ProcessHandle, DesiredAccess, TokenHandle);
5493 }
5494 
5495 inline BOOL os::Advapi32Dll::LookupPrivilegeValue(LPCTSTR lpSystemName,
5496                                                   LPCTSTR lpName,
5497                                                   PLUID lpLuid) {
5498   return ::LookupPrivilegeValue(lpSystemName, lpName, lpLuid);
5499 }
5500 
5501 inline BOOL os::Advapi32Dll::AdvapiAvailable() {
5502   return true;
5503 }
5504 
5505 void* os::get_default_process_handle() {
5506   return (void*)GetModuleHandle(NULL);
5507 }
5508 
5509 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
5510 // which is used to find statically linked in agents.
5511 // Additionally for windows, takes into account __stdcall names.
5512 // Parameters:
5513 //            sym_name: Symbol in library we are looking for
5514 //            lib_name: Name of library to look in, NULL for shared libs.
5515 //            is_absolute_path == true if lib_name is absolute path to agent
5516 //                                     such as "C:/a/b/L.dll"
5517 //            == false if only the base name of the library is passed in
5518 //               such as "L"
5519 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
5520                                     bool is_absolute_path) {
5521   char *agent_entry_name;
5522   size_t len;
5523   size_t name_len;
5524   size_t prefix_len = strlen(JNI_LIB_PREFIX);
5525   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
5526   const char *start;
5527 
5528   if (lib_name != NULL) {
5529     len = name_len = strlen(lib_name);
5530     if (is_absolute_path) {
5531       // Need to strip path, prefix and suffix
5532       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
5533         lib_name = ++start;
5534       } else {
5535         // Need to check for drive prefix
5536         if ((start = strchr(lib_name, ':')) != NULL) {
5537           lib_name = ++start;
5538         }
5539       }
5540       if (len <= (prefix_len + suffix_len)) {
5541         return NULL;
5542       }
5543       lib_name += prefix_len;
5544       name_len = strlen(lib_name) - suffix_len;
5545     }
5546   }
5547   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
5548   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
5549   if (agent_entry_name == NULL) {
5550     return NULL;
5551   }
5552   if (lib_name != NULL) {
5553     const char *p = strrchr(sym_name, '@');
5554     if (p != NULL && p != sym_name) {
5555       // sym_name == _Agent_OnLoad@XX
5556       strncpy(agent_entry_name, sym_name, (p - sym_name));
5557       agent_entry_name[(p-sym_name)] = '\0';
5558       // agent_entry_name == _Agent_OnLoad
5559       strcat(agent_entry_name, "_");
5560       strncat(agent_entry_name, lib_name, name_len);
5561       strcat(agent_entry_name, p);
5562       // agent_entry_name == _Agent_OnLoad_lib_name@XX
5563     } else {
5564       strcpy(agent_entry_name, sym_name);
5565       strcat(agent_entry_name, "_");
5566       strncat(agent_entry_name, lib_name, name_len);
5567     }
5568   } else {
5569     strcpy(agent_entry_name, sym_name);
5570   }
5571   return agent_entry_name;
5572 }
5573 
5574 #else
5575 // Kernel32 API
5576 typedef BOOL (WINAPI* SwitchToThread_Fn)(void);
5577 typedef HANDLE (WINAPI* CreateToolhelp32Snapshot_Fn)(DWORD, DWORD);
5578 typedef BOOL (WINAPI* Module32First_Fn)(HANDLE, LPMODULEENTRY32);
5579 typedef BOOL (WINAPI* Module32Next_Fn)(HANDLE, LPMODULEENTRY32);
5580 typedef void (WINAPI* GetNativeSystemInfo_Fn)(LPSYSTEM_INFO);
5581 
5582 SwitchToThread_Fn           os::Kernel32Dll::_SwitchToThread = NULL;
5583 CreateToolhelp32Snapshot_Fn os::Kernel32Dll::_CreateToolhelp32Snapshot = NULL;
5584 Module32First_Fn            os::Kernel32Dll::_Module32First = NULL;
5585 Module32Next_Fn             os::Kernel32Dll::_Module32Next = NULL;
5586 GetNativeSystemInfo_Fn      os::Kernel32Dll::_GetNativeSystemInfo = NULL;
5587 
5588 void os::Kernel32Dll::initialize() {
5589   if (!initialized) {
5590     HMODULE handle = ::GetModuleHandle("Kernel32.dll");
5591     assert(handle != NULL, "Just check");
5592 
5593     _SwitchToThread = (SwitchToThread_Fn)::GetProcAddress(handle, "SwitchToThread");
5594     _CreateToolhelp32Snapshot = (CreateToolhelp32Snapshot_Fn)
5595       ::GetProcAddress(handle, "CreateToolhelp32Snapshot");
5596     _Module32First = (Module32First_Fn)::GetProcAddress(handle, "Module32First");
5597     _Module32Next = (Module32Next_Fn)::GetProcAddress(handle, "Module32Next");
5598     _GetNativeSystemInfo = (GetNativeSystemInfo_Fn)::GetProcAddress(handle, "GetNativeSystemInfo");
5599     initializeCommon();  // resolve the functions that always need resolving
5600 
5601     initialized = TRUE;
5602   }
5603 }
5604 
5605 BOOL os::Kernel32Dll::SwitchToThread() {
5606   assert(initialized && _SwitchToThread != NULL,
5607          "SwitchToThreadAvailable() not yet called");
5608   return _SwitchToThread();
5609 }
5610 
5611 
5612 BOOL os::Kernel32Dll::SwitchToThreadAvailable() {
5613   if (!initialized) {
5614     initialize();
5615   }
5616   return _SwitchToThread != NULL;
5617 }
5618 
5619 // Help tools
5620 BOOL os::Kernel32Dll::HelpToolsAvailable() {
5621   if (!initialized) {
5622     initialize();
5623   }
5624   return _CreateToolhelp32Snapshot != NULL &&
5625          _Module32First != NULL &&
5626          _Module32Next != NULL;
5627 }
5628 
5629 HANDLE os::Kernel32Dll::CreateToolhelp32Snapshot(DWORD dwFlags,
5630                                                  DWORD th32ProcessId) {
5631   assert(initialized && _CreateToolhelp32Snapshot != NULL,
5632          "HelpToolsAvailable() not yet called");
5633 
5634   return _CreateToolhelp32Snapshot(dwFlags, th32ProcessId);
5635 }
5636 
5637 BOOL os::Kernel32Dll::Module32First(HANDLE hSnapshot,LPMODULEENTRY32 lpme) {
5638   assert(initialized && _Module32First != NULL,
5639          "HelpToolsAvailable() not yet called");
5640 
5641   return _Module32First(hSnapshot, lpme);
5642 }
5643 
5644 inline BOOL os::Kernel32Dll::Module32Next(HANDLE hSnapshot,
5645                                           LPMODULEENTRY32 lpme) {
5646   assert(initialized && _Module32Next != NULL,
5647          "HelpToolsAvailable() not yet called");
5648 
5649   return _Module32Next(hSnapshot, lpme);
5650 }
5651 
5652 
5653 BOOL os::Kernel32Dll::GetNativeSystemInfoAvailable() {
5654   if (!initialized) {
5655     initialize();
5656   }
5657   return _GetNativeSystemInfo != NULL;
5658 }
5659 
5660 void os::Kernel32Dll::GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo) {
5661   assert(initialized && _GetNativeSystemInfo != NULL,
5662          "GetNativeSystemInfoAvailable() not yet called");
5663 
5664   _GetNativeSystemInfo(lpSystemInfo);
5665 }
5666 
5667 // PSAPI API
5668 
5669 
5670 typedef BOOL (WINAPI *EnumProcessModules_Fn)(HANDLE, HMODULE *, DWORD, LPDWORD);
5671 typedef BOOL (WINAPI *GetModuleFileNameEx_Fn)(HANDLE, HMODULE, LPTSTR, DWORD);
5672 typedef BOOL (WINAPI *GetModuleInformation_Fn)(HANDLE, HMODULE, LPMODULEINFO, DWORD);
5673 
5674 EnumProcessModules_Fn   os::PSApiDll::_EnumProcessModules = NULL;
5675 GetModuleFileNameEx_Fn  os::PSApiDll::_GetModuleFileNameEx = NULL;
5676 GetModuleInformation_Fn os::PSApiDll::_GetModuleInformation = NULL;
5677 BOOL                    os::PSApiDll::initialized = FALSE;
5678 
5679 void os::PSApiDll::initialize() {
5680   if (!initialized) {
5681     HMODULE handle = os::win32::load_Windows_dll("PSAPI.DLL", NULL, 0);
5682     if (handle != NULL) {
5683       _EnumProcessModules = (EnumProcessModules_Fn)::GetProcAddress(handle,
5684                                                                     "EnumProcessModules");
5685       _GetModuleFileNameEx = (GetModuleFileNameEx_Fn)::GetProcAddress(handle,
5686                                                                       "GetModuleFileNameExA");
5687       _GetModuleInformation = (GetModuleInformation_Fn)::GetProcAddress(handle,
5688                                                                         "GetModuleInformation");
5689     }
5690     initialized = TRUE;
5691   }
5692 }
5693 
5694 
5695 
5696 BOOL os::PSApiDll::EnumProcessModules(HANDLE hProcess, HMODULE *lpModule,
5697                                       DWORD cb, LPDWORD lpcbNeeded) {
5698   assert(initialized && _EnumProcessModules != NULL,
5699          "PSApiAvailable() not yet called");
5700   return _EnumProcessModules(hProcess, lpModule, cb, lpcbNeeded);
5701 }
5702 
5703 DWORD os::PSApiDll::GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule,
5704                                         LPTSTR lpFilename, DWORD nSize) {
5705   assert(initialized && _GetModuleFileNameEx != NULL,
5706          "PSApiAvailable() not yet called");
5707   return _GetModuleFileNameEx(hProcess, hModule, lpFilename, nSize);
5708 }
5709 
5710 BOOL os::PSApiDll::GetModuleInformation(HANDLE hProcess, HMODULE hModule,
5711                                         LPMODULEINFO lpmodinfo, DWORD cb) {
5712   assert(initialized && _GetModuleInformation != NULL,
5713          "PSApiAvailable() not yet called");
5714   return _GetModuleInformation(hProcess, hModule, lpmodinfo, cb);
5715 }
5716 
5717 BOOL os::PSApiDll::PSApiAvailable() {
5718   if (!initialized) {
5719     initialize();
5720   }
5721   return _EnumProcessModules != NULL &&
5722     _GetModuleFileNameEx != NULL &&
5723     _GetModuleInformation != NULL;
5724 }
5725 
5726 
5727 // WinSock2 API
5728 typedef int (PASCAL FAR* WSAStartup_Fn)(WORD, LPWSADATA);
5729 typedef struct hostent *(PASCAL FAR *gethostbyname_Fn)(...);
5730 
5731 WSAStartup_Fn    os::WinSock2Dll::_WSAStartup = NULL;
5732 gethostbyname_Fn os::WinSock2Dll::_gethostbyname = NULL;
5733 BOOL             os::WinSock2Dll::initialized = FALSE;
5734 
5735 void os::WinSock2Dll::initialize() {
5736   if (!initialized) {
5737     HMODULE handle = os::win32::load_Windows_dll("ws2_32.dll", NULL, 0);
5738     if (handle != NULL) {
5739       _WSAStartup = (WSAStartup_Fn)::GetProcAddress(handle, "WSAStartup");
5740       _gethostbyname = (gethostbyname_Fn)::GetProcAddress(handle, "gethostbyname");
5741     }
5742     initialized = TRUE;
5743   }
5744 }
5745 
5746 
5747 BOOL os::WinSock2Dll::WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData) {
5748   assert(initialized && _WSAStartup != NULL,
5749          "WinSock2Available() not yet called");
5750   return _WSAStartup(wVersionRequested, lpWSAData);
5751 }
5752 
5753 struct hostent* os::WinSock2Dll::gethostbyname(const char *name) {
5754   assert(initialized && _gethostbyname != NULL,
5755          "WinSock2Available() not yet called");
5756   return _gethostbyname(name);
5757 }
5758 
5759 BOOL os::WinSock2Dll::WinSock2Available() {
5760   if (!initialized) {
5761     initialize();
5762   }
5763   return _WSAStartup != NULL &&
5764     _gethostbyname != NULL;
5765 }
5766 
5767 typedef BOOL (WINAPI *AdjustTokenPrivileges_Fn)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
5768 typedef BOOL (WINAPI *OpenProcessToken_Fn)(HANDLE, DWORD, PHANDLE);
5769 typedef BOOL (WINAPI *LookupPrivilegeValue_Fn)(LPCTSTR, LPCTSTR, PLUID);
5770 
5771 AdjustTokenPrivileges_Fn os::Advapi32Dll::_AdjustTokenPrivileges = NULL;
5772 OpenProcessToken_Fn      os::Advapi32Dll::_OpenProcessToken = NULL;
5773 LookupPrivilegeValue_Fn  os::Advapi32Dll::_LookupPrivilegeValue = NULL;
5774 BOOL                     os::Advapi32Dll::initialized = FALSE;
5775 
5776 void os::Advapi32Dll::initialize() {
5777   if (!initialized) {
5778     HMODULE handle = os::win32::load_Windows_dll("advapi32.dll", NULL, 0);
5779     if (handle != NULL) {
5780       _AdjustTokenPrivileges = (AdjustTokenPrivileges_Fn)::GetProcAddress(handle,
5781                                                                           "AdjustTokenPrivileges");
5782       _OpenProcessToken = (OpenProcessToken_Fn)::GetProcAddress(handle,
5783                                                                 "OpenProcessToken");
5784       _LookupPrivilegeValue = (LookupPrivilegeValue_Fn)::GetProcAddress(handle,
5785                                                                         "LookupPrivilegeValueA");
5786     }
5787     initialized = TRUE;
5788   }
5789 }
5790 
5791 BOOL os::Advapi32Dll::AdjustTokenPrivileges(HANDLE TokenHandle,
5792                                             BOOL DisableAllPrivileges,
5793                                             PTOKEN_PRIVILEGES NewState,
5794                                             DWORD BufferLength,
5795                                             PTOKEN_PRIVILEGES PreviousState,
5796                                             PDWORD ReturnLength) {
5797   assert(initialized && _AdjustTokenPrivileges != NULL,
5798          "AdvapiAvailable() not yet called");
5799   return _AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, NewState,
5800                                 BufferLength, PreviousState, ReturnLength);
5801 }
5802 
5803 BOOL os::Advapi32Dll::OpenProcessToken(HANDLE ProcessHandle,
5804                                        DWORD DesiredAccess,
5805                                        PHANDLE TokenHandle) {
5806   assert(initialized && _OpenProcessToken != NULL,
5807          "AdvapiAvailable() not yet called");
5808   return _OpenProcessToken(ProcessHandle, DesiredAccess, TokenHandle);
5809 }
5810 
5811 BOOL os::Advapi32Dll::LookupPrivilegeValue(LPCTSTR lpSystemName,
5812                                            LPCTSTR lpName, PLUID lpLuid) {
5813   assert(initialized && _LookupPrivilegeValue != NULL,
5814          "AdvapiAvailable() not yet called");
5815   return _LookupPrivilegeValue(lpSystemName, lpName, lpLuid);
5816 }
5817 
5818 BOOL os::Advapi32Dll::AdvapiAvailable() {
5819   if (!initialized) {
5820     initialize();
5821   }
5822   return _AdjustTokenPrivileges != NULL &&
5823     _OpenProcessToken != NULL &&
5824     _LookupPrivilegeValue != NULL;
5825 }
5826 
5827 #endif
5828 
5829 #ifndef PRODUCT
5830 
5831 // test the code path in reserve_memory_special() that tries to allocate memory in a single
5832 // contiguous memory block at a particular address.
5833 // The test first tries to find a good approximate address to allocate at by using the same
5834 // method to allocate some memory at any address. The test then tries to allocate memory in
5835 // the vicinity (not directly after it to avoid possible by-chance use of that location)
5836 // This is of course only some dodgy assumption, there is no guarantee that the vicinity of
5837 // the previously allocated memory is available for allocation. The only actual failure
5838 // that is reported is when the test tries to allocate at a particular location but gets a
5839 // different valid one. A NULL return value at this point is not considered an error but may
5840 // be legitimate.
5841 // If -XX:+VerboseInternalVMTests is enabled, print some explanatory messages.
5842 void TestReserveMemorySpecial_test() {
5843   if (!UseLargePages) {
5844     if (VerboseInternalVMTests) {
5845       gclog_or_tty->print("Skipping test because large pages are disabled");
5846     }
5847     return;
5848   }
5849   // save current value of globals
5850   bool old_use_large_pages_individual_allocation = UseLargePagesIndividualAllocation;
5851   bool old_use_numa_interleaving = UseNUMAInterleaving;
5852 
5853   // set globals to make sure we hit the correct code path
5854   UseLargePagesIndividualAllocation = UseNUMAInterleaving = false;
5855 
5856   // do an allocation at an address selected by the OS to get a good one.
5857   const size_t large_allocation_size = os::large_page_size() * 4;
5858   char* result = os::reserve_memory_special(large_allocation_size, os::large_page_size(), NULL, false);
5859   if (result == NULL) {
5860     if (VerboseInternalVMTests) {
5861       gclog_or_tty->print("Failed to allocate control block with size "SIZE_FORMAT". Skipping remainder of test.",
5862                           large_allocation_size);
5863     }
5864   } else {
5865     os::release_memory_special(result, large_allocation_size);
5866 
5867     // allocate another page within the recently allocated memory area which seems to be a good location. At least
5868     // we managed to get it once.
5869     const size_t expected_allocation_size = os::large_page_size();
5870     char* expected_location = result + os::large_page_size();
5871     char* actual_location = os::reserve_memory_special(expected_allocation_size, os::large_page_size(), expected_location, false);
5872     if (actual_location == NULL) {
5873       if (VerboseInternalVMTests) {
5874         gclog_or_tty->print("Failed to allocate any memory at "PTR_FORMAT" size "SIZE_FORMAT". Skipping remainder of test.",
5875                             expected_location, large_allocation_size);
5876       }
5877     } else {
5878       // release memory
5879       os::release_memory_special(actual_location, expected_allocation_size);
5880       // only now check, after releasing any memory to avoid any leaks.
5881       assert(actual_location == expected_location,
5882              err_msg("Failed to allocate memory at requested location "PTR_FORMAT" of size "SIZE_FORMAT", is "PTR_FORMAT" instead",
5883              expected_location, expected_allocation_size, actual_location));
5884     }
5885   }
5886 
5887   // restore globals
5888   UseLargePagesIndividualAllocation = old_use_large_pages_individual_allocation;
5889   UseNUMAInterleaving = old_use_numa_interleaving;
5890 }
5891 #endif // PRODUCT
5892