PageRenderTime 148ms CodeModel.GetById 21ms RepoModel.GetById 2ms app.codeStats 3ms

/hotspot/src/os/windows/vm/os_windows.cpp

https://bitbucket.org/nkabir/jdk-6
C++ | 4760 lines | 3219 code | 644 blank | 897 comment | 805 complexity | bd0a29115bdf310e6738b41a729e50c5 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * CopyrighT (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation.
  8. *
  9. * This code is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * version 2 for more details (a copy is included in the LICENSE file that
  13. * accompanied this code).
  14. *
  15. * You should have received a copy of the GNU General Public License version
  16. * 2 along with this work; if not, write to the Free Software Foundation,
  17. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18. *
  19. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20. * or visit www.oracle.com if you need additional information or have any
  21. * questions.
  22. *
  23. */
  24. #ifdef _WIN64
  25. // Must be at least Windows 2000 or XP to use VectoredExceptions
  26. #define _WIN32_WINNT 0x500
  27. #endif
  28. // no precompiled headers
  29. #include "classfile/classLoader.hpp"
  30. #include "classfile/systemDictionary.hpp"
  31. #include "classfile/vmSymbols.hpp"
  32. #include "code/icBuffer.hpp"
  33. #include "code/vtableStubs.hpp"
  34. #include "compiler/compileBroker.hpp"
  35. #include "interpreter/interpreter.hpp"
  36. #include "jvm_windows.h"
  37. #include "memory/allocation.inline.hpp"
  38. #include "memory/filemap.hpp"
  39. #include "mutex_windows.inline.hpp"
  40. #include "oops/oop.inline.hpp"
  41. #include "os_share_windows.hpp"
  42. #include "prims/jniFastGetField.hpp"
  43. #include "prims/jvm.h"
  44. #include "prims/jvm_misc.hpp"
  45. #include "runtime/arguments.hpp"
  46. #include "runtime/extendedPC.hpp"
  47. #include "runtime/globals.hpp"
  48. #include "runtime/interfaceSupport.hpp"
  49. #include "runtime/java.hpp"
  50. #include "runtime/javaCalls.hpp"
  51. #include "runtime/mutexLocker.hpp"
  52. #include "runtime/objectMonitor.hpp"
  53. #include "runtime/osThread.hpp"
  54. #include "runtime/perfMemory.hpp"
  55. #include "runtime/sharedRuntime.hpp"
  56. #include "runtime/statSampler.hpp"
  57. #include "runtime/stubRoutines.hpp"
  58. #include "runtime/threadCritical.hpp"
  59. #include "runtime/timer.hpp"
  60. #include "services/attachListener.hpp"
  61. #include "services/runtimeService.hpp"
  62. #include "thread_windows.inline.hpp"
  63. #include "utilities/decoder.hpp"
  64. #include "utilities/defaultStream.hpp"
  65. #include "utilities/events.hpp"
  66. #include "utilities/growableArray.hpp"
  67. #include "utilities/vmError.hpp"
  68. #ifdef TARGET_ARCH_x86
  69. # include "assembler_x86.inline.hpp"
  70. # include "nativeInst_x86.hpp"
  71. #endif
  72. #ifdef COMPILER1
  73. #include "c1/c1_Runtime1.hpp"
  74. #endif
  75. #ifdef COMPILER2
  76. #include "opto/runtime.hpp"
  77. #endif
  78. #ifdef _DEBUG
  79. #include <crtdbg.h>
  80. #endif
  81. #include <windows.h>
  82. #include <sys/types.h>
  83. #include <sys/stat.h>
  84. #include <sys/timeb.h>
  85. #include <objidl.h>
  86. #include <shlobj.h>
  87. #include <malloc.h>
  88. #include <signal.h>
  89. #include <direct.h>
  90. #include <errno.h>
  91. #include <fcntl.h>
  92. #include <io.h>
  93. #include <process.h> // For _beginthreadex(), _endthreadex()
  94. #include <imagehlp.h> // For os::dll_address_to_function_name
  95. /* for enumerating dll libraries */
  96. #include <tlhelp32.h>
  97. #include <vdmdbg.h>
  98. // for timer info max values which include all bits
  99. #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
  100. // For DLL loading/load error detection
  101. // Values of PE COFF
  102. #define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c
  103. #define IMAGE_FILE_SIGNATURE_LENGTH 4
  104. static HANDLE main_process;
  105. static HANDLE main_thread;
  106. static int main_thread_id;
  107. static FILETIME process_creation_time;
  108. static FILETIME process_exit_time;
  109. static FILETIME process_user_time;
  110. static FILETIME process_kernel_time;
  111. #ifdef _WIN64
  112. PVOID topLevelVectoredExceptionHandler = NULL;
  113. #endif
  114. #ifdef _M_IA64
  115. #define __CPU__ ia64
  116. #elif _M_AMD64
  117. #define __CPU__ amd64
  118. #else
  119. #define __CPU__ i486
  120. #endif
  121. // save DLL module handle, used by GetModuleFileName
  122. HINSTANCE vm_lib_handle;
  123. static int getLastErrorString(char *buf, size_t len);
  124. BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
  125. switch (reason) {
  126. case DLL_PROCESS_ATTACH:
  127. vm_lib_handle = hinst;
  128. if(ForceTimeHighResolution)
  129. timeBeginPeriod(1L);
  130. break;
  131. case DLL_PROCESS_DETACH:
  132. if(ForceTimeHighResolution)
  133. timeEndPeriod(1L);
  134. #ifdef _WIN64
  135. if (topLevelVectoredExceptionHandler != NULL) {
  136. RemoveVectoredExceptionHandler(topLevelVectoredExceptionHandler);
  137. topLevelVectoredExceptionHandler = NULL;
  138. }
  139. #endif
  140. break;
  141. default:
  142. break;
  143. }
  144. return true;
  145. }
  146. static inline double fileTimeAsDouble(FILETIME* time) {
  147. const double high = (double) ((unsigned int) ~0);
  148. const double split = 10000000.0;
  149. double result = (time->dwLowDateTime / split) +
  150. time->dwHighDateTime * (high/split);
  151. return result;
  152. }
  153. // Implementation of os
  154. bool os::getenv(const char* name, char* buffer, int len) {
  155. int result = GetEnvironmentVariable(name, buffer, len);
  156. return result > 0 && result < len;
  157. }
  158. // No setuid programs under Windows.
  159. bool os::have_special_privileges() {
  160. return false;
  161. }
  162. // This method is a periodic task to check for misbehaving JNI applications
  163. // under CheckJNI, we can add any periodic checks here.
  164. // For Windows at the moment does nothing
  165. void os::run_periodic_checks() {
  166. return;
  167. }
  168. #ifndef _WIN64
  169. // previous UnhandledExceptionFilter, if there is one
  170. static LPTOP_LEVEL_EXCEPTION_FILTER prev_uef_handler = NULL;
  171. LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo);
  172. #endif
  173. void os::init_system_properties_values() {
  174. /* sysclasspath, java_home, dll_dir */
  175. {
  176. char *home_path;
  177. char *dll_path;
  178. char *pslash;
  179. char *bin = "\\bin";
  180. char home_dir[MAX_PATH];
  181. if (!getenv("_ALT_JAVA_HOME_DIR", home_dir, MAX_PATH)) {
  182. os::jvm_path(home_dir, sizeof(home_dir));
  183. // Found the full path to jvm[_g].dll.
  184. // Now cut the path to <java_home>/jre if we can.
  185. *(strrchr(home_dir, '\\')) = '\0'; /* get rid of \jvm.dll */
  186. pslash = strrchr(home_dir, '\\');
  187. if (pslash != NULL) {
  188. *pslash = '\0'; /* get rid of \{client|server} */
  189. pslash = strrchr(home_dir, '\\');
  190. if (pslash != NULL)
  191. *pslash = '\0'; /* get rid of \bin */
  192. }
  193. }
  194. home_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + 1);
  195. if (home_path == NULL)
  196. return;
  197. strcpy(home_path, home_dir);
  198. Arguments::set_java_home(home_path);
  199. dll_path = NEW_C_HEAP_ARRAY(char, strlen(home_dir) + strlen(bin) + 1);
  200. if (dll_path == NULL)
  201. return;
  202. strcpy(dll_path, home_dir);
  203. strcat(dll_path, bin);
  204. Arguments::set_dll_dir(dll_path);
  205. if (!set_boot_path('\\', ';'))
  206. return;
  207. }
  208. /* library_path */
  209. #define EXT_DIR "\\lib\\ext"
  210. #define BIN_DIR "\\bin"
  211. #define PACKAGE_DIR "\\Sun\\Java"
  212. {
  213. /* Win32 library search order (See the documentation for LoadLibrary):
  214. *
  215. * 1. The directory from which application is loaded.
  216. * 2. The current directory
  217. * 3. The system wide Java Extensions directory (Java only)
  218. * 4. System directory (GetSystemDirectory)
  219. * 5. Windows directory (GetWindowsDirectory)
  220. * 6. The PATH environment variable
  221. */
  222. char *library_path;
  223. char tmp[MAX_PATH];
  224. char *path_str = ::getenv("PATH");
  225. library_path = NEW_C_HEAP_ARRAY(char, MAX_PATH * 5 + sizeof(PACKAGE_DIR) +
  226. sizeof(BIN_DIR) + (path_str ? strlen(path_str) : 0) + 10);
  227. library_path[0] = '\0';
  228. GetModuleFileName(NULL, tmp, sizeof(tmp));
  229. *(strrchr(tmp, '\\')) = '\0';
  230. strcat(library_path, tmp);
  231. strcat(library_path, ";.");
  232. GetWindowsDirectory(tmp, sizeof(tmp));
  233. strcat(library_path, ";");
  234. strcat(library_path, tmp);
  235. strcat(library_path, PACKAGE_DIR BIN_DIR);
  236. GetSystemDirectory(tmp, sizeof(tmp));
  237. strcat(library_path, ";");
  238. strcat(library_path, tmp);
  239. GetWindowsDirectory(tmp, sizeof(tmp));
  240. strcat(library_path, ";");
  241. strcat(library_path, tmp);
  242. if (path_str) {
  243. strcat(library_path, ";");
  244. strcat(library_path, path_str);
  245. }
  246. Arguments::set_library_path(library_path);
  247. FREE_C_HEAP_ARRAY(char, library_path);
  248. }
  249. /* Default extensions directory */
  250. {
  251. char path[MAX_PATH];
  252. char buf[2 * MAX_PATH + 2 * sizeof(EXT_DIR) + sizeof(PACKAGE_DIR) + 1];
  253. GetWindowsDirectory(path, MAX_PATH);
  254. sprintf(buf, "%s%s;%s%s%s", Arguments::get_java_home(), EXT_DIR,
  255. path, PACKAGE_DIR, EXT_DIR);
  256. Arguments::set_ext_dirs(buf);
  257. }
  258. #undef EXT_DIR
  259. #undef BIN_DIR
  260. #undef PACKAGE_DIR
  261. /* Default endorsed standards directory. */
  262. {
  263. #define ENDORSED_DIR "\\lib\\endorsed"
  264. size_t len = strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR);
  265. char * buf = NEW_C_HEAP_ARRAY(char, len);
  266. sprintf(buf, "%s%s", Arguments::get_java_home(), ENDORSED_DIR);
  267. Arguments::set_endorsed_dirs(buf);
  268. #undef ENDORSED_DIR
  269. }
  270. #ifndef _WIN64
  271. // set our UnhandledExceptionFilter and save any previous one
  272. prev_uef_handler = SetUnhandledExceptionFilter(Handle_FLT_Exception);
  273. #endif
  274. // Done
  275. return;
  276. }
  277. void os::breakpoint() {
  278. DebugBreak();
  279. }
  280. // Invoked from the BREAKPOINT Macro
  281. extern "C" void breakpoint() {
  282. os::breakpoint();
  283. }
  284. // Returns an estimate of the current stack pointer. Result must be guaranteed
  285. // to point into the calling threads stack, and be no lower than the current
  286. // stack pointer.
  287. address os::current_stack_pointer() {
  288. int dummy;
  289. address sp = (address)&dummy;
  290. return sp;
  291. }
  292. // os::current_stack_base()
  293. //
  294. // Returns the base of the stack, which is the stack's
  295. // starting address. This function must be called
  296. // while running on the stack of the thread being queried.
  297. address os::current_stack_base() {
  298. MEMORY_BASIC_INFORMATION minfo;
  299. address stack_bottom;
  300. size_t stack_size;
  301. VirtualQuery(&minfo, &minfo, sizeof(minfo));
  302. stack_bottom = (address)minfo.AllocationBase;
  303. stack_size = minfo.RegionSize;
  304. // Add up the sizes of all the regions with the same
  305. // AllocationBase.
  306. while( 1 )
  307. {
  308. VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo));
  309. if ( stack_bottom == (address)minfo.AllocationBase )
  310. stack_size += minfo.RegionSize;
  311. else
  312. break;
  313. }
  314. #ifdef _M_IA64
  315. // IA64 has memory and register stacks
  316. stack_size = stack_size / 2;
  317. #endif
  318. return stack_bottom + stack_size;
  319. }
  320. size_t os::current_stack_size() {
  321. size_t sz;
  322. MEMORY_BASIC_INFORMATION minfo;
  323. VirtualQuery(&minfo, &minfo, sizeof(minfo));
  324. sz = (size_t)os::current_stack_base() - (size_t)minfo.AllocationBase;
  325. return sz;
  326. }
  327. struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
  328. const struct tm* time_struct_ptr = localtime(clock);
  329. if (time_struct_ptr != NULL) {
  330. *res = *time_struct_ptr;
  331. return res;
  332. }
  333. return NULL;
  334. }
  335. LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo);
  336. // Thread start routine for all new Java threads
  337. static unsigned __stdcall java_start(Thread* thread) {
  338. // Try to randomize the cache line index of hot stack frames.
  339. // This helps when threads of the same stack traces evict each other's
  340. // cache lines. The threads can be either from the same JVM instance, or
  341. // from different JVM instances. The benefit is especially true for
  342. // processors with hyperthreading technology.
  343. static int counter = 0;
  344. int pid = os::current_process_id();
  345. _alloca(((pid ^ counter++) & 7) * 128);
  346. OSThread* osthr = thread->osthread();
  347. assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
  348. if (UseNUMA) {
  349. int lgrp_id = os::numa_get_group_id();
  350. if (lgrp_id != -1) {
  351. thread->set_lgrp_id(lgrp_id);
  352. }
  353. }
  354. if (UseVectoredExceptions) {
  355. // If we are using vectored exception we don't need to set a SEH
  356. thread->run();
  357. }
  358. else {
  359. // Install a win32 structured exception handler around every thread created
  360. // by VM, so VM can genrate error dump when an exception occurred in non-
  361. // Java thread (e.g. VM thread).
  362. __try {
  363. thread->run();
  364. } __except(topLevelExceptionFilter(
  365. (_EXCEPTION_POINTERS*)_exception_info())) {
  366. // Nothing to do.
  367. }
  368. }
  369. // One less thread is executing
  370. // When the VMThread gets here, the main thread may have already exited
  371. // which frees the CodeHeap containing the Atomic::add code
  372. if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
  373. Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count);
  374. }
  375. return 0;
  376. }
  377. static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle, int thread_id) {
  378. // Allocate the OSThread object
  379. OSThread* osthread = new OSThread(NULL, NULL);
  380. if (osthread == NULL) return NULL;
  381. // Initialize support for Java interrupts
  382. HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
  383. if (interrupt_event == NULL) {
  384. delete osthread;
  385. return NULL;
  386. }
  387. osthread->set_interrupt_event(interrupt_event);
  388. // Store info on the Win32 thread into the OSThread
  389. osthread->set_thread_handle(thread_handle);
  390. osthread->set_thread_id(thread_id);
  391. if (UseNUMA) {
  392. int lgrp_id = os::numa_get_group_id();
  393. if (lgrp_id != -1) {
  394. thread->set_lgrp_id(lgrp_id);
  395. }
  396. }
  397. // Initial thread state is INITIALIZED, not SUSPENDED
  398. osthread->set_state(INITIALIZED);
  399. return osthread;
  400. }
  401. bool os::create_attached_thread(JavaThread* thread) {
  402. #ifdef ASSERT
  403. thread->verify_not_published();
  404. #endif
  405. HANDLE thread_h;
  406. if (!DuplicateHandle(main_process, GetCurrentThread(), GetCurrentProcess(),
  407. &thread_h, THREAD_ALL_ACCESS, false, 0)) {
  408. fatal("DuplicateHandle failed\n");
  409. }
  410. OSThread* osthread = create_os_thread(thread, thread_h,
  411. (int)current_thread_id());
  412. if (osthread == NULL) {
  413. return false;
  414. }
  415. // Initial thread state is RUNNABLE
  416. osthread->set_state(RUNNABLE);
  417. thread->set_osthread(osthread);
  418. return true;
  419. }
  420. bool os::create_main_thread(JavaThread* thread) {
  421. #ifdef ASSERT
  422. thread->verify_not_published();
  423. #endif
  424. if (_starting_thread == NULL) {
  425. _starting_thread = create_os_thread(thread, main_thread, main_thread_id);
  426. if (_starting_thread == NULL) {
  427. return false;
  428. }
  429. }
  430. // The primordial thread is runnable from the start)
  431. _starting_thread->set_state(RUNNABLE);
  432. thread->set_osthread(_starting_thread);
  433. return true;
  434. }
  435. // Allocate and initialize a new OSThread
  436. bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
  437. unsigned thread_id;
  438. // Allocate the OSThread object
  439. OSThread* osthread = new OSThread(NULL, NULL);
  440. if (osthread == NULL) {
  441. return false;
  442. }
  443. // Initialize support for Java interrupts
  444. HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
  445. if (interrupt_event == NULL) {
  446. delete osthread;
  447. return NULL;
  448. }
  449. osthread->set_interrupt_event(interrupt_event);
  450. osthread->set_interrupted(false);
  451. thread->set_osthread(osthread);
  452. if (stack_size == 0) {
  453. switch (thr_type) {
  454. case os::java_thread:
  455. // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
  456. if (JavaThread::stack_size_at_create() > 0)
  457. stack_size = JavaThread::stack_size_at_create();
  458. break;
  459. case os::compiler_thread:
  460. if (CompilerThreadStackSize > 0) {
  461. stack_size = (size_t)(CompilerThreadStackSize * K);
  462. break;
  463. } // else fall through:
  464. // use VMThreadStackSize if CompilerThreadStackSize is not defined
  465. case os::vm_thread:
  466. case os::pgc_thread:
  467. case os::cgc_thread:
  468. case os::watcher_thread:
  469. if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
  470. break;
  471. }
  472. }
  473. // Create the Win32 thread
  474. //
  475. // Contrary to what MSDN document says, "stack_size" in _beginthreadex()
  476. // does not specify stack size. Instead, it specifies the size of
  477. // initially committed space. The stack size is determined by
  478. // PE header in the executable. If the committed "stack_size" is larger
  479. // than default value in the PE header, the stack is rounded up to the
  480. // nearest multiple of 1MB. For example if the launcher has default
  481. // stack size of 320k, specifying any size less than 320k does not
  482. // affect the actual stack size at all, it only affects the initial
  483. // commitment. On the other hand, specifying 'stack_size' larger than
  484. // default value may cause significant increase in memory usage, because
  485. // not only the stack space will be rounded up to MB, but also the
  486. // entire space is committed upfront.
  487. //
  488. // Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION'
  489. // for CreateThread() that can treat 'stack_size' as stack size. However we
  490. // are not supposed to call CreateThread() directly according to MSDN
  491. // document because JVM uses C runtime library. The good news is that the
  492. // flag appears to work with _beginthredex() as well.
  493. #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
  494. #define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000)
  495. #endif
  496. HANDLE thread_handle =
  497. (HANDLE)_beginthreadex(NULL,
  498. (unsigned)stack_size,
  499. (unsigned (__stdcall *)(void*)) java_start,
  500. thread,
  501. CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
  502. &thread_id);
  503. if (thread_handle == NULL) {
  504. // perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again
  505. // without the flag.
  506. thread_handle =
  507. (HANDLE)_beginthreadex(NULL,
  508. (unsigned)stack_size,
  509. (unsigned (__stdcall *)(void*)) java_start,
  510. thread,
  511. CREATE_SUSPENDED,
  512. &thread_id);
  513. }
  514. if (thread_handle == NULL) {
  515. // Need to clean up stuff we've allocated so far
  516. CloseHandle(osthread->interrupt_event());
  517. thread->set_osthread(NULL);
  518. delete osthread;
  519. return NULL;
  520. }
  521. Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count);
  522. // Store info on the Win32 thread into the OSThread
  523. osthread->set_thread_handle(thread_handle);
  524. osthread->set_thread_id(thread_id);
  525. // Initial thread state is INITIALIZED, not SUSPENDED
  526. osthread->set_state(INITIALIZED);
  527. // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
  528. return true;
  529. }
  530. // Free Win32 resources related to the OSThread
  531. void os::free_thread(OSThread* osthread) {
  532. assert(osthread != NULL, "osthread not set");
  533. CloseHandle(osthread->thread_handle());
  534. CloseHandle(osthread->interrupt_event());
  535. delete osthread;
  536. }
  537. static int has_performance_count = 0;
  538. static jlong first_filetime;
  539. static jlong initial_performance_count;
  540. static jlong performance_frequency;
  541. jlong as_long(LARGE_INTEGER x) {
  542. jlong result = 0; // initialization to avoid warning
  543. set_high(&result, x.HighPart);
  544. set_low(&result, x.LowPart);
  545. return result;
  546. }
  547. jlong os::elapsed_counter() {
  548. LARGE_INTEGER count;
  549. if (has_performance_count) {
  550. QueryPerformanceCounter(&count);
  551. return as_long(count) - initial_performance_count;
  552. } else {
  553. FILETIME wt;
  554. GetSystemTimeAsFileTime(&wt);
  555. return (jlong_from(wt.dwHighDateTime, wt.dwLowDateTime) - first_filetime);
  556. }
  557. }
  558. jlong os::elapsed_frequency() {
  559. if (has_performance_count) {
  560. return performance_frequency;
  561. } else {
  562. // the FILETIME time is the number of 100-nanosecond intervals since January 1,1601.
  563. return 10000000;
  564. }
  565. }
  566. julong os::available_memory() {
  567. return win32::available_memory();
  568. }
  569. julong os::win32::available_memory() {
  570. // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
  571. // value if total memory is larger than 4GB
  572. MEMORYSTATUSEX ms;
  573. ms.dwLength = sizeof(ms);
  574. GlobalMemoryStatusEx(&ms);
  575. return (julong)ms.ullAvailPhys;
  576. }
  577. julong os::physical_memory() {
  578. return win32::physical_memory();
  579. }
  580. julong os::allocatable_physical_memory(julong size) {
  581. #ifdef _LP64
  582. return size;
  583. #else
  584. // Limit to 1400m because of the 2gb address space wall
  585. return MIN2(size, (julong)1400*M);
  586. #endif
  587. }
  588. // VC6 lacks DWORD_PTR
  589. #if _MSC_VER < 1300
  590. typedef UINT_PTR DWORD_PTR;
  591. #endif
  592. int os::active_processor_count() {
  593. DWORD_PTR lpProcessAffinityMask = 0;
  594. DWORD_PTR lpSystemAffinityMask = 0;
  595. int proc_count = processor_count();
  596. if (proc_count <= sizeof(UINT_PTR) * BitsPerByte &&
  597. GetProcessAffinityMask(GetCurrentProcess(), &lpProcessAffinityMask, &lpSystemAffinityMask)) {
  598. // Nof active processors is number of bits in process affinity mask
  599. int bitcount = 0;
  600. while (lpProcessAffinityMask != 0) {
  601. lpProcessAffinityMask = lpProcessAffinityMask & (lpProcessAffinityMask-1);
  602. bitcount++;
  603. }
  604. return bitcount;
  605. } else {
  606. return proc_count;
  607. }
  608. }
  609. bool os::distribute_processes(uint length, uint* distribution) {
  610. // Not yet implemented.
  611. return false;
  612. }
  613. bool os::bind_to_processor(uint processor_id) {
  614. // Not yet implemented.
  615. return false;
  616. }
  617. static void initialize_performance_counter() {
  618. LARGE_INTEGER count;
  619. if (QueryPerformanceFrequency(&count)) {
  620. has_performance_count = 1;
  621. performance_frequency = as_long(count);
  622. QueryPerformanceCounter(&count);
  623. initial_performance_count = as_long(count);
  624. } else {
  625. has_performance_count = 0;
  626. FILETIME wt;
  627. GetSystemTimeAsFileTime(&wt);
  628. first_filetime = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
  629. }
  630. }
  631. double os::elapsedTime() {
  632. return (double) elapsed_counter() / (double) elapsed_frequency();
  633. }
  634. // Windows format:
  635. // The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
  636. // Java format:
  637. // Java standards require the number of milliseconds since 1/1/1970
  638. // Constant offset - calculated using offset()
  639. static jlong _offset = 116444736000000000;
  640. // Fake time counter for reproducible results when debugging
  641. static jlong fake_time = 0;
  642. #ifdef ASSERT
  643. // Just to be safe, recalculate the offset in debug mode
  644. static jlong _calculated_offset = 0;
  645. static int _has_calculated_offset = 0;
  646. jlong offset() {
  647. if (_has_calculated_offset) return _calculated_offset;
  648. SYSTEMTIME java_origin;
  649. java_origin.wYear = 1970;
  650. java_origin.wMonth = 1;
  651. java_origin.wDayOfWeek = 0; // ignored
  652. java_origin.wDay = 1;
  653. java_origin.wHour = 0;
  654. java_origin.wMinute = 0;
  655. java_origin.wSecond = 0;
  656. java_origin.wMilliseconds = 0;
  657. FILETIME jot;
  658. if (!SystemTimeToFileTime(&java_origin, &jot)) {
  659. fatal(err_msg("Error = %d\nWindows error", GetLastError()));
  660. }
  661. _calculated_offset = jlong_from(jot.dwHighDateTime, jot.dwLowDateTime);
  662. _has_calculated_offset = 1;
  663. assert(_calculated_offset == _offset, "Calculated and constant time offsets must be equal");
  664. return _calculated_offset;
  665. }
  666. #else
  667. jlong offset() {
  668. return _offset;
  669. }
  670. #endif
  671. jlong windows_to_java_time(FILETIME wt) {
  672. jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime);
  673. return (a - offset()) / 10000;
  674. }
  675. FILETIME java_to_windows_time(jlong l) {
  676. jlong a = (l * 10000) + offset();
  677. FILETIME result;
  678. result.dwHighDateTime = high(a);
  679. result.dwLowDateTime = low(a);
  680. return result;
  681. }
  682. // For now, we say that Windows does not support vtime. I have no idea
  683. // whether it can actually be made to (DLD, 9/13/05).
  684. bool os::supports_vtime() { return false; }
  685. bool os::enable_vtime() { return false; }
  686. bool os::vtime_enabled() { return false; }
  687. double os::elapsedVTime() {
  688. // better than nothing, but not much
  689. return elapsedTime();
  690. }
  691. jlong os::javaTimeMillis() {
  692. if (UseFakeTimers) {
  693. return fake_time++;
  694. } else {
  695. FILETIME wt;
  696. GetSystemTimeAsFileTime(&wt);
  697. return windows_to_java_time(wt);
  698. }
  699. }
  700. #define NANOS_PER_SEC CONST64(1000000000)
  701. #define NANOS_PER_MILLISEC 1000000
  702. jlong os::javaTimeNanos() {
  703. if (!has_performance_count) {
  704. return javaTimeMillis() * NANOS_PER_MILLISEC; // the best we can do.
  705. } else {
  706. LARGE_INTEGER current_count;
  707. QueryPerformanceCounter(&current_count);
  708. double current = as_long(current_count);
  709. double freq = performance_frequency;
  710. jlong time = (jlong)((current/freq) * NANOS_PER_SEC);
  711. return time;
  712. }
  713. }
  714. void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
  715. if (!has_performance_count) {
  716. // javaTimeMillis() doesn't have much percision,
  717. // but it is not going to wrap -- so all 64 bits
  718. info_ptr->max_value = ALL_64_BITS;
  719. // this is a wall clock timer, so may skip
  720. info_ptr->may_skip_backward = true;
  721. info_ptr->may_skip_forward = true;
  722. } else {
  723. jlong freq = performance_frequency;
  724. if (freq < NANOS_PER_SEC) {
  725. // the performance counter is 64 bits and we will
  726. // be multiplying it -- so no wrap in 64 bits
  727. info_ptr->max_value = ALL_64_BITS;
  728. } else if (freq > NANOS_PER_SEC) {
  729. // use the max value the counter can reach to
  730. // determine the max value which could be returned
  731. julong max_counter = (julong)ALL_64_BITS;
  732. info_ptr->max_value = (jlong)(max_counter / (freq / NANOS_PER_SEC));
  733. } else {
  734. // the performance counter is 64 bits and we will
  735. // be using it directly -- so no wrap in 64 bits
  736. info_ptr->max_value = ALL_64_BITS;
  737. }
  738. // using a counter, so no skipping
  739. info_ptr->may_skip_backward = false;
  740. info_ptr->may_skip_forward = false;
  741. }
  742. info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
  743. }
  744. char* os::local_time_string(char *buf, size_t buflen) {
  745. SYSTEMTIME st;
  746. GetLocalTime(&st);
  747. jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  748. st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
  749. return buf;
  750. }
  751. bool os::getTimesSecs(double* process_real_time,
  752. double* process_user_time,
  753. double* process_system_time) {
  754. HANDLE h_process = GetCurrentProcess();
  755. FILETIME create_time, exit_time, kernel_time, user_time;
  756. BOOL result = GetProcessTimes(h_process,
  757. &create_time,
  758. &exit_time,
  759. &kernel_time,
  760. &user_time);
  761. if (result != 0) {
  762. FILETIME wt;
  763. GetSystemTimeAsFileTime(&wt);
  764. jlong rtc_millis = windows_to_java_time(wt);
  765. jlong user_millis = windows_to_java_time(user_time);
  766. jlong system_millis = windows_to_java_time(kernel_time);
  767. *process_real_time = ((double) rtc_millis) / ((double) MILLIUNITS);
  768. *process_user_time = ((double) user_millis) / ((double) MILLIUNITS);
  769. *process_system_time = ((double) system_millis) / ((double) MILLIUNITS);
  770. return true;
  771. } else {
  772. return false;
  773. }
  774. }
  775. void os::shutdown() {
  776. // allow PerfMemory to attempt cleanup of any persistent resources
  777. perfMemory_exit();
  778. // flush buffered output, finish log files
  779. ostream_abort();
  780. // Check for abort hook
  781. abort_hook_t abort_hook = Arguments::abort_hook();
  782. if (abort_hook != NULL) {
  783. abort_hook();
  784. }
  785. }
  786. void os::abort(bool dump_core)
  787. {
  788. os::shutdown();
  789. // no core dump on Windows
  790. ::exit(1);
  791. }
  792. // Die immediately, no exit hook, no abort hook, no cleanup.
  793. void os::die() {
  794. _exit(-1);
  795. }
  796. // Directory routines copied from src/win32/native/java/io/dirent_md.c
  797. // * dirent_md.c 1.15 00/02/02
  798. //
  799. // The declarations for DIR and struct dirent are in jvm_win32.h.
  800. /* Caller must have already run dirname through JVM_NativePath, which removes
  801. duplicate slashes and converts all instances of '/' into '\\'. */
  802. DIR *
  803. os::opendir(const char *dirname)
  804. {
  805. assert(dirname != NULL, "just checking"); // hotspot change
  806. DIR *dirp = (DIR *)malloc(sizeof(DIR));
  807. DWORD fattr; // hotspot change
  808. char alt_dirname[4] = { 0, 0, 0, 0 };
  809. if (dirp == 0) {
  810. errno = ENOMEM;
  811. return 0;
  812. }
  813. /*
  814. * Win32 accepts "\" in its POSIX stat(), but refuses to treat it
  815. * as a directory in FindFirstFile(). We detect this case here and
  816. * prepend the current drive name.
  817. */
  818. if (dirname[1] == '\0' && dirname[0] == '\\') {
  819. alt_dirname[0] = _getdrive() + 'A' - 1;
  820. alt_dirname[1] = ':';
  821. alt_dirname[2] = '\\';
  822. alt_dirname[3] = '\0';
  823. dirname = alt_dirname;
  824. }
  825. dirp->path = (char *)malloc(strlen(dirname) + 5);
  826. if (dirp->path == 0) {
  827. free(dirp);
  828. errno = ENOMEM;
  829. return 0;
  830. }
  831. strcpy(dirp->path, dirname);
  832. fattr = GetFileAttributes(dirp->path);
  833. if (fattr == 0xffffffff) {
  834. free(dirp->path);
  835. free(dirp);
  836. errno = ENOENT;
  837. return 0;
  838. } else if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  839. free(dirp->path);
  840. free(dirp);
  841. errno = ENOTDIR;
  842. return 0;
  843. }
  844. /* Append "*.*", or possibly "\\*.*", to path */
  845. if (dirp->path[1] == ':'
  846. && (dirp->path[2] == '\0'
  847. || (dirp->path[2] == '\\' && dirp->path[3] == '\0'))) {
  848. /* No '\\' needed for cases like "Z:" or "Z:\" */
  849. strcat(dirp->path, "*.*");
  850. } else {
  851. strcat(dirp->path, "\\*.*");
  852. }
  853. dirp->handle = FindFirstFile(dirp->path, &dirp->find_data);
  854. if (dirp->handle == INVALID_HANDLE_VALUE) {
  855. if (GetLastError() != ERROR_FILE_NOT_FOUND) {
  856. free(dirp->path);
  857. free(dirp);
  858. errno = EACCES;
  859. return 0;
  860. }
  861. }
  862. return dirp;
  863. }
  864. /* parameter dbuf unused on Windows */
  865. struct dirent *
  866. os::readdir(DIR *dirp, dirent *dbuf)
  867. {
  868. assert(dirp != NULL, "just checking"); // hotspot change
  869. if (dirp->handle == INVALID_HANDLE_VALUE) {
  870. return 0;
  871. }
  872. strcpy(dirp->dirent.d_name, dirp->find_data.cFileName);
  873. if (!FindNextFile(dirp->handle, &dirp->find_data)) {
  874. if (GetLastError() == ERROR_INVALID_HANDLE) {
  875. errno = EBADF;
  876. return 0;
  877. }
  878. FindClose(dirp->handle);
  879. dirp->handle = INVALID_HANDLE_VALUE;
  880. }
  881. return &dirp->dirent;
  882. }
  883. int
  884. os::closedir(DIR *dirp)
  885. {
  886. assert(dirp != NULL, "just checking"); // hotspot change
  887. if (dirp->handle != INVALID_HANDLE_VALUE) {
  888. if (!FindClose(dirp->handle)) {
  889. errno = EBADF;
  890. return -1;
  891. }
  892. dirp->handle = INVALID_HANDLE_VALUE;
  893. }
  894. free(dirp->path);
  895. free(dirp);
  896. return 0;
  897. }
  898. // This must be hard coded because it's the system's temporary
  899. // directory not the java application's temp directory, ala java.io.tmpdir.
  900. const char* os::get_temp_directory() {
  901. static char path_buf[MAX_PATH];
  902. if (GetTempPath(MAX_PATH, path_buf)>0)
  903. return path_buf;
  904. else{
  905. path_buf[0]='\0';
  906. return path_buf;
  907. }
  908. }
  909. static bool file_exists(const char* filename) {
  910. if (filename == NULL || strlen(filename) == 0) {
  911. return false;
  912. }
  913. return GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES;
  914. }
  915. void os::dll_build_name(char *buffer, size_t buflen,
  916. const char* pname, const char* fname) {
  917. const size_t pnamelen = pname ? strlen(pname) : 0;
  918. const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0;
  919. // Quietly truncates on buffer overflow. Should be an error.
  920. if (pnamelen + strlen(fname) + 10 > buflen) {
  921. *buffer = '\0';
  922. return;
  923. }
  924. if (pnamelen == 0) {
  925. jio_snprintf(buffer, buflen, "%s.dll", fname);
  926. } else if (c == ':' || c == '\\') {
  927. jio_snprintf(buffer, buflen, "%s%s.dll", pname, fname);
  928. } else if (strchr(pname, *os::path_separator()) != NULL) {
  929. int n;
  930. char** pelements = split_path(pname, &n);
  931. for (int i = 0 ; i < n ; i++) {
  932. char* path = pelements[i];
  933. // Really shouldn't be NULL, but check can't hurt
  934. size_t plen = (path == NULL) ? 0 : strlen(path);
  935. if (plen == 0) {
  936. continue; // skip the empty path values
  937. }
  938. const char lastchar = path[plen - 1];
  939. if (lastchar == ':' || lastchar == '\\') {
  940. jio_snprintf(buffer, buflen, "%s%s.dll", path, fname);
  941. } else {
  942. jio_snprintf(buffer, buflen, "%s\\%s.dll", path, fname);
  943. }
  944. if (file_exists(buffer)) {
  945. break;
  946. }
  947. }
  948. // release the storage
  949. for (int i = 0 ; i < n ; i++) {
  950. if (pelements[i] != NULL) {
  951. FREE_C_HEAP_ARRAY(char, pelements[i]);
  952. }
  953. }
  954. if (pelements != NULL) {
  955. FREE_C_HEAP_ARRAY(char*, pelements);
  956. }
  957. } else {
  958. jio_snprintf(buffer, buflen, "%s\\%s.dll", pname, fname);
  959. }
  960. }
  961. // Needs to be in os specific directory because windows requires another
  962. // header file <direct.h>
  963. const char* os::get_current_directory(char *buf, int buflen) {
  964. return _getcwd(buf, buflen);
  965. }
  966. //-----------------------------------------------------------
  967. // Helper functions for fatal error handler
  968. // The following library functions are resolved dynamically at runtime:
  969. // PSAPI functions, for Windows NT, 2000, XP
  970. // psapi.h doesn't come with Visual Studio 6; it can be downloaded as Platform
  971. // SDK from Microsoft. Here are the definitions copied from psapi.h
  972. typedef struct _MODULEINFO {
  973. LPVOID lpBaseOfDll;
  974. DWORD SizeOfImage;
  975. LPVOID EntryPoint;
  976. } MODULEINFO, *LPMODULEINFO;
  977. static BOOL (WINAPI *_EnumProcessModules) ( HANDLE, HMODULE *, DWORD, LPDWORD );
  978. static DWORD (WINAPI *_GetModuleFileNameEx) ( HANDLE, HMODULE, LPTSTR, DWORD );
  979. static BOOL (WINAPI *_GetModuleInformation)( HANDLE, HMODULE, LPMODULEINFO, DWORD );
  980. // ToolHelp Functions, for Windows 95, 98 and ME
  981. static HANDLE(WINAPI *_CreateToolhelp32Snapshot)(DWORD,DWORD) ;
  982. static BOOL (WINAPI *_Module32First) (HANDLE,LPMODULEENTRY32) ;
  983. static BOOL (WINAPI *_Module32Next) (HANDLE,LPMODULEENTRY32) ;
  984. bool _has_psapi;
  985. bool _psapi_init = false;
  986. bool _has_toolhelp;
  987. static bool _init_psapi() {
  988. HINSTANCE psapi = LoadLibrary( "PSAPI.DLL" ) ;
  989. if( psapi == NULL ) return false ;
  990. _EnumProcessModules = CAST_TO_FN_PTR(
  991. BOOL(WINAPI *)(HANDLE, HMODULE *, DWORD, LPDWORD),
  992. GetProcAddress(psapi, "EnumProcessModules")) ;
  993. _GetModuleFileNameEx = CAST_TO_FN_PTR(
  994. DWORD (WINAPI *)(HANDLE, HMODULE, LPTSTR, DWORD),
  995. GetProcAddress(psapi, "GetModuleFileNameExA"));
  996. _GetModuleInformation = CAST_TO_FN_PTR(
  997. BOOL (WINAPI *)(HANDLE, HMODULE, LPMODULEINFO, DWORD),
  998. GetProcAddress(psapi, "GetModuleInformation"));
  999. _has_psapi = (_EnumProcessModules && _GetModuleFileNameEx && _GetModuleInformation);
  1000. _psapi_init = true;
  1001. return _has_psapi;
  1002. }
  1003. static bool _init_toolhelp() {
  1004. HINSTANCE kernel32 = LoadLibrary("Kernel32.DLL") ;
  1005. if (kernel32 == NULL) return false ;
  1006. _CreateToolhelp32Snapshot = CAST_TO_FN_PTR(
  1007. HANDLE(WINAPI *)(DWORD,DWORD),
  1008. GetProcAddress(kernel32, "CreateToolhelp32Snapshot"));
  1009. _Module32First = CAST_TO_FN_PTR(
  1010. BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32),
  1011. GetProcAddress(kernel32, "Module32First" ));
  1012. _Module32Next = CAST_TO_FN_PTR(
  1013. BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32),
  1014. GetProcAddress(kernel32, "Module32Next" ));
  1015. _has_toolhelp = (_CreateToolhelp32Snapshot && _Module32First && _Module32Next);
  1016. return _has_toolhelp;
  1017. }
  1018. #ifdef _WIN64
  1019. // Helper routine which returns true if address in
  1020. // within the NTDLL address space.
  1021. //
  1022. static bool _addr_in_ntdll( address addr )
  1023. {
  1024. HMODULE hmod;
  1025. MODULEINFO minfo;
  1026. hmod = GetModuleHandle("NTDLL.DLL");
  1027. if ( hmod == NULL ) return false;
  1028. if ( !_GetModuleInformation( GetCurrentProcess(), hmod,
  1029. &minfo, sizeof(MODULEINFO)) )
  1030. return false;
  1031. if ( (addr >= minfo.lpBaseOfDll) &&
  1032. (addr < (address)((uintptr_t)minfo.lpBaseOfDll + (uintptr_t)minfo.SizeOfImage)))
  1033. return true;
  1034. else
  1035. return false;
  1036. }
  1037. #endif
  1038. // Enumerate all modules for a given process ID
  1039. //
  1040. // Notice that Windows 95/98/Me and Windows NT/2000/XP have
  1041. // different API for doing this. We use PSAPI.DLL on NT based
  1042. // Windows and ToolHelp on 95/98/Me.
  1043. // Callback function that is called by enumerate_modules() on
  1044. // every DLL module.
  1045. // Input parameters:
  1046. // int pid,
  1047. // char* module_file_name,
  1048. // address module_base_addr,
  1049. // unsigned module_size,
  1050. // void* param
  1051. typedef int (*EnumModulesCallbackFunc)(int, char *, address, unsigned, void *);
  1052. // enumerate_modules for Windows NT, using PSAPI
  1053. static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void * param)
  1054. {
  1055. HANDLE hProcess ;
  1056. # define MAX_NUM_MODULES 128
  1057. HMODULE modules[MAX_NUM_MODULES];
  1058. static char filename[ MAX_PATH ];
  1059. int result = 0;
  1060. if (!_has_psapi && (_psapi_init || !_init_psapi())) return 0;
  1061. hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
  1062. FALSE, pid ) ;
  1063. if (hProcess == NULL) return 0;
  1064. DWORD size_needed;
  1065. if (!_EnumProcessModules(hProcess, modules,
  1066. sizeof(modules), &size_needed)) {
  1067. CloseHandle( hProcess );
  1068. return 0;
  1069. }
  1070. // number of modules that are currently loaded
  1071. int num_modules = size_needed / sizeof(HMODULE);
  1072. for (int i = 0; i < MIN2(num_modules, MAX_NUM_MODULES); i++) {
  1073. // Get Full pathname:
  1074. if(!_GetModuleFileNameEx(hProcess, modules[i],
  1075. filename, sizeof(filename))) {
  1076. filename[0] = '\0';
  1077. }
  1078. MODULEINFO modinfo;
  1079. if (!_GetModuleInformation(hProcess, modules[i],
  1080. &modinfo, sizeof(modinfo))) {
  1081. modinfo.lpBaseOfDll = NULL;
  1082. modinfo.SizeOfImage = 0;
  1083. }
  1084. // Invoke callback function
  1085. result = func(pid, filename, (address)modinfo.lpBaseOfDll,
  1086. modinfo.SizeOfImage, param);
  1087. if (result) break;
  1088. }
  1089. CloseHandle( hProcess ) ;
  1090. return result;
  1091. }
  1092. // enumerate_modules for Windows 95/98/ME, using TOOLHELP
  1093. static int _enumerate_modules_windows( int pid, EnumModulesCallbackFunc func, void *param)
  1094. {
  1095. HANDLE hSnapShot ;
  1096. static MODULEENTRY32 modentry ;
  1097. int result = 0;
  1098. if (!_has_toolhelp) return 0;
  1099. // Get a handle to a Toolhelp snapshot of the system
  1100. hSnapShot = _CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid ) ;
  1101. if( hSnapShot == INVALID_HANDLE_VALUE ) {
  1102. return FALSE ;
  1103. }
  1104. // iterate through all modules
  1105. modentry.dwSize = sizeof(MODULEENTRY32) ;
  1106. bool not_done = _Module32First( hSnapShot, &modentry ) != 0;
  1107. while( not_done ) {
  1108. // invoke the callback
  1109. result=func(pid, modentry.szExePath, (address)modentry.modBaseAddr,
  1110. modentry.modBaseSize, param);
  1111. if (result) break;
  1112. modentry.dwSize = sizeof(MODULEENTRY32) ;
  1113. not_done = _Module32Next( hSnapShot, &modentry ) != 0;
  1114. }
  1115. CloseHandle(hSnapShot);
  1116. return result;
  1117. }
  1118. int enumerate_modules( int pid, EnumModulesCallbackFunc func, void * param )
  1119. {
  1120. // Get current process ID if caller doesn't provide it.
  1121. if (!pid) pid = os::current_process_id();
  1122. if (os::win32::is_nt()) return _enumerate_modules_winnt (pid, func, param);
  1123. else return _enumerate_modules_windows(pid, func, param);
  1124. }
  1125. struct _modinfo {
  1126. address addr;
  1127. char* full_path; // point to a char buffer
  1128. int buflen; // size of the buffer
  1129. address base_addr;
  1130. };
  1131. static int _locate_module_by_addr(int pid, char * mod_fname, address base_addr,
  1132. unsigned size, void * param) {
  1133. struct _modinfo *pmod = (struct _modinfo *)param;
  1134. if (!pmod) return -1;
  1135. if (base_addr <= pmod->addr &&
  1136. base_addr+size > pmod->addr) {
  1137. // if a buffer is provided, copy path name to the buffer
  1138. if (pmod->full_path) {
  1139. jio_snprintf(pmod->full_path, pmod->buflen, "%s", mod_fname);
  1140. }
  1141. pmod->base_addr = base_addr;
  1142. return 1;
  1143. }
  1144. return 0;
  1145. }
  1146. bool os::dll_address_to_library_name(address addr, char* buf,
  1147. int buflen, int* offset) {
  1148. // NOTE: the reason we don't use SymGetModuleInfo() is it doesn't always
  1149. // return the full path to the DLL file, sometimes it returns path
  1150. // to the corresponding PDB file (debug info); sometimes it only
  1151. // returns partial path, which makes life painful.
  1152. struct _modinfo mi;
  1153. mi.addr = addr;
  1154. mi.full_path = buf;
  1155. mi.buflen = buflen;
  1156. int pid = os::current_process_id();
  1157. if (enumerate_modules(pid, _locate_module_by_addr, (void *)&mi)) {
  1158. // buf already contains path name
  1159. if (offset) *offset = addr - mi.base_addr;
  1160. return true;
  1161. } else {
  1162. if (buf) buf[0] = '\0';
  1163. if (offset) *offset = -1;
  1164. return false;
  1165. }
  1166. }
  1167. bool os::dll_address_to_function_name(address addr, char *buf,
  1168. int buflen, int *offset) {
  1169. if (Decoder::decode(addr, buf, buflen, offset) == Decoder::no_error) {
  1170. return true;
  1171. }
  1172. if (offset != NULL) *offset = -1;
  1173. if (buf != NULL) buf[0] = '\0';
  1174. return false;
  1175. }
  1176. // save the start and end address of jvm.dll into param[0] and param[1]
  1177. static int _locate_jvm_dll(int pid, char* mod_fname, address base_addr,
  1178. unsigned size, void * param) {
  1179. if (!param) return -1;
  1180. if (base_addr <= (address)_locate_jvm_dll &&
  1181. base_addr+size > (address)_locate_jvm_dll) {
  1182. ((address*)param)[0] = base_addr;
  1183. ((address*)param)[1] = base_addr + size;
  1184. return 1;
  1185. }
  1186. return 0;
  1187. }
  1188. address vm_lib_location[2]; // start and end address of jvm.dll
  1189. // check if addr is inside jvm.dll
  1190. bool os::address_is_in_vm(address addr) {
  1191. if (!vm_lib_location[0] || !vm_lib_location[1]) {
  1192. int pid = os::current_process_id();
  1193. if (!enumerate_modules(pid, _locate_jvm_dll, (void *)vm_lib_location)) {
  1194. assert(false, "Can't find jvm module.");
  1195. return false;
  1196. }
  1197. }
  1198. return (vm_lib_location[0] <= addr) && (addr < vm_lib_location[1]);
  1199. }
  1200. // print module info; param is outputStream*
  1201. static int _print_module(int pid, char* fname, address base,
  1202. unsigned size, void* param) {
  1203. if (!param) return -1;
  1204. outputStream* st = (outputStream*)param;
  1205. address end_addr = base + size;
  1206. st->print(PTR_FORMAT " - " PTR_FORMAT " \t%s\n", base, end_addr, fname);
  1207. return 0;
  1208. }
  1209. // Loads .dll/.so and
  1210. // in case of error it checks if .dll/.so was built for the
  1211. // same architecture as Hotspot is running on
  1212. void * os::dll_load(const char *name, char *ebuf, int ebuflen)
  1213. {
  1214. void * result = LoadLibrary(name);
  1215. if (result != NULL)
  1216. {
  1217. return result;
  1218. }
  1219. long errcode = GetLastError();
  1220. if (errcode == ERROR_MOD_NOT_FOUND) {
  1221. strncpy(ebuf, "Can't find dependent libraries", ebuflen-1);
  1222. ebuf[ebuflen-1]='\0';
  1223. return NULL;
  1224. }
  1225. // Parsing dll below
  1226. // If we can read dll-info and find that dll was built
  1227. // for an architecture other than Hotspot is running in
  1228. // - then print to buffer "DLL was built for a different architecture"
  1229. // else call getLastErrorString to obtain system error message
  1230. // Read system error message into ebuf
  1231. // It may or may not be overwritten below (in the for loop and just above)
  1232. getLastErrorString(ebuf, (size_t) ebuflen);
  1233. ebuf[ebuflen-1]='\0';
  1234. int file_descriptor=::open(name, O_RDONLY | O_BINARY, 0);
  1235. if (file_descriptor<0)
  1236. {
  1237. return NULL;
  1238. }
  1239. uint32_t signature_offset;
  1240. uint16_t lib_arch=0;
  1241. bool failed_to_get_lib_arch=
  1242. (
  1243. //Go to position 3c in the dll
  1244. (os::seek_to_file_offset(file_descriptor,IMAGE_FILE_PTR_TO_SIGNATURE)<0)
  1245. ||
  1246. // Read loacation of signature
  1247. (sizeof(signature_offset)!=
  1248. (os::read(file_descriptor, (void*)&signature_offset,sizeof(signature_offset))))
  1249. ||
  1250. //Go to COFF File Header in dll
  1251. //that is located after"signature" (4 bytes long)
  1252. (os::seek_to_file_offset(file_descriptor,
  1253. signature_offset+IMAGE_FILE_SIGNATURE_LENGTH)<0)
  1254. ||
  1255. //Read field that contains code of architecture
  1256. // that dll was build for
  1257. (sizeof(lib_arch)!=
  1258. (os::read(file_descriptor, (void*)&lib_arch,sizeof(lib_arch))))
  1259. );
  1260. ::close(file_descriptor);
  1261. if (failed_to_get_lib_arch)
  1262. {
  1263. // file i/o error - report getLastErrorString(...) msg
  1264. return NULL;
  1265. }
  1266. typedef struct
  1267. {
  1268. uint16_t arch_code;
  1269. char* arch_name;
  1270. } arch_t;
  1271. static const arch_t arch_array[]={
  1272. {IMAGE_FILE_MACHINE_I386, (char*)"IA 32"},
  1273. {IMAGE_FILE_MACHINE_AMD64, (char*)"AMD 64"},
  1274. {IMAGE_FILE_MACHINE_IA64, (char*)"IA 64"}
  1275. };
  1276. #if (defined _M_IA64)
  1277. static const uint16_t running_arch=IMAGE_FILE_MACHINE_IA64;
  1278. #elif (defined _M_AMD64)
  1279. static const uint16_t running_arch=IMAGE_FILE_MACHINE_AMD64;
  1280. #elif (defined _M_IX86)
  1281. static const uint16_t running_arch=IMAGE_FILE_MACHINE_I386;
  1282. #else
  1283. #error Method os::dll_load requires that one of following \
  1284. is defined :_M_IA64,_M_AMD64 or _M_IX86
  1285. #endif
  1286. // Obtain a string for printf operation
  1287. // lib_arch_str shall contain string what platform this .dll was built for
  1288. // running_arch_str shall string contain what platform Hotspot was built for
  1289. char *running_arch_str=NULL,*lib_arch_str=NULL;
  1290. for (unsigned int i=0;i<ARRAY_SIZE(arch_array);i++)
  1291. {
  1292. if (lib_arch==arch_array[i].arch_code)
  1293. lib_arch_str=arch_array[i].arch_name;
  1294. if (running_arch==arch_array[i].arch_code)
  1295. running_arch_str=arch_array[i].arch_name;
  1296. }
  1297. assert(running_arch_str,
  1298. "Didn't find runing architecture code in arch_array");
  1299. // If the architure is right
  1300. // but some other error took place - report getLastErrorString(...) msg
  1301. if (lib_arch == running_arch)
  1302. {
  1303. return NULL;
  1304. }
  1305. if (lib_arch_str!=NULL)
  1306. {
  1307. ::_snprintf(ebuf, ebuflen-1,
  1308. "Can't load %s-bit .dll on a %s-bit platform",
  1309. lib_arch_str,running_arch_str);
  1310. }
  1311. else
  1312. {
  1313. // don't know what architecture this dll was build for
  1314. ::_snprintf(ebuf, ebuflen-1,
  1315. "Can't load this .dll (machine code=0x%x) on a %s-bit platform",
  1316. lib_arch,running_arch_str);
  1317. }
  1318. return NULL;
  1319. }
  1320. void os::print_dll_info(outputStream *st) {
  1321. int pid = os::current_process_id();
  1322. st->print_cr("Dynamic libraries:");
  1323. enumerate_modules(pid, _print_module, (void *)st);
  1324. }
  1325. // function pointer to Windows API "GetNativeSystemInfo".
  1326. typedef void (WINAPI *GetNativeSystemInfo_func_type)(LPSYSTEM_INFO);
  1327. static GetNativeSystemInfo_func_type _GetNativeSystemInfo;
  1328. void os::print_os_info(outputStream* st) {
  1329. st->print("OS:");
  1330. OSVERSIONINFOEX osvi;
  1331. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  1332. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  1333. if (!GetVersionEx((OSVERSIONINFO *)&osvi)) {
  1334. st->print_cr("N/A");
  1335. return;
  1336. }
  1337. int os_vers = osvi.dwMajorVersion * 1000 + osvi.dwMinorVersion;
  1338. if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
  1339. switch (os_vers) {
  1340. case 3051: st->print(" Windows NT 3.51"); break;
  1341. case 4000: st->print(" Windows NT 4.0"); break;
  1342. case 5000: st->print(" Windows 2000"); break;
  1343. case 5001: st->print(" Windows XP"); break;
  1344. case 5002:
  1345. case 6000:
  1346. case 6001: {
  1347. // Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could
  1348. // find out whether we are running on 64 bit processor or not.
  1349. SYSTEM_INFO si;
  1350. ZeroMemory(&si, sizeof(SYSTEM_INFO));
  1351. // Check to see if _GetNativeSystemInfo has been initialized.
  1352. if (_GetNativeSystemInfo == NULL) {
  1353. HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32.dll"));
  1354. _GetNativeSystemInfo =
  1355. CAST_TO_FN_PTR(GetNativeSystemInfo_func_type,
  1356. GetProcAddress(hKernel32,
  1357. "GetNativeSystemInfo"));
  1358. if (_GetNativeSystemInfo == NULL)
  1359. GetSystemInfo(&si);
  1360. } else {
  1361. _GetNativeSystemInfo(&si);
  1362. }
  1363. if (os_vers == 5002) {
  1364. if (osvi.wProductType == VER_NT_WORKSTATION &&
  1365. si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
  1366. st->print(" Windows XP x64 Edition");
  1367. else
  1368. st->print(" Windows Server 2003 family");
  1369. } else if (os_vers == 6000) {
  1370. if (osvi.wProductType == VER_NT_WORKSTATION)
  1371. st->print(" Windows Vista");
  1372. else
  1373. st->print(" Windows Server 2008");
  1374. if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
  1375. st->print(" , 64 bit");
  1376. } else if (os_vers == 6001) {
  1377. if (osvi.wProductType == VER_NT_WORKSTATION) {
  1378. st->print(" Windows 7");
  1379. } else {
  1380. st->print(" Windows Server 2008 R2");
  1381. }
  1382. if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
  1383. st->print(" , 64 bit");
  1384. } else { // future os
  1385. // Unrecognized windows, print out its major and minor versions
  1386. st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
  1387. if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
  1388. st->print(" , 64 bit");
  1389. }
  1390. break;
  1391. }
  1392. default: // future windows, print out its major and minor versions
  1393. st->print(" Windows NT %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
  1394. }
  1395. } else {
  1396. switch (os_vers) {
  1397. case 4000: st->print(" Windows 95"); break;
  1398. case 4010: st->print(" Windows 98"); break;
  1399. case 4090: st->print(" Windows Me"); break;
  1400. default: // future windows, print out its major and minor versions
  1401. st->print(" Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
  1402. }
  1403. }
  1404. st->print(" Build %d", osvi.dwBuildNumber);
  1405. st->print(" %s", osvi.szCSDVersion); // service pack
  1406. st->cr();
  1407. }
  1408. void os::print_memory_info(outputStream* st) {
  1409. st->print("Memory:");
  1410. st->print(" %dk page", os::vm_page_size()>>10);
  1411. // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect
  1412. // value if total memory is larger than 4GB
  1413. MEMORYSTATUSEX ms;
  1414. ms.dwLength = sizeof(ms);
  1415. GlobalMemoryStatusEx(&ms);
  1416. st->print(", physical %uk", os::phys

Large files files are truncated, but you can click here to view the full file