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