annotate src/os/windows/vm/os_windows.cpp @ 1999:2c8e1acf0433

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