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