src/os/windows/vm/os_windows.cpp

Tue, 08 Aug 2017 15:57:29 +0800

author
aoqi
date
Tue, 08 Aug 2017 15:57:29 +0800
changeset 6876
710a3c8b516e
parent 6779
364b73402247
parent 0
f90c822e73f8
child 7535
7ae4e26cb1e0
permissions
-rw-r--r--

merge

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

mercurial