/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// Must be at least Windows 2000 or XP to use VectoredExceptions and IsDebuggerPresent
// no precompiled headers
#include "classfile/classLoader.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/icBuffer.hpp"
#include "code/vtableStubs.hpp"
#include "compiler/compileBroker.hpp"
#include "interpreter/interpreter.hpp"
#include "jvm_windows.h"
#include "memory/allocation.inline.hpp"
#include "memory/filemap.hpp"
#include "mutex_windows.inline.hpp"
#include "oops/oop.inline.hpp"
#include "os_share_windows.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm_misc.hpp"
#include "runtime/arguments.hpp"
#include "runtime/extendedPC.hpp"
#include "runtime/globals.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/osThread.hpp"
#include "runtime/perfMemory.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/statSampler.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/threadCritical.hpp"
#include "services/attachListener.hpp"
#include "services/memTracker.hpp"
#include "services/runtimeService.hpp"
#include "thread_windows.inline.hpp"
#include "utilities/decoder.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
#include "utilities/growableArray.hpp"
#include "utilities/vmError.hpp"
#ifdef TARGET_ARCH_x86
# include "assembler_x86.inline.hpp"
# include "nativeInst_x86.hpp"
#endif
#ifdef _DEBUG
#include <crtdbg.h>
#endif
#include <windows.h>
#include <objidl.h>
#include <shlobj.h>
#include <malloc.h>
#include <signal.h>
#include <direct.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <process.h> // For _beginthreadex(), _endthreadex()
#include <imagehlp.h> // For os::dll_address_to_function_name
/* for enumerating dll libraries */
#include <vdmdbg.h>
// for timer info max values which include all bits
// Values of PE COFF
static int main_thread_id;
#ifdef _WIN64
#endif
#ifdef _M_IA64
#else
#endif
// save DLL module handle, used by GetModuleFileName
switch (reason) {
case DLL_PROCESS_ATTACH:
timeBeginPeriod(1L);
break;
case DLL_PROCESS_DETACH:
timeEndPeriod(1L);
#ifdef _WIN64
if (topLevelVectoredExceptionHandler != NULL) {
}
#endif
break;
default:
break;
}
return true;
}
const double high = (double) ((unsigned int) ~0);
return result;
}
// Implementation of os
}
// No setuid programs under Windows.
return false;
}
// This method is a periodic task to check for misbehaving JNI applications
// under CheckJNI, we can add any periodic checks here.
// For Windows at the moment does nothing
return;
}
#ifndef _WIN64
// previous UnhandledExceptionFilter, if there is one
#endif
/* sysclasspath, java_home, dll_dir */
{
char *home_path;
char *dll_path;
char *pslash;
// Found the full path to jvm[_g].dll.
// Now cut the path to <java_home>/jre if we can.
}
}
return;
return;
return;
}
/* library_path */
{
/* Win32 library search order (See the documentation for LoadLibrary):
*
* 1. The directory from which application is loaded.
* 2. The system wide Java Extensions directory (Java only)
* 3. System directory (GetSystemDirectory)
* 4. Windows directory (GetWindowsDirectory)
* 5. The PATH environment variable
* 6. The current directory
*/
char *library_path;
library_path[0] = '\0';
if (path_str) {
}
}
/* Default extensions directory */
{
}
/* Default endorsed standards directory. */
{
}
#ifndef _WIN64
// set our UnhandledExceptionFilter and save any previous one
#endif
// Done
return;
}
DebugBreak();
}
// Invoked from the BREAKPOINT Macro
os::breakpoint();
}
/*
* RtlCaptureStackBackTrace Windows API may not exist prior to Windows XP.
* So far, this method is only used by Native Memory Tracking, which is
* only supported on Windows XP or later.
*/
#ifdef _NMT_NOINLINE_
n ++;
#endif
return pc;
}
return NULL;
}
// os::current_stack_base()
//
// Returns the base of the stack, which is the stack's
// starting address. This function must be called
// while running on the stack of the thread being queried.
// Add up the sizes of all the regions with the same
// AllocationBase.
while( 1 )
{
else
break;
}
#ifdef _M_IA64
// IA64 has memory and register stacks
#endif
return stack_bottom + stack_size;
}
return sz;
}
if (time_struct_ptr != NULL) {
*res = *time_struct_ptr;
return res;
}
return NULL;
}
// Thread start routine for all new Java threads
// Try to randomize the cache line index of hot stack frames.
// This helps when threads of the same stack traces evict each other's
// cache lines. The threads can be either from the same JVM instance, or
// from different JVM instances. The benefit is especially true for
// processors with hyperthreading technology.
static int counter = 0;
if (UseNUMA) {
if (lgrp_id != -1) {
}
}
if (UseVectoredExceptions) {
// If we are using vectored exception we don't need to set a SEH
}
else {
// Install a win32 structured exception handler around every thread created
// by VM, so VM can genrate error dump when an exception occurred in non-
// Java thread (e.g. VM thread).
__try {
(_EXCEPTION_POINTERS*)_exception_info())) {
// Nothing to do.
}
}
// One less thread is executing
// When the VMThread gets here, the main thread may have already exited
// which frees the CodeHeap containing the Atomic::add code
}
return 0;
}
// Allocate the OSThread object
// Initialize support for Java interrupts
if (interrupt_event == NULL) {
delete osthread;
return NULL;
}
// Store info on the Win32 thread into the OSThread
if (UseNUMA) {
if (lgrp_id != -1) {
}
}
// Initial thread state is INITIALIZED, not SUSPENDED
return osthread;
}
#ifdef ASSERT
#endif
&thread_h, THREAD_ALL_ACCESS, false, 0)) {
fatal("DuplicateHandle failed\n");
}
(int)current_thread_id());
return false;
}
// Initial thread state is RUNNABLE
return true;
}
#ifdef ASSERT
#endif
if (_starting_thread == NULL) {
if (_starting_thread == NULL) {
return false;
}
}
// The primordial thread is runnable from the start)
return true;
}
// Allocate and initialize a new OSThread
unsigned thread_id;
// Allocate the OSThread object
return false;
}
// Initialize support for Java interrupts
if (interrupt_event == NULL) {
delete osthread;
return NULL;
}
osthread->set_interrupted(false);
if (stack_size == 0) {
switch (thr_type) {
case os::java_thread:
// Java threads use ThreadStackSize which default value can be changed with the flag -Xss
if (JavaThread::stack_size_at_create() > 0)
break;
case os::compiler_thread:
if (CompilerThreadStackSize > 0) {
break;
} // else fall through:
// use VMThreadStackSize if CompilerThreadStackSize is not defined
case os::pgc_thread:
case os::cgc_thread:
case os::watcher_thread:
break;
}
}
// Create the Win32 thread
//
// Contrary to what MSDN document says, "stack_size" in _beginthreadex()
// does not specify stack size. Instead, it specifies the size of
// initially committed space. The stack size is determined by
// PE header in the executable. If the committed "stack_size" is larger
// than default value in the PE header, the stack is rounded up to the
// nearest multiple of 1MB. For example if the launcher has default
// stack size of 320k, specifying any size less than 320k does not
// affect the actual stack size at all, it only affects the initial
// commitment. On the other hand, specifying 'stack_size' larger than
// default value may cause significant increase in memory usage, because
// not only the stack space will be rounded up to MB, but also the
// entire space is committed upfront.
//
// Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION'
// for CreateThread() that can treat 'stack_size' as stack size. However we
// are not supposed to call CreateThread() directly according to MSDN
// document because JVM uses C runtime library. The good news is that the
// flag appears to work with _beginthredex() as well.
#endif
(unsigned)stack_size,
(unsigned (__stdcall *)(void*)) java_start,
&thread_id);
if (thread_handle == NULL) {
// perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again
// without the flag.
(unsigned)stack_size,
(unsigned (__stdcall *)(void*)) java_start,
&thread_id);
}
if (thread_handle == NULL) {
// Need to clean up stuff we've allocated so far
delete osthread;
return NULL;
}
// Store info on the Win32 thread into the OSThread
// Initial thread state is INITIALIZED, not SUSPENDED
// The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
return true;
}
// Free Win32 resources related to the OSThread
delete osthread;
}
static int has_performance_count = 0;
return result;
}
if (has_performance_count) {
} else {
}
}
if (has_performance_count) {
return performance_frequency;
} else {
// the FILETIME time is the number of 100-nanosecond intervals since January 1,1601.
return 10000000;
}
}
return win32::available_memory();
}
// Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
// value if total memory is larger than 4GB
}
return win32::physical_memory();
}
#ifdef _LP64
return size;
#else
// Limit to 1400m because of the 2gb address space wall
#endif
}
// VC6 lacks DWORD_PTR
#if _MSC_VER < 1300
#endif
// Nof active processors is number of bits in process affinity mask
int bitcount = 0;
while (lpProcessAffinityMask != 0) {
bitcount++;
}
return bitcount;
} else {
return proc_count;
}
}
// Not yet implemented.
return;
}
// Not yet implemented.
return false;
}
// Not yet implemented.
return false;
}
static void initialize_performance_counter() {
if (QueryPerformanceFrequency(&count)) {
} else {
}
}
return (double) elapsed_counter() / (double) elapsed_frequency();
}
// Windows format:
// The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
// Java format:
// Java standards require the number of milliseconds since 1/1/1970
// Constant offset - calculated using offset()
// Fake time counter for reproducible results when debugging
#ifdef ASSERT
// Just to be safe, recalculate the offset in debug mode
static int _has_calculated_offset = 0;
if (_has_calculated_offset) return _calculated_offset;
java_origin.wHour = 0;
java_origin.wMinute = 0;
java_origin.wSecond = 0;
java_origin.wMilliseconds = 0;
}
return _calculated_offset;
}
#else
return _offset;
}
#endif
return (a - offset()) / 10000;
}
return result;
}
// For now, we say that Windows does not support vtime. I have no idea
// whether it can actually be made to (DLD, 9/13/05).
// better than nothing, but not much
return elapsedTime();
}
if (UseFakeTimers) {
return fake_time++;
} else {
return windows_to_java_time(wt);
}
}
if (!has_performance_count) {
} else {
return time;
}
}
if (!has_performance_count) {
// javaTimeMillis() doesn't have much percision,
// but it is not going to wrap -- so all 64 bits
// this is a wall clock timer, so may skip
info_ptr->may_skip_backward = true;
info_ptr->may_skip_forward = true;
} else {
if (freq < NANOSECS_PER_SEC) {
// the performance counter is 64 bits and we will
// be multiplying it -- so no wrap in 64 bits
} else if (freq > NANOSECS_PER_SEC) {
// use the max value the counter can reach to
// determine the max value which could be returned
} else {
// the performance counter is 64 bits and we will
// be using it directly -- so no wrap in 64 bits
}
// using a counter, so no skipping
info_ptr->may_skip_backward = false;
info_ptr->may_skip_forward = false;
}
}
GetLocalTime(&st);
return buf;
}
double* process_user_time,
double* process_system_time) {
&user_time);
if (result != 0) {
return true;
} else {
return false;
}
}
// allow PerfMemory to attempt cleanup of any persistent resources
// flush buffered output, finish log files
// Check for abort hook
if (abort_hook != NULL) {
abort_hook();
}
}
static BOOL (WINAPI *_MiniDumpWriteDump) ( HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION,
void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize) {
static const char* cwd;
// If running on a client version of Windows and user has not explicitly enabled dumping
VMError::report_coredump_status("Minidumps are not enabled by default on client versions of Windows", false);
return;
// If running on a server version of Windows and user has explictly disabled dumping
} else if (os::win32::is_windows_server() && !FLAG_IS_DEFAULT(CreateMinidumpOnCrash) && !CreateMinidumpOnCrash) {
return;
}
return;
}
if (_MiniDumpWriteDump == NULL) {
return;
}
// API_VERSION_NUMBER 11 or higher contains the ones we want though
#if API_VERSION_NUMBER >= 11
#endif
if (dumpFile == INVALID_HANDLE_VALUE) {
return;
}
} else {
}
// Older versions of dbghelp.dll (the one shipped with Win2003 for example) may not support all
// the dump types we really want. If first call fails, lets fall back to just use MiniDumpWithFullMemory then.
_MiniDumpWriteDump(hProcess, processId, dumpFile, (MINIDUMP_TYPE)MiniDumpWithFullMemory, pmei, NULL, NULL) == false) {
} else {
}
}
{
// no core dump on Windows
::exit(1);
}
// Die immediately, no exit hook, no abort hook, no cleanup.
_exit(-1);
}
// * dirent_md.c 1.15 00/02/02
//
// The declarations for DIR and struct dirent are in jvm_win32.h.
/* Caller must have already run dirname through JVM_NativePath, which removes
duplicate slashes and converts all instances of '/' into '\\'. */
DIR *
{
if (dirp == 0) {
return 0;
}
/*
* Win32 accepts "\" in its POSIX stat(), but refuses to treat it
* as a directory in FindFirstFile(). We detect this case here and
* prepend the current drive name.
*/
}
return 0;
}
if (fattr == 0xffffffff) {
return 0;
} else if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
return 0;
}
/* Append "*.*", or possibly "\\*.*", to path */
/* No '\\' needed for cases like "Z:" or "Z:\" */
} else {
}
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
return 0;
}
}
return dirp;
}
/* parameter dbuf unused on Windows */
struct dirent *
{
return 0;
}
if (GetLastError() == ERROR_INVALID_HANDLE) {
return 0;
}
}
}
int
{
return -1;
}
}
return 0;
}
// This must be hard coded because it's the system's temporary
// directory not the java application's temp directory, ala java.io.tmpdir.
return path_buf;
else{
path_buf[0]='\0';
return path_buf;
}
}
return false;
}
}
// Quietly truncates on buffer overflow. Should be an error.
*buffer = '\0';
return;
}
if (pnamelen == 0) {
} else if (c == ':' || c == '\\') {
int n;
for (int i = 0 ; i < n ; i++) {
// Really shouldn't be NULL, but check can't hurt
if (plen == 0) {
continue; // skip the empty path values
}
} else {
}
if (file_exists(buffer)) {
break;
}
}
// release the storage
for (int i = 0 ; i < n ; i++) {
}
}
}
} else {
}
}
// Needs to be in os specific directory because windows requires another
// header file <direct.h>
}
//-----------------------------------------------------------
// Helper functions for fatal error handler
#ifdef _WIN64
// Helper routine which returns true if address in
// within the NTDLL address space.
//
{
&minfo, sizeof(MODULEINFO)) )
return false;
return true;
else
return false;
}
#endif
// Enumerate all modules for a given process ID
//
// Notice that Windows 95/98/Me and Windows NT/2000/XP have
// different API for doing this. We use PSAPI.DLL on NT based
// Windows and ToolHelp on 95/98/Me.
// Callback function that is called by enumerate_modules() on
// every DLL module.
// Input parameters:
// int pid,
// char* module_file_name,
// address module_base_addr,
// unsigned module_size,
// void* param
// enumerate_modules for Windows NT, using PSAPI
{
int result = 0;
return 0;
}
sizeof(modules), &size_needed)) {
CloseHandle( hProcess );
return 0;
}
// number of modules that are currently loaded
// Get Full pathname:
filename[0] = '\0';
}
modinfo.SizeOfImage = 0;
}
// Invoke callback function
if (result) break;
}
CloseHandle( hProcess ) ;
return result;
}
// enumerate_modules for Windows 95/98/ME, using TOOLHELP
{
int result = 0;
return 0;
}
// Get a handle to a Toolhelp snapshot of the system
if( hSnapShot == INVALID_HANDLE_VALUE ) {
return FALSE ;
}
// iterate through all modules
while( not_done ) {
// invoke the callback
if (result) break;
}
return result;
}
{
// Get current process ID if caller doesn't provide it.
}
struct _modinfo {
};
if (!pmod) return -1;
// if a buffer is provided, copy path name to the buffer
}
return 1;
}
return 0;
}
// NOTE: the reason we don't use SymGetModuleInfo() is it doesn't always
// return the full path to the DLL file, sometimes it returns path
// to the corresponding PDB file (debug info); sometimes it only
// returns partial path, which makes life painful.
// buf already contains path name
return true;
} else {
return false;
}
}
return true;
}
return false;
}
// save the start and end address of jvm.dll into param[0] and param[1]
if (!param) return -1;
return 1;
}
return 0;
}
// check if addr is inside jvm.dll
assert(false, "Can't find jvm module.");
return false;
}
}
}
// print module info; param is outputStream*
if (!param) return -1;
return 0;
}
// Loads .dll/.so and
// in case of error it checks if .dll/.so was built for the
// same architecture as Hotspot is running on
{
{
return result;
}
if (errcode == ERROR_MOD_NOT_FOUND) {
return NULL;
}
// Parsing dll below
// If we can read dll-info and find that dll was built
// for an architecture other than Hotspot is running in
// - then print to buffer "DLL was built for a different architecture"
// else call os::lasterror to obtain system error message
// Read system error message into ebuf
// It may or may not be overwritten below (in the for loop and just above)
if (file_descriptor<0)
{
return NULL;
}
bool failed_to_get_lib_arch=
(
//Go to position 3c in the dll
||
// Read loacation of signature
(sizeof(signature_offset)!=
||
//Go to COFF File Header in dll
//that is located after"signature" (4 bytes long)
||
//Read field that contains code of architecture
// that dll was build for
(sizeof(lib_arch)!=
);
::close(file_descriptor);
{
// file i/o error - report os::lasterror(...) msg
return NULL;
}
typedef struct
{
char* arch_name;
} arch_t;
{IMAGE_FILE_MACHINE_I386, (char*)"IA 32"},
{IMAGE_FILE_MACHINE_AMD64, (char*)"AMD 64"},
{IMAGE_FILE_MACHINE_IA64, (char*)"IA 64"}
};
#if (defined _M_IA64)
#else
#endif
// Obtain a string for printf operation
// lib_arch_str shall contain string what platform this .dll was built for
// running_arch_str shall string contain what platform Hotspot was built for
for (unsigned int i=0;i<ARRAY_SIZE(arch_array);i++)
{
}
"Didn't find runing architecture code in arch_array");
// If the architure is right
// but some other error took place - report os::lasterror(...) msg
if (lib_arch == running_arch)
{
return NULL;
}
if (lib_arch_str!=NULL)
{
"Can't load %s-bit .dll on a %s-bit platform",
}
else
{
// don't know what architecture this dll was build for
"Can't load this .dll (machine code=0x%x) on a %s-bit platform",
}
return NULL;
}
}
}
}
return;
}
switch (os_vers) {
case 5002:
case 6000:
case 6001:
case 6002: {
// Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could
// find out whether we are running on 64 bit processor or not.
GetSystemInfo(&si);
} else {
}
if (os_vers == 5002) {
else
} else if (os_vers == 6000) {
else
} else if (os_vers == 6001) {
} else {
// Unrecognized windows, print out its major and minor versions
}
} else if (os_vers == 6002) {
} else {
}
} else { // future os
// Unrecognized windows, print out its major and minor versions
}
break;
}
default: // future windows, print out its major and minor versions
}
} else {
switch (os_vers) {
default: // future windows, print out its major and minor versions
}
}
}
// Nothing to do for now.
}
// Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
// value if total memory is larger than 4GB
}
switch (er->ExceptionInformation[0]) {
er->ExceptionInformation[0]);
}
" Mapped file inaccessible during execution, " \
}
} else {
if (num > 0) {
for (int i = 0; i < num; i++) {
}
}
}
}
// do nothing
}
// Find the full path to the current module, jvm.dll or jvm_g.dll
// Error checking.
assert(false, "must use a large-enough buffer");
buf[0] = '\0';
return;
}
// Lazy resolve the path to current module.
if (saved_jvm_path[0] != 0) {
return;
}
buf[0] = '\0';
if (Arguments::created_by_gamma_launcher()) {
// Support for the gamma launcher. Check for an
// JAVA_HOME environment variable
// and fix up the path so it looks like
// libjvm.so is installed there (append a fake suffix
// determine if this is a legacy image or modules image
// modules image doesn't have "jre" subdirectory
}
}
}
if(buf[0] == '\0') {
}
}
#ifndef _WIN64
#endif
}
#ifndef _WIN64
#endif
}
// This method is a copy of JDK's sysGetLastErrorString
// from src/windows/hpi/src/system_md.c
if ((errval = GetLastError()) != 0) {
// DOS error
NULL,
0,
buf,
NULL);
if (n > 3) {
// Drop final '.', CR, LF
buf[n] = '\0';
}
return n;
}
if (errno != 0) {
// C runtime error that has no corresponding DOS error code
buf[n] = '\0';
return n;
}
return 0;
}
if (error == 0)
return (int)error;
}
// sun.misc.Signal
// NOTE that this is a workaround for an apparent kernel bug where if
// a signal handler for SIGBREAK is installed then that signal handler
// takes priority over the console control handler for CTRL_CLOSE_EVENT.
// See bug 4416763.
// We need to reinstate the signal handler each time...
}
return (void*) UserHandler;
}
void (*oldHandler)(int) = sigbreakHandler;
sigbreakHandler = (void (*)(int)) handler;
return (void*) oldHandler;
} else {
}
}
}
// The Win32 C runtime library maps all console control events other than ^C
// into SIGBREAK, which makes it impossible to distinguish ^BREAK from close,
// logoff, and shutdown events. We therefore install our own console handler
// that raises SIGTERM for the latter cases.
//
switch(event) {
case CTRL_C_EVENT:
if (is_error_reported()) {
// Ctrl-C is pressed during error reporting, likely because the error
// handler fails to abort. Let VM die immediately.
}
return TRUE;
break;
case CTRL_BREAK_EVENT:
if (sigbreakHandler != NULL) {
(*sigbreakHandler)(SIGBREAK);
}
return TRUE;
break;
case CTRL_LOGOFF_EVENT: {
// Don't terminate JVM if it is running in a non-interactive session,
// such as a service process.
sizeof( USEROBJECTFLAGS), NULL)) {
// If it is a non-interactive session, let next handler to deal
// with it.
return FALSE;
}
}
}
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
return TRUE;
break;
default:
break;
}
return FALSE;
}
/*
* The following code is moved from os.cpp for making this
* code platform specific, which it is by its very nature.
*/
// Return maximum OS signal used + 1 for internal use only
// Used as exit signal for signal_thread
return NSIG;
}
// a counter for each possible signal value, including signal_thread exit signal
// Initialize signal structures
// Programs embedding the VM do not want it to attempt to receive
// events like CTRL_LOGOFF_EVENT, which are used to implement the
// shutdown hooks mechanism introduced in 1.3. For example, when
// the VM is run as part of a Windows NT service (i.e., a servlet
// engine in a web server), the correct behavior is for any console
// control handler to return FALSE, not TRUE, because the OS's
// "final" handler for such events allows the process to continue if
// it is a service (while terminating it if it is not a service).
// To make this behavior uniform and the mechanism simpler, we
// completely disable the VM's usage of these console events if -Xrs
// (=ReduceSignalUsage) is specified. This means, for example, that
// the CTRL-BREAK thread dump mechanism is also disabled in this
// case. See bugs 4323062, 4345157, and related bugs.
if (!ReduceSignalUsage) {
// Add a CTRL-C handler
}
}
}
}
while (true) {
for (int i = 0; i < NSIG + 1; i++) {
jint n = pending_signals[i];
return i;
}
}
if (!wait_for_signal) {
return -1;
}
bool threadIsSuspended;
do {
// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
// were we externally suspended while we were waiting?
if (threadIsSuspended) {
//
// The semaphore has been incremented, but while we were waiting
// another thread suspended us. We don't want to continue running
// while suspended because that would surprise the thread that
// suspended us.
//
}
} while (threadIsSuspended);
}
}
return check_pending_signals(false);
}
return check_pending_signals(true);
}
// Implicit OS exception handling
// Save pc in thread
#ifdef _M_IA64
// Set pc to handler
// Set pc to handler
#else
// Set pc to handler
#endif
// Continue the execution
return EXCEPTION_CONTINUE_EXECUTION;
}
// Used for PostMortemDump
extern "C" void safepoints();
extern "C" void find(int x);
extern "C" void events();
// According to Windows API documentation, an illegal instruction sequence should generate
// the 0xC000001C exception code. However, real world experience shows that occasionnaly
// the execution of an illegal instruction can generate the exception code 0xC000001E. This
// seems to be an undocumented feature of Win NT 4.0 (and probably other Windows systems).
// From "Execution Protection in the Windows Operating System" draft 0.35
// Once a system header becomes available, the "real" define should be
// included or copied here.
struct siglabel {
char *name;
int number;
};
// All Visual C++ exceptions thrown from code generated by the Microsoft Visual
// C++ compiler contain this error code. Because this is a compiler-generated
// error, the code is not listed in the Win32 API header files.
// The code is actually a cryptic mnemonic device, with the initial "E"
// standing for "exception" and the final 3 bytes (0x6D7363) representing the
// ASCII values of "msc".
NULL, 0
};
return buf;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// handle exception caused by idiv; should only happen for -MinInt/-1
// (division by zero is handled explicitly)
#ifdef _M_IA64
assert(0, "Fix Handle_IDiv_Exception");
// set correct result values and continue after idiv instruction
// Continue the execution
#else
// set correct result values and continue after idiv instruction
// Continue the execution
#endif
return EXCEPTION_CONTINUE_EXECUTION;
}
#ifndef _WIN64
//-----------------------------------------------------------------------------
// handle exception caused by native method modifying control word
switch (exception_code) {
case EXCEPTION_FLT_OVERFLOW:
case EXCEPTION_FLT_UNDERFLOW:
// Restore FPCW and mask out FLT exceptions
// Mask out pending FLT exceptions
return EXCEPTION_CONTINUE_EXECUTION;
}
}
if (prev_uef_handler != NULL) {
// We didn't handle this exception so pass it to the previous
// UnhandledExceptionFilter.
return (prev_uef_handler)(exceptionInfo);
}
return EXCEPTION_CONTINUE_SEARCH;
}
#else //_WIN64
/*
On Windows, the mxcsr control bits are non-volatile across calls
See also CR 6192333
If EXCEPTION_FLT_* happened after some native method modified
mxcsr - it is not a jvm fault.
However should we decide to restore of mxcsr after a faulty
native method we can uncomment following code
jint MxCsr = INITIAL_MXCSR;
// we can't use StubRoutines::addr_mxcsr_std()
// because in Win64 mxcsr is not saved there
if (MxCsr != ctx->MxCsr) {
ctx->MxCsr = MxCsr;
return EXCEPTION_CONTINUE_EXECUTION;
}
*/
#endif //_WIN64
// Fatal error reporting is single threaded so we can make this a
// static and preallocated. If it's more than MAX_PATH silently ignore
// it.
}
}
// If UseOsErrorReporting, this will return here and save the error file
// somewhere where we can find it in the minidump.
}
//-----------------------------------------------------------------------------
if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH;
#ifdef _M_IA64
#else
#endif
#ifndef _WIN64
// Execution protection violation - win32 running on AMD64 only
// Handled first to avoid misdiagnosis as a "normal" access violation;
// code for this condition.
if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
// Make sure the pc and the faulting address are sane.
//
// If an instruction spans a page boundary, and the page containing
// the beginning of the instruction is executable but the following
// page is not, the pc and the faulting address might be slightly
// different - we still want to unguard the 2nd page in this case.
//
// 15 bytes seems to be a (very) safe value for max instruction size.
bool pc_is_near_addr =
bool instr_spans_page_boundary =
// In conservative mode, don't unguard unless the address is in the VM
// Set memory to RWX and retry
os::MEM_PROT_RWX);
if (PrintMiscellaneous && Verbose) {
"at " INTPTR_FORMAT
}
// Set last_addr so if we fault again at the same address, we don't
// end up in an endless loop.
//
// There are two potential complications here. Two threads trapping
// at the same address at the same time could cause one of the
// threads to think it already unguarded, and abort the VM. Likely
// very rare.
//
// The other race involves two threads alternately trapping at
// different addresses and failing to unguard the page, resulting in
// an endless loop. This condition is probably even more unlikely
// than the first.
//
// Although both cases could be avoided by using locks or thread
// local last_addr, these solutions are unnecessary complication:
// this handler is a best-effort safety net, not a complete solution.
// It is disabled by default and should only be used as a workaround
// in case we missed any no-execute-unsafe VM code.
return EXCEPTION_CONTINUE_EXECUTION;
}
}
// Last unguard failed or not unguarding
return EXCEPTION_CONTINUE_SEARCH;
}
}
#endif // _WIN64
// Check to see if we caught the safepoint code in the
// process of write protecting the memory serialization page.
// It write enables the page immediately after protecting it
// so just return.
if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) {
// Block current thread until the memory serialize page permission restored.
return EXCEPTION_CONTINUE_EXECUTION;
}
}
if (t != NULL && t->is_Java_thread()) {
// Handle potential stack overflows up front.
if (exception_code == EXCEPTION_STACK_OVERFLOW) {
if (os::uses_stack_guard_pages()) {
#ifdef _M_IA64
//
// If it's a legal stack address continue, Windows will map it in.
//
return EXCEPTION_CONTINUE_EXECUTION;
// The register save area is the same size as the memory stack
// and starts at the page just above the start of the memory stack.
// If we get a fault in this area, we've run out of register
// stack. If we are in java, try throwing a stack overflow exception.
"Register stack overflow, addr:%p, stack_base:%p\n",
// If not in java code, return and hope for the best.
}
#endif
if (thread->stack_yellow_zone_enabled()) {
// Yellow zone violation. The o/s has unprotected the first yellow
// zone page for us. Note: must call disable_stack_yellow_zone to
// update the enabled status, even if the zone contains only one page.
// If not in java code, return and hope for the best.
} else {
// Fatal red zone violation.
return EXCEPTION_CONTINUE_SEARCH;
}
} else if (in_java) {
// JVM-managed guard pages cannot be used on win95/98. The o/s provides
// a one-time-only guard page, which it has released to us. The next
// stack overflow on this thread will result in an ACCESS_VIOLATION.
return Handle_Exception(exceptionInfo,
} else {
// Can only return and hope for the best. Further stack growth will
// result in an ACCESS_VIOLATION.
return EXCEPTION_CONTINUE_EXECUTION;
}
} else if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
// Either stack overflow or null pointer exception.
if (in_java) {
// Stack overflow.
"should be caught by red zone code above.");
return Handle_Exception(exceptionInfo,
}
//
// Check for safepoint polling and implicit null
// We only expect null pointers in the stubs (vtable)
// the rest are checked explicitly now.
//
}
}
{
#ifdef _WIN64
//
// If it's a legal stack address map the entire region in
//
!ExecMem);
return EXCEPTION_CONTINUE_EXECUTION;
}
else
#endif
{
// Null pointer exception.
#ifdef _M_IA64
// We catch register stack overflows in compiled code by doing
// an explicit compare and executing a st8(G0, G0) if the
// BSP enters into our guard area. We test for the overflow
// condition and fall into the normal null pointer exception
// code if BSP hasn't overflowed.
if ( in_java ) {
if(thread->register_stack_overflow()) {
"GR7 doesn't contain register_stack_limit");
// Disable the yellow zone which sets the state that
// we've got a stack overflow problem.
if (thread->stack_yellow_zone_enabled()) {
}
// Give us some room to process the exception
// Update GR7 with the new limit so we can continue running
// compiled code.
return Handle_Exception(exceptionInfo,
} else {
//
// Check for implicit null
// We only expect null pointers in the stubs (vtable)
// the rest are checked explicitly now.
//
// an access to the first page of VM--assume it is a null pointer
address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
}
}
} // in_java
// IA64 doesn't use implicit null checking yet. So we shouldn't
// get here.
return EXCEPTION_CONTINUE_SEARCH;
#else /* !IA64 */
// Windows 98 reports faulting addresses incorrectly
address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
}
return EXCEPTION_CONTINUE_SEARCH;
#endif
}
}
}
#ifdef _WIN64
// Special care for fast JNI field accessors.
// jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks
// in and the heap gets shrunk before the field access.
if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
}
}
#endif
#ifdef _WIN64
// Windows will sometimes generate an access violation
// when we call malloc. Since we use VectoredExceptions
// on 64 bit platforms, we see this exception. We must
// pass this exception on so Windows can recover.
// We check to see if the pc of the fault is in NTDLL.DLL
// if so, we pass control on to Windows for handling.
#endif
// Stack overflow or null pointer exception in native code.
return EXCEPTION_CONTINUE_SEARCH;
}
if (in_java) {
switch (exception_code) {
return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO));
case EXCEPTION_INT_OVERFLOW:
return Handle_IDiv_Exception(exceptionInfo);
} // switch
}
#ifndef _WIN64
{
}
#endif //_WIN64
}
if (exception_code != EXCEPTION_BREAKPOINT) {
#ifndef _WIN64
#else
// Itanium Windows uses a VectoredExceptionHandler
// will get here. Continue the search for the right except block if
// the exception code is not a fatal code.
switch ( exception_code ) {
case EXCEPTION_STACK_OVERFLOW:
case EXCEPTION_INT_OVERFLOW:
}
break;
default:
break;
}
#endif
}
return EXCEPTION_CONTINUE_SEARCH;
}
#ifndef _WIN64
// Special care for fast JNI accessors.
// jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and
// the heap gets shrunk before the field access.
// Need to install our own structured exception handler since native code may
// install its own.
if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
__try { \
} \
return 0; \
}
switch (type) {
default: ShouldNotReachHere();
}
return (address)-1;
}
#endif
// Virtual Memory
}
// Windows large page support is available on Windows 2003. In order to use
// large page memory, the administrator must first assign additional privilege
// to the user:
// + select Control Panel -> Administrative Tools -> Local Security Policy
// + select Local Policies -> User Rights Assignment
// + reboot
// Note the above steps are needed for administrator as well, as administrators
// by default do not have the privilege to lock pages in memory.
//
// Note about Windows 2003: although the API supports committing large page
// memory on a page-by-page basis and VirtualAlloc() returns success under this
// scenario, I found through experiment it only uses large page if the entire
// memory region is reserved and committed in a single VirtualAlloc() call.
// This makes Windows large page support more or less like Solaris ISM, in
// that the entire heap must be committed upfront. This probably will change
// in the future, if so the code below needs to be revisited.
#ifndef MEM_LARGE_PAGES
#endif
// Container for NUMA node list info
class NUMANodeListHolder {
private:
void free_node_list() {
if (_numa_used_node_list != NULL) {
}
}
public:
// do rest of initialization in build routine (after function pointers are set up)
}
~NUMANodeListHolder() {
}
bool build() {
for (unsigned int i = 0; i <= highest_node_number; i++) {
if ((proc_aff_mask & proc_mask_numa_node)!=0) {
}
}
return (_numa_used_node_count > 1);
}
int get_node_list_entry(int n) {
// for indexes out of range, returns -1
}
static bool resolve_functions_for_large_page_init() {
}
static bool request_lock_memory_privilege() {
os::current_process_id());
// AdjustTokenPrivileges() may return TRUE even when it couldn't change the
// privilege. Check GetLastError() too. See MSDN document.
(GetLastError() == ERROR_SUCCESS)) {
return true;
}
}
return false;
}
static void cleanup_after_large_page_init() {
}
static bool numa_interleaving_init() {
bool success = false;
// print a warning if UseNUMAInterleaving flag is specified on command line
// NUMAInterleaveGranularity cannot be less than vm_allocation_granularity (or _large_page_size if using large pages)
size_t min_interleave_granularity = UseLargePages ? _large_page_size : os::vm_allocation_granularity();
if (numa_node_list_holder.build()) {
if (PrintMiscellaneous && Verbose) {
for (int i = 0; i < numa_node_list_holder.get_count(); i++) {
}
}
success = true;
} else {
WARN("Process does not cover multiple NUMA nodes.");
}
} else {
WARN("NUMA Interleaving is not supported by the operating system.");
}
if (!success) {
}
return success;
}
// this routine is used whenever we need to reserve a contiguous VA range
// but we need to make separate VirtualAlloc calls for each piece of the range
// Reasons for doing this:
// * UseLargePagesIndividualAllocation was set (normally only needed on WS2003 but possible to be set otherwise)
// * UseNUMAInterleaving requires a separate node for each piece
bool should_inject_error=false) {
char * p_buf;
// note: at setup time we guaranteed that NUMAInterleaveGranularity was aligned up to a page size
// first reserve enough address space in advance since we want to be
// able to break a single contiguous virtual address range into multiple
// large page commits but WS2003 does not allow reserving large page space
// so we just use 4K pages for reserve, this gives us a legal contiguous
// address space. then we will deallocate that reservation, and re alloc
// using large pages
if (bytes > size_of_reserve) {
// Overflowed.
return NULL;
}
size_of_reserve, // size of Reserve
// If reservation failed, return NULL
// we still need to round up to a page boundary (in case we are using large pages)
// but not to a chunk boundary (in case InterleavingGranularity doesn't align with page size)
// instead we handle this in the bytes_to_rq computation below
// now go through and allocate one chunk at a time until all bytes are
// allocated
// An overflow of align_size_up() would have been caught above
// in the calculation of size_of_reserve.
#ifdef ASSERT
// Variable for the failure injection
#endif
int count=0;
while (bytes_remaining) {
// select bytes_to_rq to get to the next chunk_size boundary
// Note allocate and commit
char * p_new;
#ifdef ASSERT
#else
const bool inject_error_now = false;
#endif
if (inject_error_now) {
} else {
if (!UseNUMAInterleaving) {
prot);
} else {
// get the next node to use from the used_node_list
prot,
node);
}
}
// Free any allocated pages
if (next_alloc_addr > p_buf) {
// Some memory was committed so release it.
// NMT has yet to record any individual blocks, so it
// need to create a dummy 'reserve' record to match
// the release.
}
#ifdef ASSERT
if (should_inject_error) {
if (TracePageSizes && Verbose) {
}
}
#endif
return NULL;
}
count++;
}
// Although the memory is allocated individually, it is returned as one.
// NMT records it as one block.
if ((flags & MEM_COMMIT) != 0) {
} else {
}
// made it this far, success
return p_buf;
}
if (!UseLargePages) return;
// print a warning if any large page related flag is specified on command line
bool success = false;
if (request_lock_memory_privilege()) {
if (s) {
WARN("JVM cannot use large pages bigger than 4mb.");
} else {
#endif
if (LargePageSizeInBytes && LargePageSizeInBytes % s == 0) {
} else {
_large_page_size = s;
}
success = true;
}
#endif
} else {
WARN("Large page is not supported by the processor.");
}
} else {
WARN("JVM cannot use large page memory because it does not have enough privilege to lock pages in memory.");
}
} else {
WARN("Large page is not supported by the operating system.");
}
_page_sizes[0] = _large_page_size;
_page_sizes[2] = 0;
}
}
// On win32, one cannot release just a part of reserved memory, it's an
// all or nothing deal. When we split a reservation, we must break the
// reservation into two reservations.
bool realloc) {
if (size > 0) {
if (realloc) {
}
}
}
}
return false;
}
// Multiple threads can race in this code but it's not possible to unmap small sections of
// virtual space to get requested alignment, like posix-like os's.
// Windows prevents multiple thread from remapping over each other so this loop is thread-safe.
"Alignment must be a multiple of allocation granularity (page size)");
do {
if (extra_base == NULL) {
return NULL;
}
// Do manual alignment
} while (aligned_base == NULL);
return aligned_base;
}
"reserve alignment");
char* res;
// note that if UseLargePages is on, all the areas that require interleaving
// will go thru reserve_memory_special rather than thru here.
if (!use_individual) {
} else {
// in numa interleaving, we have to allocate pages individually
// (well really chunks of NUMAInterleaveGranularity size)
warning("NUMA page allocation failed");
}
if( Verbose && PrintMiscellaneous ) {
reserveTimer.stop();
}
}
"Unexpected address from reserve.");
return res;
}
// Reserve memory at an arbitrary address, only if that area is
// available (and not reserved for something else).
// Windows os::reserve_memory() fails of the requested address range is
// not avilable.
}
return _large_page_size;
}
// Windows only uses large page memory when the entire region is reserved
// and committed in a single VirtualAlloc() call. This may change in the
// future, but with Windows 2003 it's not possible to commit on demand.
return false;
}
return true;
}
// with large pages, there are two cases where we need to use Individual Allocation
// 1) the UseLargePagesIndividualAllocation flag is set (set by default on WS2003)
// 2) NUMA Interleaving is enabled, in which case we use a different node for each page
if (TracePageSizes && Verbose) {
}
char * p_buf = allocate_pages_individually(bytes, addr, flags, prot, LargePagesIndividualAllocationInjectError);
// give an appropriate warning message
if (UseNUMAInterleaving) {
warning("NUMA large page allocation failed, UseLargePages flag ignored");
}
warning("Individually allocated large pages failed, "
"use -XX:-UseLargePagesIndividualAllocation to turn off");
}
return NULL;
}
return p_buf;
} else {
// normal policy just allocate it all at once
}
return res;
}
}
}
}
}
if (bytes == 0) {
// Don't bother the OS with noops.
return true;
}
// Don't attempt to print anything if the OS call fails. We're
// probably low on resources, so the print itself may cause crashes.
// unless we have NUMAInterleaving enabled, the range of a commit
// is always within a reserve covered by a single VirtualAlloc
// in that case we can just do a single commit for the requested size
if (!UseNUMAInterleaving) {
return false;
}
if (exec) {
// Windows doc says to use VirtualProtect to get execute permissions
return false;
}
}
return true;
} else {
// when NUMAInterleaving is enabled, the commit might cover a range that
// came from multiple VirtualAlloc reserves (using allocate_pages_individually).
// VirtualQuery can help us determine that. The RegionSize that VirtualQuery
// returns represents the number of bytes that can be committed in one step.
while (bytes_remaining > 0) {
PAGE_READWRITE) == NULL) {
exec);)
return false;
}
if (exec) {
exec);)
return false;
}
}
}
}
// if we made it this far, return true
return true;
}
bool exec) {
// alignment_hint is ignored on this OS
}
const char* mesg) {
}
}
const char* mesg) {
// alignment_hint is ignored on this OS
}
if (bytes == 0) {
// Don't bother the OS with noops.
return true;
}
}
}
}
}
// Set protections specified
bool is_committed) {
unsigned int p = 0;
switch (prot) {
case MEM_PROT_NONE: p = PAGE_NOACCESS; break;
case MEM_PROT_READ: p = PAGE_READONLY; break;
case MEM_PROT_RW: p = PAGE_READWRITE; break;
case MEM_PROT_RWX: p = PAGE_EXECUTE_READWRITE; break;
default:
}
// Strange enough, but on Win32 one can change protection only for committed
// memory, not a big deal anyway, as bytes less or equal than 64K
if (!is_committed) {
"cannot commit protection page");
}
// One cannot use os::guard_memory() here, as on Win32 guard page
// have different (one-shot) semantics, from MSDN on PAGE_GUARD:
//
// Pages in the region become guard pages. Any attempt to access a guard page
// causes the system to raise a STATUS_GUARD_PAGE exception and turn off
// the guard page status. Guard pages thus act as a one-time access alarm.
}
}
}
// Provide an answer for UMA systems
ids[0] = 0;
return 1;
} else {
// check for size bigger than actual groups_num
for (int i = 0; i < (int)size; i++) {
}
return size;
}
}
return false;
}
return end;
}
// Must never look like an address returned by reserve_memory,
// even in its subfields (as defined by the CPU immediate fields,
// if the CPU splits constants across multiple instructions).
return (char*)-1;
}
// Returns previous suspend state:
// 0: Thread was not suspended
// 1: Thread is running now
// >1: Thread is still suspended.
}
class HighResolutionInterval {
// The default timer resolution seems to be 10 milliseconds.
// (Where is this written down?)
// If someone wants to sleep for only a fraction of the default,
// then we set the timer resolution down to 1 millisecond for
// the duration of their interval.
// We carefully set the resolution back, since otherwise we
// seem to incur an overhead (3%?) that we don't need.
// CONSIDER: if ms is small, say 3, then we should run with a high resolution time.
// Buf if ms is large, say 500, or 503, we should avoid the call to timeBeginPeriod().
// Alternatively, we could compute the relative error (503/500 = .6%) and only use
// timeBeginPeriod() if the relative error exceeded some threshold.
// timeBeginPeriod() has been linked to problems with clock drift on win32 systems and
// to decreased efficiency related to increased timer "tick" rates. We want to minimize
// (a) calls to timeBeginPeriod() and timeEndPeriod() and (b) time spent with high
// resolution timers running.
private:
public:
if (resolution != 0) {
}
}
if (resolution != 0) {
}
resolution = 0L;
}
};
int res;
return res;
}
int result;
if (interruptable) {
// cleared by handle_special_suspend_equivalent_condition() or
// java_suspend_self() via check_and_wait_while_suspended()
result = OS_TIMEOUT;
} else {
osthread->set_interrupted(false);
}
delete phri; //if it is NULL, harmless
// were we externally suspended while we were waiting?
} else {
result = OS_TIMEOUT;
}
return result;
}
// Sleep forever; naked call to OS-specific sleep; use with CAUTION
while (true) { // sleep forever ...
}
}
// Use either SwitchToThread() or Sleep(0)
// Consider passing back the return value from SwitchToThread().
} else {
Sleep(0);
}
return os::YIELD_UNKNOWN ;
}
// Yields to all threads, including threads with lower priorities
Sleep(1);
}
// Win32 only gives you access to seven real priorities at a time,
// so we compress Java's ten down to seven. It would be better
// if we dynamically adjusted relative priorities.
THREAD_PRIORITY_IDLE, // 0 Entry should never be used
THREAD_PRIORITY_LOWEST, // 1 MinPriority
THREAD_PRIORITY_LOWEST, // 2
THREAD_PRIORITY_NORMAL, // 5 NormPriority
THREAD_PRIORITY_NORMAL, // 6
THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority
THREAD_PRIORITY_HIGHEST, // 10 MaxPriority
THREAD_PRIORITY_HIGHEST // 11 CriticalPriority
};
THREAD_PRIORITY_IDLE, // 0 Entry should never be used
THREAD_PRIORITY_LOWEST, // 1 MinPriority
THREAD_PRIORITY_LOWEST, // 2
THREAD_PRIORITY_NORMAL, // 5 NormPriority
THREAD_PRIORITY_HIGHEST, // 8
THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority
THREAD_PRIORITY_TIME_CRITICAL, // 10 MaxPriority
THREAD_PRIORITY_TIME_CRITICAL // 11 CriticalPriority
};
static int prio_init() {
// If ThreadPriorityPolicy is 1, switch tables
if (ThreadPriorityPolicy == 1) {
int i;
for (i = 0; i < CriticalPriority + 1; i++) {
}
}
}
return 0;
}
if (!UseThreadPriorities) return OS_OK;
}
if ( !UseThreadPriorities ) {
return OS_OK;
}
if (os_prio == THREAD_PRIORITY_ERROR_RETURN) {
assert(false, "GetThreadPriority failed");
return OS_ERR;
}
*priority_ptr = os_prio;
return OS_OK;
}
// Hint to the underlying OS that a task switch would not be good.
// Void return because it's a hint and can fail.
"possibility of dangling Thread pointer");
osthread->set_interrupted(true);
// More than one thread can get here with the same value of osthread,
// resulting in multiple notifications. We do, however, want the store
// to interrupted() to be visible to other threads before we post
// the interrupt event.
OrderAccess::release();
// For JSR166: unpark after setting status
if (thread->is_Java_thread())
}
"possibility of dangling Thread pointer");
// There is no synchronization between the setting of the interrupt
// and it being cleared here. It is critical - see 6535709 - that
// we only clear the interrupt state, and reset the interrupt event,
// if we are going to report that we were indeed interrupted - else
// an interrupt can be "lost", leading to spurious wakeups or lost wakeups
// depending on the timing
if (interrupted && clear_interrupted) {
osthread->set_interrupted(false);
} // Otherwise leave the interrupted state alone
return interrupted;
}
// Get's a pc (hint) for a running thread. Currently used only for profiling.
#ifdef _M_IA64
assert(0, "Fix get_thread_pc");
return ExtendedPC(NULL);
#else
#ifdef _M_AMD64
#else
#endif
} else {
return ExtendedPC(NULL);
}
#endif
}
// GetCurrentThreadId() returns DWORD
static int _initial_pid = 0;
{
}
// Processor level is not available on non-NT systems, use vm_version instead
GetSystemInfo(&si);
// also returns dwAvailPhys (free physical memory bytes), dwTotalVirtual, dwAvailVirtual,
// dwMemoryLoad (% of memory in use)
switch(oi.dwPlatformId) {
case VER_PLATFORM_WIN32_WINDOWS: _is_nt = false; break;
case VER_PLATFORM_WIN32_NT:
_is_nt = true;
{
if (os_vers == 5002) {
_is_windows_2003 = true;
}
_is_windows_server = true;
}
}
break;
default: fatal("Unknown platform");
}
"stack size not a multiple of page size");
// known to deadlock the system, if the VM issues to thread operations with
// a too high frequency, e.g., such as changing the priorities.
// The 6000 seems to work well - no deadlocks has been notices on the test
// programs that we have seen experience this problem.
StarvationMonitorInterval = 6000;
}
}
// only allow library name without path component
"Invalid parameter while calling os::win32::load_windows_dll(): cannot take path: %s", name);
return NULL;
}
// search system directory
return result;
}
}
// try Windows directory
return result;
}
}
"os::win32::load_windows_dll() cannot load %s from system directories.", name);
return NULL;
}
}
return IsDebuggerPresent() ? true : false;
}
if (PauseAtExit) {
}
}
}
return TlsAlloc();
}
}
}
return TlsGetValue(index);
}
#ifndef PRODUCT
#ifndef _WIN64
// Helpers to check whether NX protection is enabled
return EXCEPTION_EXECUTE_HANDLER;
}
return EXCEPTION_CONTINUE_SEARCH;
}
void nx_check_protection() {
// If NX is enabled we'll get an exception calling into code on the stack
__try {
}
}
#endif // _WIN64
#endif // PRODUCT
// this is called _before_ the global arguments have been parsed
_initial_pid = _getpid();
init_random(1234567);
win32::setmode_streams();
// For better scalability on MP systems (must be called after initialize_system_info)
#ifndef PRODUCT
if (is_MP()) {
NoYieldsInMicrolock = true;
}
#endif
// This may be overridden later when argument processing is done.
// Initialize main_process and main_thread
&main_thread, THREAD_ALL_ACCESS, false, 0)) {
fatal("DuplicateHandle failed\n");
}
main_thread_id = (int) GetCurrentThreadId();
}
// To install functions for atexit processing
extern "C" {
static void perfMemory_exit_helper() {
}
}
// this is called _after_ the global arguments have been parsed
// Allocate a single page and mark it as readable for safepoint polling
address return_page = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY);
#ifndef PRODUCT
if( Verbose && PrintMiscellaneous )
#endif
if (!UseMembar) {
address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE);
return_page = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE);
#ifndef PRODUCT
if(Verbose && PrintMiscellaneous)
#endif
}
os::large_page_init();
// Setup Windows Exceptions
// On Itanium systems, Structured Exception Handling does not
// work since stack frames must be walkable by the OS. Since
// much of our code is dynamically generated, and we do not have
// proper unwind .xdata sections, the system simply exits
// rather than delivering the exception. To work around
// this we use VectorExceptions instead.
#ifdef _WIN64
if (UseVectoredExceptions) {
}
#endif
// for debugging float code generation bugs
if (ForceFloatExceptions) {
#ifndef _WIN64
static long fp_control_word = 0;
// see Intel PPro Manual, Vol. 2, p 7-16
#endif
}
// If stack_commit_size is 0, windows will reserve the default size,
// but only commit a small portion of it.
if (stack_commit_size < default_reserve_size) {
// If stack_commit_size == 0, we want this too
}
// Check minimum allowable stack size for thread creation and to initialize
// the java system classes, including StackOverflowError - depends on page
// size. Add a page for compiler2 recursion in main thread.
// Add in 2*BytesPerWord times page size to account for VM stack during
// class initialization depending on 32 or 64 bit VM.
if (actual_reserve_size < min_stack_allowed) {
"Specify at least %dk",
min_stack_allowed / K);
return JNI_ERR;
}
// Calculate theoretical max. size of Threads to guard gainst artifical
// out-of-memory situations, where all available address-space has been
// reserved by thread stacks.
// Calculate the thread limit when we should start doing Virtual Memory
// banging. Currently when the threads will have used all but 200Mb of space.
//
// TODO: consider performing a similar calculation for commit size instead
// as reserve size, since on a 64-bit platform we'll run into that more
// often than running out of virtual memory space. We can use the
// lower value of the two calculations as the os_thread_limit.
// at exit methods are called in the reverse order of their registration.
// there is no limit to the number of functions registered. atexit does
// not set errno.
if (PerfAllowAtExitRegistration) {
// only register atexit functions if PerfAllowAtExitRegistration is set.
// atexit functions can be delayed until process exit time, which
// can be problematic for embedded VM situations. Embedded VMs should
// call DestroyJavaVM() to assure that VM resources are released.
// note: perfMemory_exit_helper atexit function may be removed in
// the future if the appropriate cleanup code can be added to the
// VM_Exit VMOperation's doit method.
if (atexit(perfMemory_exit_helper) != 0) {
warning("os::init_2 atexit(perfMemory_exit_helper) failed");
}
}
#ifndef _WIN64
// Print something if NX is enabled (win32 on AMD64)
#endif
// initialize thread priority policy
prio_init();
UseNUMA = false; // We don't fully support this yet
}
if (UseNUMAInterleaving) {
// first check whether this Windows OS supports VirtualAllocExNuma, if not ignore this flag
if (!success) UseNUMAInterleaving = false;
}
return JNI_OK;
}
return;
}
// Mark the polling page as unreadable
fatal("Could not disable polling page");
};
// Mark the polling page as readable
fatal("Could not enable polling page");
};
return -1;
}
// Fix for 6539723. st_mtime returned from stat() is dependent on
// the system timezone and so can return different values for the
// makes sure the same timestamp is returned regardless of the TZ.
//
// See:
// time_zone_information_str.asp
// and
//
// NOTE: there is a insidious bug here: If the timezone is changed
// after the call to stat() but before 'GetTimeZoneInformation()', then
// the adjustment we do here will be wrong and we'll return the wrong
// value (which will likely end up creating an invalid class data
// archive). Absent a better API for this, or some time zone locking
// mechanism, we'll have to live with this risk.
int daylightBias =
}
return ret;
}
// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
// are used by JVM M&M and JVMTI to get user+sys or user CPU time
// of a thread.
//
// current_thread_cpu_time() and thread_cpu_time(Thread*) returns
// the fast estimate available on the platform.
// current_thread_cpu_time() is not optimized for Windows yet
// return user + sys since the cost is the same
}
// consistent with what current_thread_cpu_time() returns.
}
}
// This code is copy from clasic VM -> hpi::sysThreadCPUTime
// If this function changes, os::is_thread_cpu_time_supported() should too
return -1;
else
if (user_sys_cpu_time) {
} else {
}
} else {
}
}
}
}
// see os::thread_cpu_time
if ( GetThreadTimes(GetCurrentThread(),
return false;
else
return true;
} else {
return false;
}
}
// Windows does't provide a loadavg primitive so this is stubbed out for now.
// It does have primitives (PDH API) to get CPU usage and run queue length.
// "\\Processor(_Total)\\% Processor Time", "\\System\\Processor Queue Length"
// If we wanted to implement loadavg on Windows, we have a few options:
//
// a) Query CPU usage and run queue length and "fake" an answer by
// returning the CPU usage if it's under 100%, and the run queue
// length otherwise. It turns out that querying is pretty slow
// on Windows, on the order of 200 microseconds on a fast machine.
// Note that on the Windows the CPU usage value is the % usage
// since the last time the API was called (and the first call
// returns 100%), so we'd have to deal with that as well.
//
// b) Sample the "fake" answer using a sampling thread and store
// the answer in a global variable. The call to loadavg would
// just return the value of the global, avoiding the slow query.
//
// c) Sample a better answer using exponential decay to smooth the
// value. This is basically the algorithm used by UNIX kernels.
//
// Note that sampling thread starvation could affect both (b) and (c).
return -1;
}
// DontYieldALot=false by default: dutifully perform all yields as requested by JVM_Yield()
return DontYieldALot;
}
// This method is a slightly reworked copy of JDK's sysOpen
// from src/windows/hpi/src/sys_api_md.c
return -1;
}
}
// Is a (classpath) directory empty?
if (f == INVALID_HANDLE_VALUE) {
return true;
}
FindClose(f);
return false;
}
// create binary file, rewriting existing file if required
if (!rewrite_existing) {
}
}
// return current position of file pointer
}
// move file pointer to the specified offset
}
}
// This method is a slightly reworked copy of JDK's sysNativePath
/* Convert a pathname to native format. On win32, this involves forcing all
separators to be '\\' rather than '/' (both are legal inputs, but Win95
sometimes rejects '/') and removing redundant separators. The input path is
assumed to have been converted into the character encoding used by the local
system. Because this might be a double-byte encoding, care is taken to
treat double-byte lead characters correctly.
This procedure modifies the given path in place, as the result is never
longer than the original. There is no error return; this operation always
succeeds. */
point to the colon following the drive
letter */
/* Assumption: '/', '\\', ':', and drive letters are never lead bytes */
&& (!::IsDBCSLeadByte('\\'))
&& (!::IsDBCSLeadByte(':'))),
"Illegal lead byte");
/* Check for leading separators */
src++;
}
/* Remove leading separators if followed by drive specifier. This
hack is necessary to support file URLs containing drive
specifiers (e.g., "file://c:/path"). As a side effect,
"/c:/path" can be used as an alternative to "c:/path". */
*dst++ = ':';
src++;
} else {
/* UNC pathname: Retain first separator; leave src pointed at
second separator so that further separators will be collapsed
into the second separator. The result will be a pathname
beginning with "\\\\" followed (most likely) by a host name. */
}
}
/* Remove redundant separators from remainder of path, forcing all
separators to be '\\' rather than '/'. Also, single byte space
characters are removed from the end of the path because those
are not legal ending characters on this operating system.
*/
while (*src != '\0') {
if (*src == '\0') {
/* Check for trailing separator */
/* "\\\\" is not collapsed to "\\" because "\\\\" marks the
beginning of a UNC pathname. Even though it is not, by
itself, a valid UNC pathname, we leave it as is in order
to be consistent with the path canonicalizer as well
as the win32 APIs, which treat this case as an invalid
UNC pathname rather than as an alias for the root
directory of the current drive. */
break;
}
remove trailing separator */
break;
}
} else {
} else { /* Copy a single-byte character */
char c = *src++;
*dst++ = c;
/* Space is not a legal ending character */
}
}
}
*end = '\0';
/* For "z:", add "." to work around a bug in the C runtime library */
}
#ifdef DEBUG
#endif DEBUG
return path;
}
// This code is a copy of JDK's sysSetLength
// from src/windows/hpi/src/sys_api_md.c
if (h == (HANDLE)(-1)) {
return -1;
}
return -1;
}
if (::SetEndOfFile(h) == FALSE) {
return -1;
}
return 0;
}
// This code is a copy of JDK's sysSync
// from src/windows/hpi/src/sys_api_md.c
// except for the legacy workaround for a bug in Win 98
if ( (!::FlushFileBuffers(handle)) &&
(GetLastError() != ERROR_ACCESS_DENIED) ) {
/* from winerror.h */
return -1;
}
return 0;
}
static int nonSeekAvailable(int, long *);
static int stdinAvailable(int, long *);
// This code is a copy of JDK's sysAvailable
// from src/windows/hpi/src/sys_api_md.c
int ret;
long lpbytes;
if (fd == 0) {
} else {
}
return ret;
}
return FALSE;
return FALSE;
return FALSE;
}
return TRUE;
} else {
return FALSE;
}
}
// This code is a copy of JDK's nonSeekAvailable
// from src/windows/hpi/src/sys_api_md.c
/* This is used for available on non-seekable devices
* (like both named and anonymous pipes, such as pipes
* connected to an exec'd process).
* Standard Input is a special case.
*
*/
return FALSE;
}
/* PeekNamedPipe fails when at EOF. In that case we
* simply make *pbytes = 0 which is consistent with the
* behavior we get on Solaris when an fd is at EOF.
* The only alternative is to raise an Exception,
* which isn't really warranted.
*/
if (::GetLastError() != ERROR_BROKEN_PIPE) {
return FALSE;
}
*pbytes = 0;
}
return TRUE;
}
// This code is a copy of JDK's stdinAvailable
// from src/windows/hpi/src/sys_api_md.c
DWORD i = 0; /* Loop index */
return FALSE;
}
/* Construct an array of input records in the console buffer */
if (error == 0) {
}
/* lpBuffer must fit into 64K or else PeekConsoleInput fails */
if (numEvents > MAX_INPUT_EVENTS) {
}
return FALSE;
}
if (error == 0) {
return FALSE;
}
/* Examine input records for the number of bytes available */
for(i=0; i<numEvents; i++) {
curLength++;
if (*keyPressed == '\r') {
}
}
}
}
}
*pbytes = (long) actualLength;
return TRUE;
}
// Map a block of memory.
bool allow_exec) {
char* base;
if (PrintMiscellaneous && Verbose) {
}
return NULL;
}
if (allow_exec) {
// CreateFileMapping/MapViewOfFileEx can't map executable memory
// unless it comes from a PE image (which the shared archive is not.)
// Even VirtualProtect refuses to give execute access to mapped memory
// that was not previously executable.
//
// Instead, stick the executable region in anonymous memory. Yuck.
// Penalty is that ~4 pages will not be shareable - in the future
// we might consider DLLizing the shared archive with a proper PE
// header so that mapping executable + sharing is possible.
if (PrintMiscellaneous && Verbose) {
}
return NULL;
}
overlapped.OffsetHigh = 0;
// ReadFile guarantees that if the return value is true, the requested
// number of bytes were read before returning.
if (!res) {
if (PrintMiscellaneous && Verbose) {
}
return NULL;
}
} else {
NULL /*file_name*/);
if (PrintMiscellaneous && Verbose) {
}
return NULL;
}
if (PrintMiscellaneous && Verbose) {
}
return NULL;
}
if (CloseHandle(hMap) == 0) {
if (PrintMiscellaneous && Verbose) {
}
return base;
}
}
if (allow_exec) {
if (!res) {
if (PrintMiscellaneous && Verbose) {
}
// Don't consider this a hard error, on IA32 even if the
// VirtualProtect fails, we should still be able to execute
return base;
}
}
if (CloseHandle(hFile) == 0) {
if (PrintMiscellaneous && Verbose) {
}
return base;
}
return base;
}
// Remap a block of memory.
bool allow_exec) {
// This OS does not allow existing memory maps to be remapped so we
// have to unmap the memory before we remap it.
return NULL;
}
// There is a very small theoretical window between the unmap_memory()
// call above and the map_memory() call below where a thread in native
// code may be able to access an address that is no longer mapped.
}
// Unmap a block of memory.
// Returns true=success, otherwise false.
if (result == 0) {
if (PrintMiscellaneous && Verbose) {
}
return false;
}
return true;
}
if (PauseAtStartupFile && PauseAtStartupFile[0]) {
} else {
}
if (fd != -1) {
Sleep(100);
}
} else {
"Could not open pause file '%s', continuing immediately.\n", filename);
}
}
// An Event wraps a win32 "CreateEvent" kernel handle.
//
// We have a number of choices regarding "CreateEvent" win32 handle leakage:
//
// 1: When a thread dies return the Event to the EventFreeList, clear the ParkHandle
// field, and call CloseHandle() on the win32 event handle. Unpark() would
// need to be modified to tolerate finding a NULL (invalid) win32 event handle.
// In addition, an unpark() operation might fetch the handle field, but the
// event could recycle between the fetch and the SetEvent() operation.
// SetEvent() would either fail because the handle was invalid, or inadvertently work,
// as the win32 handle value had been recycled. In an ideal world calling SetEvent()
// on an stale but recycled handle would be harmless, but in practice this might
// confuse other non-Sun code, so it's not a viable approach.
//
// 2: Once a win32 event handle is associated with an Event, it remains associated
// with the Event. The event handle is never closed. This could be construed
// as handle leakage, but only up to the maximum # of threads that have been extant
// at any one time. This shouldn't be an issue, as windows platforms typically
// permit a process to have hundreds of thousands of open handles.
//
// 3: Same as (1), but periodically, at stop-the-world time, rundown the EventFreeList
// and release unused handles.
//
// 4: Add a CRITICAL_SECTION to the Event to protect LD+SetEvent from LD;ST(null);CloseHandle.
// It's not clear, however, that we wouldn't be trading one type of leak for another.
//
// 5. Use an RCU-like mechanism (Read-Copy Update).
// Or perhaps something similar to Maged Michael's "Hazard pointers".
//
// We use (2).
//
// TODO-FIXME:
// 1. Reconcile Doug's JSR166 j.u.c park-unpark with the objectmonitor implementation.
// to recover from (or at least detect) the dreaded Windows 841176 bug.
// 3. Collapse the interrupt_event, the JSR166 parker event, and the objectmonitor ParkEvent
// into a single win32 CreateEvent() handle.
//
// _Event transitions in park()
// -1 => -1 : illegal
// 1 => 0 : pass - return immediately
// 0 => -1 : block
//
// _Event serves as a restricted-range semaphore :
// -1 : thread is blocked
// 0 : neutral - thread is running or ready
// 1 : signaled - thread is running or ready
//
// Another possible encoding of _Event would be
// with explicit "PARKED" and "SIGNALED" bits.
int v ;
// CONSIDER: defer assigning a CreateEvent() handle to the Event until
// the initial park() operation.
for (;;) {
v = _Event ;
}
if (v != 0) return OS_OK ;
// Do this the hard way by blocking ...
// TODO: consider a brief spin here, gated on the success of recent
// spin attempts by this thread.
//
// We decompose long timeouts into series of shorter timed waits.
// Evidently large timo values passed in WaitForSingleObject() are problematic on some
// versions of Windows. See EventWait() for details. This may be superstition. Or not.
// We trust the WAIT_TIMEOUT indication and don't track the elapsed wait time
// with os::javaTimeNanos(). Furthermore, we assume that spurious returns from
// ::WaitForSingleObject() caused by latent ::setEvent() operations will tend
// to happen early in the wait interval. Specifically, after a spurious wakeup (rv ==
// WAIT_OBJECT_0 but _Event is still < 0) we don't bother to recompute Millis to compensate
// for the already waited time. This policy does not admit any new outcomes.
// In the future, however, we might want to track the accumulated wait time and
// adjust Millis accordingly if we encounter a spurious wakeup.
if (Millis > MAXTIMEOUT) {
prd = MAXTIMEOUT ;
}
if (rv == WAIT_TIMEOUT) {
}
}
v = _Event ;
_Event = 0 ;
// see comment at end of os::PlatformEvent::park() below:
OrderAccess::fence() ;
// If we encounter a nearly simultanous timeout expiry and unpark()
// we return OS_OK indicating we awoke via unpark().
// Implementor's license -- returning OS_TIMEOUT would be equally valid, however.
return (v >= 0) ? OS_OK : OS_TIMEOUT ;
}
// Invariant: Only the thread associated with the Event/PlatformEvent
// may call park().
int v ;
for (;;) {
v = _Event ;
}
if (v != 0) return ;
// Do this the hard way by blocking ...
// TODO: consider a brief spin here, gated on the success of recent
// spin attempts by this thread.
while (_Event < 0) {
}
// Usually we'll find _Event == 0 at this point, but as
// an optional optimization we clear it, just in case can
// multiple unpark() operations drove _Event up to 1.
_Event = 0 ;
OrderAccess::fence() ;
}
// Transitions for _Event:
// 0 :=> 1
// 1 :=> 1
// -1 :=> either 0 or 1; must signal target thread
// That is, we can safely transition _Event from -1 to either
// 0 or 1. Forcing 1 is slightly more efficient for back-to-back
// unpark() calls.
// See also: "Semaphores in Plan 9" by Mullender & Cox
//
// Note: Forcing a transition from "-1" to "1" on an unpark() means
// that it will take two back-to-back park() calls for the owning
// thread to block. This has the benefit of forcing a spurious return
// from the first park() call after an unpark() call which will help
// shake out uses of park() and unpark() without condition variables.
::SetEvent(_ParkHandle);
}
// JSR166
// -------------------------------------------------------
/*
* The Windows implementation of Park is very straightforward: Basic
* operations on Win32 Events turn out to have the right semantics to
* use them directly. We opportunistically resuse the event inherited
* from Monitor.
*/
// First, demultiplex/decode time arguments
if (time < 0) { // don't wait
return;
}
else if (time == 0 && !isAbsolute) {
}
else if (isAbsolute) {
if (time <= 0) // already elapsed
return;
}
else { // relative
if (time == 0) // Wait for the minimal time unit if zero
time = 1;
}
// Don't wait if interrupted or already triggered
return;
}
else {
// If externally suspended while waiting, re-suspend
jt->java_suspend_self();
}
}
}
}
// Run the specified command in a separate process. Return its exit value,
// or -1 on failure (e.g. can't create a new process).
cmd, // command line
NULL, // process security attribute
NULL, // thread security attribute
TRUE, // inherits system handles
0, // no creation flags
NULL, // use parent's environment block
NULL, // use parent's starting directory
&si, // (in) startup information
&pi); // (out) process information
if (rslt) {
// Wait until child process exits.
// Close process and thread handles.
return (int)exit_code;
} else {
return -1;
}
}
//--------------------------------------------------------------------------------------------------
// Non-product code
static int mallocDebugIntervalCounter = 0;
static int mallocDebugCounter = 0;
// Note: HeapValidate executes two hardware breakpoints when it finds something
// wrong; at these points, eax contains the address of the offending block (I think).
// To get to the exlicit error message(s) below, just continue twice.
fatal("corrupted C heap");
}
}
}
}
}
return true;
}
// Nothing yet
return false;
}
if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) {
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
// We don't build a headless jre for Windows
static void initSock() {
::GetLastError());
return;
}
if (sock_initialized == TRUE) return;
}
}
if (!sock_initialized) {
initSock();
}
return NULL;
}
}
return ::closesocket(fd);
}
return (ret < 0) ? 0 : 1;
}
}
}
}
}
}
}
}
}
}
struct timeval t;
}
}
}
}
}
}
}
// WINDOWS CONTEXT Flags for THREAS_SAMPLING
#if defined(IA32)
# define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
#endif
// returns true if thread could be suspended,
// false otherwise
if (h != NULL) {
if (SuspendThread(*h) != ~0) {
return true;
}
}
return false;
}
// resume the thread
// calling resume on an active thread is a no-op
if (h != NULL) {
ResumeThread(*h);
}
}
// from the tid. Caller validates handle return value.
if (h != NULL) {
}
}
//
// Thread sampling implementation
//
// get context capable handle for thread
// sanity
if (h == NULL || h == INVALID_HANDLE_VALUE) {
return;
}
// suspend the thread
if (do_suspend(&h)) {
// get thread context
GetThreadContext(h, &ctxt);
// pass context to Thread Sampling impl
// resume thread
do_resume(&h);
}
// close handle
CloseHandle(h);
}
// Kernel32 API
"GetLargePageMinimumAvailable() not yet called");
return _GetLargePageMinimum();
}
if (!initialized) {
initialize();
}
return _GetLargePageMinimum != NULL;
}
if (!initialized) {
initialize();
}
return _VirtualAllocExNuma != NULL;
}
LPVOID os::Kernel32Dll::VirtualAllocExNuma(HANDLE hProc, LPVOID addr, SIZE_T bytes, DWORD flags, DWORD prot, DWORD node) {
"NUMACallsAvailable() not yet called");
}
"NUMACallsAvailable() not yet called");
}
"NUMACallsAvailable() not yet called");
}
if (!initialized) {
initialize();
}
if (_RtlCaptureStackBackTrace != NULL) {
} else {
return 0;
}
}
if (!initialized) {
_GetNumaHighestNodeNumber = (GetNumaHighestNodeNumber_Fn)::GetProcAddress(handle, "GetNumaHighestNodeNumber");
_GetNumaNodeProcessorMask = (GetNumaNodeProcessorMask_Fn)::GetProcAddress(handle, "GetNumaNodeProcessorMask");
_RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_Fn)::GetProcAddress(handle, "RtlCaptureStackBackTrace");
initialized = TRUE;
}
}
#ifndef JDK6_OR_EARLIER
}
// Kernel32 API
return ::SwitchToThread();
}
return true;
}
// Help tools
return true;
}
}
}
}
return true;
}
}
// PSAPI API
inline BOOL os::PSApiDll::EnumProcessModules(HANDLE hProcess, HMODULE *lpModule, DWORD cb, LPDWORD lpcbNeeded) {
}
inline DWORD os::PSApiDll::GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize) {
}
inline BOOL os::PSApiDll::GetModuleInformation(HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb) {
}
return true;
}
// WinSock2 API
}
return ::gethostbyname(name);
}
return true;
}
// Advapi API
}
}
inline BOOL os::Advapi32Dll::LookupPrivilegeValue(LPCTSTR lpSystemName, LPCTSTR lpName, PLUID lpLuid) {
}
return true;
}
#else
// Kernel32 API
if (!initialized) {
initializeCommon(); // resolve the functions that always need resolving
initialized = TRUE;
}
}
"SwitchToThreadAvailable() not yet called");
return _SwitchToThread();
}
if (!initialized) {
initialize();
}
return _SwitchToThread != NULL;
}
// Help tools
if (!initialized) {
initialize();
}
return _CreateToolhelp32Snapshot != NULL &&
_Module32First != NULL &&
_Module32Next != NULL;
}
"HelpToolsAvailable() not yet called");
}
"HelpToolsAvailable() not yet called");
}
"HelpToolsAvailable() not yet called");
}
if (!initialized) {
initialize();
}
return _GetNativeSystemInfo != NULL;
}
"GetNativeSystemInfoAvailable() not yet called");
}
// PSAPI API
if (!initialized) {
"EnumProcessModules");
"GetModuleFileNameExA");
"GetModuleInformation");
}
initialized = TRUE;
}
}
BOOL os::PSApiDll::EnumProcessModules(HANDLE hProcess, HMODULE *lpModule, DWORD cb, LPDWORD lpcbNeeded) {
"PSApiAvailable() not yet called");
}
DWORD os::PSApiDll::GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize) {
"PSApiAvailable() not yet called");
}
BOOL os::PSApiDll::GetModuleInformation(HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb) {
"PSApiAvailable() not yet called");
}
if (!initialized) {
initialize();
}
return _EnumProcessModules != NULL &&
_GetModuleFileNameEx != NULL &&
}
// WinSock2 API
if (!initialized) {
}
initialized = TRUE;
}
}
"WinSock2Available() not yet called");
}
"WinSock2Available() not yet called");
return _gethostbyname(name);
}
if (!initialized) {
initialize();
}
return _WSAStartup != NULL &&
_gethostbyname != NULL;
}
typedef BOOL (WINAPI *AdjustTokenPrivileges_Fn)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
if (!initialized) {
"AdjustTokenPrivileges");
"OpenProcessToken");
"LookupPrivilegeValueA");
}
initialized = TRUE;
}
}
"AdvapiAvailable() not yet called");
}
"AdvapiAvailable() not yet called");
}
"AdvapiAvailable() not yet called");
}
if (!initialized) {
initialize();
}
return _AdjustTokenPrivileges != NULL &&
_OpenProcessToken != NULL &&
}
#endif