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

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

hotspot: Initialize Decoder to satisfy assertion.

The os::dll_address_to_function_name() function can be called at any time
so Decoder should be initialized. For some reason this was not done.

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