source: trunk/openjdk/hotspot/src/os/windows/vm/os_windows.cpp @ 296

Last change on this file since 296 was 296, checked in by dmik, 9 years ago

hotspot: Use os::block_on_serialize_page_trap() when handling the serialize page exceptions in the generated code in the same way it is already used in the exception handler of the native code.

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