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