PageRenderTime 70ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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::physical_memory() >> 10);
  1417. st->print("(%uk free)", os::available_memory() >> 10);
  1418. st->print(", swap %uk", ms.ullTotalPageFile >> 10);
  1419. st->print("(%uk free)", ms.ullAvailPageFile >> 10);
  1420. st->cr();
  1421. }
  1422. void os::print_siginfo(outputStream *st, void *siginfo) {
  1423. EXCEPTION_RECORD* er = (EXCEPTION_RECORD*)siginfo;
  1424. st->print("siginfo:");
  1425. st->print(" ExceptionCode=0x%x", er->ExceptionCode);
  1426. if (er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
  1427. er->NumberParameters >= 2) {
  1428. switch (er->ExceptionInformation[0]) {
  1429. case 0: st->print(", reading address"); break;
  1430. case 1: st->print(", writing address"); break;
  1431. default: st->print(", ExceptionInformation=" INTPTR_FORMAT,
  1432. er->ExceptionInformation[0]);
  1433. }
  1434. st->print(" " INTPTR_FORMAT, er->ExceptionInformation[1]);
  1435. } else if (er->ExceptionCode == EXCEPTION_IN_PAGE_ERROR &&
  1436. er->NumberParameters >= 2 && UseSharedSpaces) {
  1437. FileMapInfo* mapinfo = FileMapInfo::current_info();
  1438. if (mapinfo->is_in_shared_space((void*)er->ExceptionInformation[1])) {
  1439. st->print("\n\nError accessing class data sharing archive." \
  1440. " Mapped file inaccessible during execution, " \
  1441. " possible disk/network problem.");
  1442. }
  1443. } else {
  1444. int num = er->NumberParameters;
  1445. if (num > 0) {
  1446. st->print(", ExceptionInformation=");
  1447. for (int i = 0; i < num; i++) {
  1448. st->print(INTPTR_FORMAT " ", er->ExceptionInformation[i]);
  1449. }
  1450. }
  1451. }
  1452. st->cr();
  1453. }
  1454. void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  1455. // do nothing
  1456. }
  1457. static char saved_jvm_path[MAX_PATH] = {0};
  1458. // Find the full path to the current module, jvm.dll or jvm_g.dll
  1459. void os::jvm_path(char *buf, jint buflen) {
  1460. // Error checking.
  1461. if (buflen < MAX_PATH) {
  1462. assert(false, "must use a large-enough buffer");
  1463. buf[0] = '\0';
  1464. return;
  1465. }
  1466. // Lazy resolve the path to current module.
  1467. if (saved_jvm_path[0] != 0) {
  1468. strcpy(buf, saved_jvm_path);
  1469. return;
  1470. }
  1471. buf[0] = '\0';
  1472. if (strcmp(Arguments::sun_java_launcher(), "gamma") == 0) {
  1473. // Support for the gamma launcher. Check for an
  1474. // JAVA_HOME environment variable
  1475. // and fix up the path so it looks like
  1476. // libjvm.so is installed there (append a fake suffix
  1477. // hotspot/libjvm.so).
  1478. char* java_home_var = ::getenv("JAVA_HOME");
  1479. if (java_home_var != NULL && java_home_var[0] != 0) {
  1480. strncpy(buf, java_home_var, buflen);
  1481. // determine if this is a legacy image or modules image
  1482. // modules image doesn't have "jre" subdirectory
  1483. size_t len = strlen(buf);
  1484. char* jrebin_p = buf + len;
  1485. jio_snprintf(jrebin_p, buflen-len, "\\jre\\bin\\");
  1486. if (0 != _access(buf, 0)) {
  1487. jio_snprintf(jrebin_p, buflen-len, "\\bin\\");
  1488. }
  1489. len = strlen(buf);
  1490. jio_snprintf(buf + len, buflen-len, "hotspot\\jvm.dll");
  1491. }
  1492. }
  1493. if(buf[0] == '\0') {
  1494. GetModuleFileName(vm_lib_handle, buf, buflen);
  1495. }
  1496. strcpy(saved_jvm_path, buf);
  1497. }
  1498. void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  1499. #ifndef _WIN64
  1500. st->print("_");
  1501. #endif
  1502. }
  1503. void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  1504. #ifndef _WIN64
  1505. st->print("@%d", args_size * sizeof(int));
  1506. #endif
  1507. }
  1508. // This method is a copy of JDK's sysGetLastErrorString
  1509. // from src/windows/hpi/src/system_md.c
  1510. size_t os::lasterror(char *buf, size_t len) {
  1511. long errval;
  1512. if ((errval = GetLastError()) != 0) {
  1513. /* DOS error */
  1514. int n = (int)FormatMessage(
  1515. FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1516. NULL,
  1517. errval,
  1518. 0,
  1519. buf,
  1520. (DWORD)len,
  1521. NULL);
  1522. if (n > 3) {
  1523. /* Drop final '.', CR, LF */
  1524. if (buf[n - 1] == '\n') n--;
  1525. if (buf[n - 1] == '\r') n--;
  1526. if (buf[n - 1] == '.') n--;
  1527. buf[n] = '\0';
  1528. }
  1529. return n;
  1530. }
  1531. if (errno != 0) {
  1532. /* C runtime error that has no corresponding DOS error code */
  1533. const char *s = strerror(errno);
  1534. size_t n = strlen(s);
  1535. if (n >= len) n = len - 1;
  1536. strncpy(buf, s, n);
  1537. buf[n] = '\0';
  1538. return n;
  1539. }
  1540. return 0;
  1541. }
  1542. // sun.misc.Signal
  1543. // NOTE that this is a workaround for an apparent kernel bug where if
  1544. // a signal handler for SIGBREAK is installed then that signal handler
  1545. // takes priority over the console control handler for CTRL_CLOSE_EVENT.
  1546. // See bug 4416763.
  1547. static void (*sigbreakHandler)(int) = NULL;
  1548. static void UserHandler(int sig, void *siginfo, void *context) {
  1549. os::signal_notify(sig);
  1550. // We need to reinstate the signal handler each time...
  1551. os::signal(sig, (void*)UserHandler);
  1552. }
  1553. void* os::user_handler() {
  1554. return (void*) UserHandler;
  1555. }
  1556. void* os::signal(int signal_number, void* handler) {
  1557. if ((signal_number == SIGBREAK) && (!ReduceSignalUsage)) {
  1558. void (*oldHandler)(int) = sigbreakHandler;
  1559. sigbreakHandler = (void (*)(int)) handler;
  1560. return (void*) oldHandler;
  1561. } else {
  1562. return (void*)::signal(signal_number, (void (*)(int))handler);
  1563. }
  1564. }
  1565. void os::signal_raise(int signal_number) {
  1566. raise(signal_number);
  1567. }
  1568. // The Win32 C runtime library maps all console control events other than ^C
  1569. // into SIGBREAK, which makes it impossible to distinguish ^BREAK from close,
  1570. // logoff, and shutdown events. We therefore install our own console handler
  1571. // that raises SIGTERM for the latter cases.
  1572. //
  1573. static BOOL WINAPI consoleHandler(DWORD event) {
  1574. switch(event) {
  1575. case CTRL_C_EVENT:
  1576. if (is_error_reported()) {
  1577. // Ctrl-C is pressed during error reporting, likely because the error
  1578. // handler fails to abort. Let VM die immediately.
  1579. os::die();
  1580. }
  1581. os::signal_raise(SIGINT);
  1582. return TRUE;
  1583. break;
  1584. case CTRL_BREAK_EVENT:
  1585. if (sigbreakHandler != NULL) {
  1586. (*sigbreakHandler)(SIGBREAK);
  1587. }
  1588. return TRUE;
  1589. break;
  1590. case CTRL_CLOSE_EVENT:
  1591. case CTRL_LOGOFF_EVENT:
  1592. case CTRL_SHUTDOWN_EVENT:
  1593. os::signal_raise(SIGTERM);
  1594. return TRUE;
  1595. break;
  1596. default:
  1597. break;
  1598. }
  1599. return FALSE;
  1600. }
  1601. /*
  1602. * The following code is moved from os.cpp for making this
  1603. * code platform specific, which it is by its very nature.
  1604. */
  1605. // Return maximum OS signal used + 1 for internal use only
  1606. // Used as exit signal for signal_thread
  1607. int os::sigexitnum_pd(){
  1608. return NSIG;
  1609. }
  1610. // a counter for each possible signal value, including signal_thread exit signal
  1611. static volatile jint pending_signals[NSIG+1] = { 0 };
  1612. static HANDLE sig_sem;
  1613. void os::signal_init_pd() {
  1614. // Initialize signal structures
  1615. memset((void*)pending_signals, 0, sizeof(pending_signals));
  1616. sig_sem = ::CreateSemaphore(NULL, 0, NSIG+1, NULL);
  1617. // Programs embedding the VM do not want it to attempt to receive
  1618. // events like CTRL_LOGOFF_EVENT, which are used to implement the
  1619. // shutdown hooks mechanism introduced in 1.3. For example, when
  1620. // the VM is run as part of a Windows NT service (i.e., a servlet
  1621. // engine in a web server), the correct behavior is for any console
  1622. // control handler to return FALSE, not TRUE, because the OS's
  1623. // "final" handler for such events allows the process to continue if
  1624. // it is a service (while terminating it if it is not a service).
  1625. // To make this behavior uniform and the mechanism simpler, we
  1626. // completely disable the VM's usage of these console events if -Xrs
  1627. // (=ReduceSignalUsage) is specified. This means, for example, that
  1628. // the CTRL-BREAK thread dump mechanism is also disabled in this
  1629. // case. See bugs 4323062, 4345157, and related bugs.
  1630. if (!ReduceSignalUsage) {
  1631. // Add a CTRL-C handler
  1632. SetConsoleCtrlHandler(consoleHandler, TRUE);
  1633. }
  1634. }
  1635. void os::signal_notify(int signal_number) {
  1636. BOOL ret;
  1637. Atomic::inc(&pending_signals[signal_number]);
  1638. ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
  1639. assert(ret != 0, "ReleaseSemaphore() failed");
  1640. }
  1641. static int check_pending_signals(bool wait_for_signal) {
  1642. DWORD ret;
  1643. while (true) {
  1644. for (int i = 0; i < NSIG + 1; i++) {
  1645. jint n = pending_signals[i];
  1646. if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  1647. return i;
  1648. }
  1649. }
  1650. if (!wait_for_signal) {
  1651. return -1;
  1652. }
  1653. JavaThread *thread = JavaThread::current();
  1654. ThreadBlockInVM tbivm(thread);
  1655. bool threadIsSuspended;
  1656. do {
  1657. thread->set_suspend_equivalent();
  1658. // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  1659. ret = ::WaitForSingleObject(sig_sem, INFINITE);
  1660. assert(ret == WAIT_OBJECT_0, "WaitForSingleObject() failed");
  1661. // were we externally suspended while we were waiting?
  1662. threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  1663. if (threadIsSuspended) {
  1664. //
  1665. // The semaphore has been incremented, but while we were waiting
  1666. // another thread suspended us. We don't want to continue running
  1667. // while suspended because that would surprise the thread that
  1668. // suspended us.
  1669. //
  1670. ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
  1671. assert(ret != 0, "ReleaseSemaphore() failed");
  1672. thread->java_suspend_self();
  1673. }
  1674. } while (threadIsSuspended);
  1675. }
  1676. }
  1677. int os::signal_lookup() {
  1678. return check_pending_signals(false);
  1679. }
  1680. int os::signal_wait() {
  1681. return check_pending_signals(true);
  1682. }
  1683. // Implicit OS exception handling
  1684. LONG Handle_Exception(struct _EXCEPTION_POINTERS* exceptionInfo, address handler) {
  1685. JavaThread* thread = JavaThread::current();
  1686. // Save pc in thread
  1687. #ifdef _M_IA64
  1688. thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->StIIP);
  1689. // Set pc to handler
  1690. exceptionInfo->ContextRecord->StIIP = (DWORD64)handler;
  1691. #elif _M_AMD64
  1692. thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Rip);
  1693. // Set pc to handler
  1694. exceptionInfo->ContextRecord->Rip = (DWORD64)handler;
  1695. #else
  1696. thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Eip);
  1697. // Set pc to handler
  1698. exceptionInfo->ContextRecord->Eip = (LONG)handler;
  1699. #endif
  1700. // Continue the execution
  1701. return EXCEPTION_CONTINUE_EXECUTION;
  1702. }
  1703. // Used for PostMortemDump
  1704. extern "C" void safepoints();
  1705. extern "C" void find(int x);
  1706. extern "C" void events();
  1707. // According to Windows API documentation, an illegal instruction sequence should generate
  1708. // the 0xC000001C exception code. However, real world experience shows that occasionnaly
  1709. // the execution of an illegal instruction can generate the exception code 0xC000001E. This
  1710. // seems to be an undocumented feature of Win NT 4.0 (and probably other Windows systems).
  1711. #define EXCEPTION_ILLEGAL_INSTRUCTION_2 0xC000001E
  1712. // From "Execution Protection in the Windows Operating System" draft 0.35
  1713. // Once a system header becomes available, the "real" define should be
  1714. // included or copied here.
  1715. #define EXCEPTION_INFO_EXEC_VIOLATION 0x08
  1716. #define def_excpt(val) #val, val
  1717. struct siglabel {
  1718. char *name;
  1719. int number;
  1720. };
  1721. // All Visual C++ exceptions thrown from code generated by the Microsoft Visual
  1722. // C++ compiler contain this error code. Because this is a compiler-generated
  1723. // error, the code is not listed in the Win32 API header files.
  1724. // The code is actually a cryptic mnemonic device, with the initial "E"
  1725. // standing for "exception" and the final 3 bytes (0x6D7363) representing the
  1726. // ASCII values of "msc".
  1727. #define EXCEPTION_UNCAUGHT_CXX_EXCEPTION 0xE06D7363
  1728. struct siglabel exceptlabels[] = {
  1729. def_excpt(EXCEPTION_ACCESS_VIOLATION),
  1730. def_excpt(EXCEPTION_DATATYPE_MISALIGNMENT),
  1731. def_excpt(EXCEPTION_BREAKPOINT),
  1732. def_excpt(EXCEPTION_SINGLE_STEP),
  1733. def_excpt(EXCEPTION_ARRAY_BOUNDS_EXCEEDED),
  1734. def_excpt(EXCEPTION_FLT_DENORMAL_OPERAND),
  1735. def_excpt(EXCEPTION_FLT_DIVIDE_BY_ZERO),
  1736. def_excpt(EXCEPTION_FLT_INEXACT_RESULT),
  1737. def_excpt(EXCEPTION_FLT_INVALID_OPERATION),
  1738. def_excpt(EXCEPTION_FLT_OVERFLOW),
  1739. def_excpt(EXCEPTION_FLT_STACK_CHECK),
  1740. def_excpt(EXCEPTION_FLT_UNDERFLOW),
  1741. def_excpt(EXCEPTION_INT_DIVIDE_BY_ZERO),
  1742. def_excpt(EXCEPTION_INT_OVERFLOW),
  1743. def_excpt(EXCEPTION_PRIV_INSTRUCTION),
  1744. def_excpt(EXCEPTION_IN_PAGE_ERROR),
  1745. def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION),
  1746. def_excpt(EXCEPTION_ILLEGAL_INSTRUCTION_2),
  1747. def_excpt(EXCEPTION_NONCONTINUABLE_EXCEPTION),
  1748. def_excpt(EXCEPTION_STACK_OVERFLOW),
  1749. def_excpt(EXCEPTION_INVALID_DISPOSITION),
  1750. def_excpt(EXCEPTION_GUARD_PAGE),
  1751. def_excpt(EXCEPTION_INVALID_HANDLE),
  1752. def_excpt(EXCEPTION_UNCAUGHT_CXX_EXCEPTION),
  1753. NULL, 0
  1754. };
  1755. const char* os::exception_name(int exception_code, char *buf, size_t size) {
  1756. for (int i = 0; exceptlabels[i].name != NULL; i++) {
  1757. if (exceptlabels[i].number == exception_code) {
  1758. jio_snprintf(buf, size, "%s", exceptlabels[i].name);
  1759. return buf;
  1760. }
  1761. }
  1762. return NULL;
  1763. }
  1764. //-----------------------------------------------------------------------------
  1765. LONG Handle_IDiv_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
  1766. // handle exception caused by idiv; should only happen for -MinInt/-1
  1767. // (division by zero is handled explicitly)
  1768. #ifdef _M_IA64
  1769. assert(0, "Fix Handle_IDiv_Exception");
  1770. #elif _M_AMD64
  1771. PCONTEXT ctx = exceptionInfo->ContextRecord;
  1772. address pc = (address)ctx->Rip;
  1773. NOT_PRODUCT(Events::log("idiv overflow exception at " INTPTR_FORMAT , pc));
  1774. assert(pc[0] == 0xF7, "not an idiv opcode");
  1775. assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
  1776. assert(ctx->Rax == min_jint, "unexpected idiv exception");
  1777. // set correct result values and continue after idiv instruction
  1778. ctx->Rip = (DWORD)pc + 2; // idiv reg, reg is 2 bytes
  1779. ctx->Rax = (DWORD)min_jint; // result
  1780. ctx->Rdx = (DWORD)0; // remainder
  1781. // Continue the execution
  1782. #else
  1783. PCONTEXT ctx = exceptionInfo->ContextRecord;
  1784. address pc = (address)ctx->Eip;
  1785. NOT_PRODUCT(Events::log("idiv overflow exception at " INTPTR_FORMAT , pc));
  1786. assert(pc[0] == 0xF7, "not an idiv opcode");
  1787. assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
  1788. assert(ctx->Eax == min_jint, "unexpected idiv exception");
  1789. // set correct result values and continue after idiv instruction
  1790. ctx->Eip = (DWORD)pc + 2; // idiv reg, reg is 2 bytes
  1791. ctx->Eax = (DWORD)min_jint; // result
  1792. ctx->Edx = (DWORD)0; // remainder
  1793. // Continue the execution
  1794. #endif
  1795. return EXCEPTION_CONTINUE_EXECUTION;
  1796. }
  1797. #ifndef _WIN64
  1798. //-----------------------------------------------------------------------------
  1799. LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
  1800. // handle exception caused by native method modifying control word
  1801. PCONTEXT ctx = exceptionInfo->ContextRecord;
  1802. DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
  1803. switch (exception_code) {
  1804. case EXCEPTION_FLT_DENORMAL_OPERAND:
  1805. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  1806. case EXCEPTION_FLT_INEXACT_RESULT:
  1807. case EXCEPTION_FLT_INVALID_OPERATION:
  1808. case EXCEPTION_FLT_OVERFLOW:
  1809. case EXCEPTION_FLT_STACK_CHECK:
  1810. case EXCEPTION_FLT_UNDERFLOW:
  1811. jint fp_control_word = (* (jint*) StubRoutines::addr_fpu_cntrl_wrd_std());
  1812. if (fp_control_word != ctx->FloatSave.ControlWord) {
  1813. // Restore FPCW and mask out FLT exceptions
  1814. ctx->FloatSave.ControlWord = fp_control_word | 0xffffffc0;
  1815. // Mask out pending FLT exceptions
  1816. ctx->FloatSave.StatusWord &= 0xffffff00;
  1817. return EXCEPTION_CONTINUE_EXECUTION;
  1818. }
  1819. }
  1820. if (prev_uef_handler != NULL) {
  1821. // We didn't handle this exception so pass it to the previous
  1822. // UnhandledExceptionFilter.
  1823. return (prev_uef_handler)(exceptionInfo);
  1824. }
  1825. return EXCEPTION_CONTINUE_SEARCH;
  1826. }
  1827. #else //_WIN64
  1828. /*
  1829. On Windows, the mxcsr control bits are non-volatile across calls
  1830. See also CR 6192333
  1831. If EXCEPTION_FLT_* happened after some native method modified
  1832. mxcsr - it is not a jvm fault.
  1833. However should we decide to restore of mxcsr after a faulty
  1834. native method we can uncomment following code
  1835. jint MxCsr = INITIAL_MXCSR;
  1836. // we can't use StubRoutines::addr_mxcsr_std()
  1837. // because in Win64 mxcsr is not saved there
  1838. if (MxCsr != ctx->MxCsr) {
  1839. ctx->MxCsr = MxCsr;
  1840. return EXCEPTION_CONTINUE_EXECUTION;
  1841. }
  1842. */
  1843. #endif //_WIN64
  1844. // Fatal error reporting is single threaded so we can make this a
  1845. // static and preallocated. If it's more than MAX_PATH silently ignore
  1846. // it.
  1847. static char saved_error_file[MAX_PATH] = {0};
  1848. void os::set_error_file(const char *logfile) {
  1849. if (strlen(logfile) <= MAX_PATH) {
  1850. strncpy(saved_error_file, logfile, MAX_PATH);
  1851. }
  1852. }
  1853. static inline void report_error(Thread* t, DWORD exception_code,
  1854. address addr, void* siginfo, void* context) {
  1855. VMError err(t, exception_code, addr, siginfo, context);
  1856. err.report_and_die();
  1857. // If UseOsErrorReporting, this will return here and save the error file
  1858. // somewhere where we can find it in the minidump.
  1859. }
  1860. //-----------------------------------------------------------------------------
  1861. LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
  1862. if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH;
  1863. DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
  1864. #ifdef _M_IA64
  1865. address pc = (address) exceptionInfo->ContextRecord->StIIP;
  1866. #elif _M_AMD64
  1867. address pc = (address) exceptionInfo->ContextRecord->Rip;
  1868. #else
  1869. address pc = (address) exceptionInfo->ContextRecord->Eip;
  1870. #endif
  1871. Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady
  1872. #ifndef _WIN64
  1873. // Execution protection violation - win32 running on AMD64 only
  1874. // Handled first to avoid misdiagnosis as a "normal" access violation;
  1875. // This is safe to do because we have a new/unique ExceptionInformation
  1876. // code for this condition.
  1877. if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
  1878. PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
  1879. int exception_subcode = (int) exceptionRecord->ExceptionInformation[0];
  1880. address addr = (address) exceptionRecord->ExceptionInformation[1];
  1881. if (exception_subcode == EXCEPTION_INFO_EXEC_VIOLATION) {
  1882. int page_size = os::vm_page_size();
  1883. // Make sure the pc and the faulting address are sane.
  1884. //
  1885. // If an instruction spans a page boundary, and the page containing
  1886. // the beginning of the instruction is executable but the following
  1887. // page is not, the pc and the faulting address might be slightly
  1888. // different - we still want to unguard the 2nd page in this case.
  1889. //
  1890. // 15 bytes seems to be a (very) safe value for max instruction size.
  1891. bool pc_is_near_addr =
  1892. (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15);
  1893. bool instr_spans_page_boundary =
  1894. (align_size_down((intptr_t) pc ^ (intptr_t) addr,
  1895. (intptr_t) page_size) > 0);
  1896. if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) {
  1897. static volatile address last_addr =
  1898. (address) os::non_memory_address_word();
  1899. // In conservative mode, don't unguard unless the address is in the VM
  1900. if (UnguardOnExecutionViolation > 0 && addr != last_addr &&
  1901. (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) {
  1902. // Set memory to RWX and retry
  1903. address page_start =
  1904. (address) align_size_down((intptr_t) addr, (intptr_t) page_size);
  1905. bool res = os::protect_memory((char*) page_start, page_size,
  1906. os::MEM_PROT_RWX);
  1907. if (PrintMiscellaneous && Verbose) {
  1908. char buf[256];
  1909. jio_snprintf(buf, sizeof(buf), "Execution protection violation "
  1910. "at " INTPTR_FORMAT
  1911. ", unguarding " INTPTR_FORMAT ": %s", addr,
  1912. page_start, (res ? "success" : strerror(errno)));
  1913. tty->print_raw_cr(buf);
  1914. }
  1915. // Set last_addr so if we fault again at the same address, we don't
  1916. // end up in an endless loop.
  1917. //
  1918. // There are two potential complications here. Two threads trapping
  1919. // at the same address at the same time could cause one of the
  1920. // threads to think it already unguarded, and abort the VM. Likely
  1921. // very rare.
  1922. //
  1923. // The other race involves two threads alternately trapping at
  1924. // different addresses and failing to unguard the page, resulting in
  1925. // an endless loop. This condition is probably even more unlikely
  1926. // than the first.
  1927. //
  1928. // Although both cases could be avoided by using locks or thread
  1929. // local last_addr, these solutions are unnecessary complication:
  1930. // this handler is a best-effort safety net, not a complete solution.
  1931. // It is disabled by default and should only be used as a workaround
  1932. // in case we missed any no-execute-unsafe VM code.
  1933. last_addr = addr;
  1934. return EXCEPTION_CONTINUE_EXECUTION;
  1935. }
  1936. }
  1937. // Last unguard failed or not unguarding
  1938. tty->print_raw_cr("Execution protection violation");
  1939. report_error(t, exception_code, addr, exceptionInfo->ExceptionRecord,
  1940. exceptionInfo->ContextRecord);
  1941. return EXCEPTION_CONTINUE_SEARCH;
  1942. }
  1943. }
  1944. #endif // _WIN64
  1945. // Check to see if we caught the safepoint code in the
  1946. // process of write protecting the memory serialization page.
  1947. // It write enables the page immediately after protecting it
  1948. // so just return.
  1949. if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) {
  1950. JavaThread* thread = (JavaThread*) t;
  1951. PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
  1952. address addr = (address) exceptionRecord->ExceptionInformation[1];
  1953. if ( os::is_memory_serialize_page(thread, addr) ) {
  1954. // Block current thread until the memory serialize page permission restored.
  1955. os::block_on_serialize_page_trap();
  1956. return EXCEPTION_CONTINUE_EXECUTION;
  1957. }
  1958. }
  1959. if (t != NULL && t->is_Java_thread()) {
  1960. JavaThread* thread = (JavaThread*) t;
  1961. bool in_java = thread->thread_state() == _thread_in_Java;
  1962. // Handle potential stack overflows up front.
  1963. if (exception_code == EXCEPTION_STACK_OVERFLOW) {
  1964. if (os::uses_stack_guard_pages()) {
  1965. #ifdef _M_IA64
  1966. //
  1967. // If it's a legal stack address continue, Windows will map it in.
  1968. //
  1969. PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
  1970. address addr = (address) exceptionRecord->ExceptionInformation[1];
  1971. if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() )
  1972. return EXCEPTION_CONTINUE_EXECUTION;
  1973. // The register save area is the same size as the memory stack
  1974. // and starts at the page just above the start of the memory stack.
  1975. // If we get a fault in this area, we've run out of register
  1976. // stack. If we are in java, try throwing a stack overflow exception.
  1977. if (addr > thread->stack_base() &&
  1978. addr <= (thread->stack_base()+thread->stack_size()) ) {
  1979. char buf[256];
  1980. jio_snprintf(buf, sizeof(buf),
  1981. "Register stack overflow, addr:%p, stack_base:%p\n",
  1982. addr, thread->stack_base() );
  1983. tty->print_raw_cr(buf);
  1984. // If not in java code, return and hope for the best.
  1985. return in_java ? Handle_Exception(exceptionInfo,
  1986. SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW))
  1987. : EXCEPTION_CONTINUE_EXECUTION;
  1988. }
  1989. #endif
  1990. if (thread->stack_yellow_zone_enabled()) {
  1991. // Yellow zone violation. The o/s has unprotected the first yellow
  1992. // zone page for us. Note: must call disable_stack_yellow_zone to
  1993. // update the enabled status, even if the zone contains only one page.
  1994. thread->disable_stack_yellow_zone();
  1995. // If not in java code, return and hope for the best.
  1996. return in_java ? Handle_Exception(exceptionInfo,
  1997. SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW))
  1998. : EXCEPTION_CONTINUE_EXECUTION;
  1999. } else {
  2000. // Fatal red zone violation.
  2001. thread->disable_stack_red_zone();
  2002. tty->print_raw_cr("An unrecoverable stack overflow has occurred.");
  2003. report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
  2004. exceptionInfo->ContextRecord);
  2005. return EXCEPTION_CONTINUE_SEARCH;
  2006. }
  2007. } else if (in_java) {
  2008. // JVM-managed guard pages cannot be used on win95/98. The o/s provides
  2009. // a one-time-only guard page, which it has released to us. The next
  2010. // stack overflow on this thread will result in an ACCESS_VIOLATION.
  2011. return Handle_Exception(exceptionInfo,
  2012. SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
  2013. } else {
  2014. // Can only return and hope for the best. Further stack growth will
  2015. // result in an ACCESS_VIOLATION.
  2016. return EXCEPTION_CONTINUE_EXECUTION;
  2017. }
  2018. } else if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
  2019. // Either stack overflow or null pointer exception.
  2020. if (in_java) {
  2021. PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
  2022. address addr = (address) exceptionRecord->ExceptionInformation[1];
  2023. address stack_end = thread->stack_base() - thread->stack_size();
  2024. if (addr < stack_end && addr >= stack_end - os::vm_page_size()) {
  2025. // Stack overflow.
  2026. assert(!os::uses_stack_guard_pages(),
  2027. "should be caught by red zone code above.");
  2028. return Handle_Exception(exceptionInfo,
  2029. SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
  2030. }
  2031. //
  2032. // Check for safepoint polling and implicit null
  2033. // We only expect null pointers in the stubs (vtable)
  2034. // the rest are checked explicitly now.
  2035. //
  2036. CodeBlob* cb = CodeCache::find_blob(pc);
  2037. if (cb != NULL) {
  2038. if (os::is_poll_address(addr)) {
  2039. address stub = SharedRuntime::get_poll_stub(pc);
  2040. return Handle_Exception(exceptionInfo, stub);
  2041. }
  2042. }
  2043. {
  2044. #ifdef _WIN64
  2045. //
  2046. // If it's a legal stack address map the entire region in
  2047. //
  2048. PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
  2049. address addr = (address) exceptionRecord->ExceptionInformation[1];
  2050. if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) {
  2051. addr = (address)((uintptr_t)addr &
  2052. (~((uintptr_t)os::vm_page_size() - (uintptr_t)1)));
  2053. os::commit_memory((char *)addr, thread->stack_base() - addr,
  2054. false );
  2055. return EXCEPTION_CONTINUE_EXECUTION;
  2056. }
  2057. else
  2058. #endif
  2059. {
  2060. // Null pointer exception.
  2061. #ifdef _M_IA64
  2062. // We catch register stack overflows in compiled code by doing
  2063. // an explicit compare and executing a st8(G0, G0) if the
  2064. // BSP enters into our guard area. We test for the overflow
  2065. // condition and fall into the normal null pointer exception
  2066. // code if BSP hasn't overflowed.
  2067. if ( in_java ) {
  2068. if(thread->register_stack_overflow()) {
  2069. assert((address)exceptionInfo->ContextRecord->IntS3 ==
  2070. thread->register_stack_limit(),
  2071. "GR7 doesn't contain register_stack_limit");
  2072. // Disable the yellow zone which sets the state that
  2073. // we've got a stack overflow problem.
  2074. if (thread->stack_yellow_zone_enabled()) {
  2075. thread->disable_stack_yellow_zone();
  2076. }
  2077. // Give us some room to process the exception
  2078. thread->disable_register_stack_guard();
  2079. // Update GR7 with the new limit so we can continue running
  2080. // compiled code.
  2081. exceptionInfo->ContextRecord->IntS3 =
  2082. (ULONGLONG)thread->register_stack_limit();
  2083. return Handle_Exception(exceptionInfo,
  2084. SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
  2085. } else {
  2086. //
  2087. // Check for implicit null
  2088. // We only expect null pointers in the stubs (vtable)
  2089. // the rest are checked explicitly now.
  2090. //
  2091. if (((uintptr_t)addr) < os::vm_page_size() ) {
  2092. // an access to the first page of VM--assume it is a null pointer
  2093. address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
  2094. if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
  2095. }
  2096. }
  2097. } // in_java
  2098. // IA64 doesn't use implicit null checking yet. So we shouldn't
  2099. // get here.
  2100. tty->print_raw_cr("Access violation, possible null pointer exception");
  2101. report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
  2102. exceptionInfo->ContextRecord);
  2103. return EXCEPTION_CONTINUE_SEARCH;
  2104. #else /* !IA64 */
  2105. // Windows 98 reports faulting addresses incorrectly
  2106. if (!MacroAssembler::needs_explicit_null_check((intptr_t)addr) ||
  2107. !os::win32::is_nt()) {
  2108. address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
  2109. if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
  2110. }
  2111. report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
  2112. exceptionInfo->ContextRecord);
  2113. return EXCEPTION_CONTINUE_SEARCH;
  2114. #endif
  2115. }
  2116. }
  2117. }
  2118. #ifdef _WIN64
  2119. // Special care for fast JNI field accessors.
  2120. // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks
  2121. // in and the heap gets shrunk before the field access.
  2122. if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
  2123. address addr = JNI_FastGetField::find_slowcase_pc(pc);
  2124. if (addr != (address)-1) {
  2125. return Handle_Exception(exceptionInfo, addr);
  2126. }
  2127. }
  2128. #endif
  2129. #ifdef _WIN64
  2130. // Windows will sometimes generate an access violation
  2131. // when we call malloc. Since we use VectoredExceptions
  2132. // on 64 bit platforms, we see this exception. We must
  2133. // pass this exception on so Windows can recover.
  2134. // We check to see if the pc of the fault is in NTDLL.DLL
  2135. // if so, we pass control on to Windows for handling.
  2136. if (UseVectoredExceptions && _addr_in_ntdll(pc)) return EXCEPTION_CONTINUE_SEARCH;
  2137. #endif
  2138. // Stack overflow or null pointer exception in native code.
  2139. report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
  2140. exceptionInfo->ContextRecord);
  2141. return EXCEPTION_CONTINUE_SEARCH;
  2142. }
  2143. if (in_java) {
  2144. switch (exception_code) {
  2145. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  2146. return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO));
  2147. case EXCEPTION_INT_OVERFLOW:
  2148. return Handle_IDiv_Exception(exceptionInfo);
  2149. } // switch
  2150. }
  2151. #ifndef _WIN64
  2152. if (((thread->thread_state() == _thread_in_Java) ||
  2153. (thread->thread_state() == _thread_in_native)) &&
  2154. exception_code != EXCEPTION_UNCAUGHT_CXX_EXCEPTION)
  2155. {
  2156. LONG result=Handle_FLT_Exception(exceptionInfo);
  2157. if (result==EXCEPTION_CONTINUE_EXECUTION) return result;
  2158. }
  2159. #endif //_WIN64
  2160. }
  2161. if (exception_code != EXCEPTION_BREAKPOINT) {
  2162. #ifndef _WIN64
  2163. report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
  2164. exceptionInfo->ContextRecord);
  2165. #else
  2166. // Itanium Windows uses a VectoredExceptionHandler
  2167. // Which means that C++ programatic exception handlers (try/except)
  2168. // will get here. Continue the search for the right except block if
  2169. // the exception code is not a fatal code.
  2170. switch ( exception_code ) {
  2171. case EXCEPTION_ACCESS_VIOLATION:
  2172. case EXCEPTION_STACK_OVERFLOW:
  2173. case EXCEPTION_ILLEGAL_INSTRUCTION:
  2174. case EXCEPTION_ILLEGAL_INSTRUCTION_2:
  2175. case EXCEPTION_INT_OVERFLOW:
  2176. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  2177. case EXCEPTION_UNCAUGHT_CXX_EXCEPTION:
  2178. { report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
  2179. exceptionInfo->ContextRecord);
  2180. }
  2181. break;
  2182. default:
  2183. break;
  2184. }
  2185. #endif
  2186. }
  2187. return EXCEPTION_CONTINUE_SEARCH;
  2188. }
  2189. #ifndef _WIN64
  2190. // Special care for fast JNI accessors.
  2191. // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and
  2192. // the heap gets shrunk before the field access.
  2193. // Need to install our own structured exception handler since native code may
  2194. // install its own.
  2195. LONG WINAPI fastJNIAccessorExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
  2196. DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
  2197. if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
  2198. address pc = (address) exceptionInfo->ContextRecord->Eip;
  2199. address addr = JNI_FastGetField::find_slowcase_pc(pc);
  2200. if (addr != (address)-1) {
  2201. return Handle_Exception(exceptionInfo, addr);
  2202. }
  2203. }
  2204. return EXCEPTION_CONTINUE_SEARCH;
  2205. }
  2206. #define DEFINE_FAST_GETFIELD(Return,Fieldname,Result) \
  2207. Return JNICALL jni_fast_Get##Result##Field_wrapper(JNIEnv *env, jobject obj, jfieldID fieldID) { \
  2208. __try { \
  2209. return (*JNI_FastGetField::jni_fast_Get##Result##Field_fp)(env, obj, fieldID); \
  2210. } __except(fastJNIAccessorExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) { \
  2211. } \
  2212. return 0; \
  2213. }
  2214. DEFINE_FAST_GETFIELD(jboolean, bool, Boolean)
  2215. DEFINE_FAST_GETFIELD(jbyte, byte, Byte)
  2216. DEFINE_FAST_GETFIELD(jchar, char, Char)
  2217. DEFINE_FAST_GETFIELD(jshort, short, Short)
  2218. DEFINE_FAST_GETFIELD(jint, int, Int)
  2219. DEFINE_FAST_GETFIELD(jlong, long, Long)
  2220. DEFINE_FAST_GETFIELD(jfloat, float, Float)
  2221. DEFINE_FAST_GETFIELD(jdouble, double, Double)
  2222. address os::win32::fast_jni_accessor_wrapper(BasicType type) {
  2223. switch (type) {
  2224. case T_BOOLEAN: return (address)jni_fast_GetBooleanField_wrapper;
  2225. case T_BYTE: return (address)jni_fast_GetByteField_wrapper;
  2226. case T_CHAR: return (address)jni_fast_GetCharField_wrapper;
  2227. case T_SHORT: return (address)jni_fast_GetShortField_wrapper;
  2228. case T_INT: return (address)jni_fast_GetIntField_wrapper;
  2229. case T_LONG: return (address)jni_fast_GetLongField_wrapper;
  2230. case T_FLOAT: return (address)jni_fast_GetFloatField_wrapper;
  2231. case T_DOUBLE: return (address)jni_fast_GetDoubleField_wrapper;
  2232. default: ShouldNotReachHere();
  2233. }
  2234. return (address)-1;
  2235. }
  2236. #endif
  2237. // Virtual Memory
  2238. int os::vm_page_size() { return os::win32::vm_page_size(); }
  2239. int os::vm_allocation_granularity() {
  2240. return os::win32::vm_allocation_granularity();
  2241. }
  2242. // Windows large page support is available on Windows 2003. In order to use
  2243. // large page memory, the administrator must first assign additional privilege
  2244. // to the user:
  2245. // + select Control Panel -> Administrative Tools -> Local Security Policy
  2246. // + select Local Policies -> User Rights Assignment
  2247. // + double click "Lock pages in memory", add users and/or groups
  2248. // + reboot
  2249. // Note the above steps are needed for administrator as well, as administrators
  2250. // by default do not have the privilege to lock pages in memory.
  2251. //
  2252. // Note about Windows 2003: although the API supports committing large page
  2253. // memory on a page-by-page basis and VirtualAlloc() returns success under this
  2254. // scenario, I found through experiment it only uses large page if the entire
  2255. // memory region is reserved and committed in a single VirtualAlloc() call.
  2256. // This makes Windows large page support more or less like Solaris ISM, in
  2257. // that the entire heap must be committed upfront. This probably will change
  2258. // in the future, if so the code below needs to be revisited.
  2259. #ifndef MEM_LARGE_PAGES
  2260. #define MEM_LARGE_PAGES 0x20000000
  2261. #endif
  2262. // GetLargePageMinimum is only available on Windows 2003. The other functions
  2263. // are available on NT but not on Windows 98/Me. We have to resolve them at
  2264. // runtime.
  2265. typedef SIZE_T (WINAPI *GetLargePageMinimum_func_type) (void);
  2266. typedef BOOL (WINAPI *AdjustTokenPrivileges_func_type)
  2267. (HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
  2268. typedef BOOL (WINAPI *OpenProcessToken_func_type) (HANDLE, DWORD, PHANDLE);
  2269. typedef BOOL (WINAPI *LookupPrivilegeValue_func_type) (LPCTSTR, LPCTSTR, PLUID);
  2270. static GetLargePageMinimum_func_type _GetLargePageMinimum;
  2271. static AdjustTokenPrivileges_func_type _AdjustTokenPrivileges;
  2272. static OpenProcessToken_func_type _OpenProcessToken;
  2273. static LookupPrivilegeValue_func_type _LookupPrivilegeValue;
  2274. static HINSTANCE _kernel32;
  2275. static HINSTANCE _advapi32;
  2276. static HANDLE _hProcess;
  2277. static HANDLE _hToken;
  2278. static size_t _large_page_size = 0;
  2279. static bool resolve_functions_for_large_page_init() {
  2280. _kernel32 = LoadLibrary("kernel32.dll");
  2281. if (_kernel32 == NULL) return false;
  2282. _GetLargePageMinimum = CAST_TO_FN_PTR(GetLargePageMinimum_func_type,
  2283. GetProcAddress(_kernel32, "GetLargePageMinimum"));
  2284. if (_GetLargePageMinimum == NULL) return false;
  2285. _advapi32 = LoadLibrary("advapi32.dll");
  2286. if (_advapi32 == NULL) return false;
  2287. _AdjustTokenPrivileges = CAST_TO_FN_PTR(AdjustTokenPrivileges_func_type,
  2288. GetProcAddress(_advapi32, "AdjustTokenPrivileges"));
  2289. _OpenProcessToken = CAST_TO_FN_PTR(OpenProcessToken_func_type,
  2290. GetProcAddress(_advapi32, "OpenProcessToken"));
  2291. _LookupPrivilegeValue = CAST_TO_FN_PTR(LookupPrivilegeValue_func_type,
  2292. GetProcAddress(_advapi32, "LookupPrivilegeValueA"));
  2293. return _AdjustTokenPrivileges != NULL &&
  2294. _OpenProcessToken != NULL &&
  2295. _LookupPrivilegeValue != NULL;
  2296. }
  2297. static bool request_lock_memory_privilege() {
  2298. _hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
  2299. os::current_process_id());
  2300. LUID luid;
  2301. if (_hProcess != NULL &&
  2302. _OpenProcessToken(_hProcess, TOKEN_ADJUST_PRIVILEGES, &_hToken) &&
  2303. _LookupPrivilegeValue(NULL, "SeLockMemoryPrivilege", &luid)) {
  2304. TOKEN_PRIVILEGES tp;
  2305. tp.PrivilegeCount = 1;
  2306. tp.Privileges[0].Luid = luid;
  2307. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2308. // AdjustTokenPrivileges() may return TRUE even when it couldn't change the
  2309. // privilege. Check GetLastError() too. See MSDN document.
  2310. if (_AdjustTokenPrivileges(_hToken, false, &tp, sizeof(tp), NULL, NULL) &&
  2311. (GetLastError() == ERROR_SUCCESS)) {
  2312. return true;
  2313. }
  2314. }
  2315. return false;
  2316. }
  2317. static void cleanup_after_large_page_init() {
  2318. _GetLargePageMinimum = NULL;
  2319. _AdjustTokenPrivileges = NULL;
  2320. _OpenProcessToken = NULL;
  2321. _LookupPrivilegeValue = NULL;
  2322. if (_kernel32) FreeLibrary(_kernel32);
  2323. _kernel32 = NULL;
  2324. if (_advapi32) FreeLibrary(_advapi32);
  2325. _advapi32 = NULL;
  2326. if (_hProcess) CloseHandle(_hProcess);
  2327. _hProcess = NULL;
  2328. if (_hToken) CloseHandle(_hToken);
  2329. _hToken = NULL;
  2330. }
  2331. bool os::large_page_init() {
  2332. if (!UseLargePages) return false;
  2333. // print a warning if any large page related flag is specified on command line
  2334. bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) ||
  2335. !FLAG_IS_DEFAULT(LargePageSizeInBytes);
  2336. bool success = false;
  2337. # define WARN(msg) if (warn_on_failure) { warning(msg); }
  2338. if (resolve_functions_for_large_page_init()) {
  2339. if (request_lock_memory_privilege()) {
  2340. size_t s = _GetLargePageMinimum();
  2341. if (s) {
  2342. #if defined(IA32) || defined(AMD64)
  2343. if (s > 4*M || LargePageSizeInBytes > 4*M) {
  2344. WARN("JVM cannot use large pages bigger than 4mb.");
  2345. } else {
  2346. #endif
  2347. if (LargePageSizeInBytes && LargePageSizeInBytes % s == 0) {
  2348. _large_page_size = LargePageSizeInBytes;
  2349. } else {
  2350. _large_page_size = s;
  2351. }
  2352. success = true;
  2353. #if defined(IA32) || defined(AMD64)
  2354. }
  2355. #endif
  2356. } else {
  2357. WARN("Large page is not supported by the processor.");
  2358. }
  2359. } else {
  2360. WARN("JVM cannot use large page memory because it does not have enough privilege to lock pages in memory.");
  2361. }
  2362. } else {
  2363. WARN("Large page is not supported by the operating system.");
  2364. }
  2365. #undef WARN
  2366. const size_t default_page_size = (size_t) vm_page_size();
  2367. if (success && _large_page_size > default_page_size) {
  2368. _page_sizes[0] = _large_page_size;
  2369. _page_sizes[1] = default_page_size;
  2370. _page_sizes[2] = 0;
  2371. }
  2372. cleanup_after_large_page_init();
  2373. return success;
  2374. }
  2375. // On win32, one cannot release just a part of reserved memory, it's an
  2376. // all or nothing deal. When we split a reservation, we must break the
  2377. // reservation into two reservations.
  2378. void os::split_reserved_memory(char *base, size_t size, size_t split,
  2379. bool realloc) {
  2380. if (size > 0) {
  2381. release_memory(base, size);
  2382. if (realloc) {
  2383. reserve_memory(split, base);
  2384. }
  2385. if (size != split) {
  2386. reserve_memory(size - split, base + split);
  2387. }
  2388. }
  2389. }
  2390. char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
  2391. assert((size_t)addr % os::vm_allocation_granularity() == 0,
  2392. "reserve alignment");
  2393. assert(bytes % os::vm_allocation_granularity() == 0, "reserve block size");
  2394. char* res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE, PAGE_READWRITE);
  2395. assert(res == NULL || addr == NULL || addr == res,
  2396. "Unexpected address from reserve.");
  2397. return res;
  2398. }
  2399. // Reserve memory at an arbitrary address, only if that area is
  2400. // available (and not reserved for something else).
  2401. char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2402. // Windows os::reserve_memory() fails of the requested address range is
  2403. // not avilable.
  2404. return reserve_memory(bytes, requested_addr);
  2405. }
  2406. size_t os::large_page_size() {
  2407. return _large_page_size;
  2408. }
  2409. bool os::can_commit_large_page_memory() {
  2410. // Windows only uses large page memory when the entire region is reserved
  2411. // and committed in a single VirtualAlloc() call. This may change in the
  2412. // future, but with Windows 2003 it's not possible to commit on demand.
  2413. return false;
  2414. }
  2415. bool os::can_execute_large_page_memory() {
  2416. return true;
  2417. }
  2418. char* os::reserve_memory_special(size_t bytes, char* addr, bool exec) {
  2419. const DWORD prot = exec ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
  2420. if (UseLargePagesIndividualAllocation) {
  2421. if (TracePageSizes && Verbose) {
  2422. tty->print_cr("Reserving large pages individually.");
  2423. }
  2424. char * p_buf;
  2425. // first reserve enough address space in advance since we want to be
  2426. // able to break a single contiguous virtual address range into multiple
  2427. // large page commits but WS2003 does not allow reserving large page space
  2428. // so we just use 4K pages for reserve, this gives us a legal contiguous
  2429. // address space. then we will deallocate that reservation, and re alloc
  2430. // using large pages
  2431. const size_t size_of_reserve = bytes + _large_page_size;
  2432. if (bytes > size_of_reserve) {
  2433. // Overflowed.
  2434. warning("Individually allocated large pages failed, "
  2435. "use -XX:-UseLargePagesIndividualAllocation to turn off");
  2436. return NULL;
  2437. }
  2438. p_buf = (char *) VirtualAlloc(addr,
  2439. size_of_reserve, // size of Reserve
  2440. MEM_RESERVE,
  2441. PAGE_READWRITE);
  2442. // If reservation failed, return NULL
  2443. if (p_buf == NULL) return NULL;
  2444. release_memory(p_buf, bytes + _large_page_size);
  2445. // round up to page boundary. If the size_of_reserve did not
  2446. // overflow and the reservation did not fail, this align up
  2447. // should not overflow.
  2448. p_buf = (char *) align_size_up((size_t)p_buf, _large_page_size);
  2449. // now go through and allocate one page at a time until all bytes are
  2450. // allocated
  2451. size_t bytes_remaining = align_size_up(bytes, _large_page_size);
  2452. // An overflow of align_size_up() would have been caught above
  2453. // in the calculation of size_of_reserve.
  2454. char * next_alloc_addr = p_buf;
  2455. #ifdef ASSERT
  2456. // Variable for the failure injection
  2457. long ran_num = os::random();
  2458. size_t fail_after = ran_num % bytes;
  2459. #endif
  2460. while (bytes_remaining) {
  2461. size_t bytes_to_rq = MIN2(bytes_remaining, _large_page_size);
  2462. // Note allocate and commit
  2463. char * p_new;
  2464. #ifdef ASSERT
  2465. bool inject_error = LargePagesIndividualAllocationInjectError &&
  2466. (bytes_remaining <= fail_after);
  2467. #else
  2468. const bool inject_error = false;
  2469. #endif
  2470. if (inject_error) {
  2471. p_new = NULL;
  2472. } else {
  2473. p_new = (char *) VirtualAlloc(next_alloc_addr,
  2474. bytes_to_rq,
  2475. MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
  2476. prot);
  2477. }
  2478. if (p_new == NULL) {
  2479. // Free any allocated pages
  2480. if (next_alloc_addr > p_buf) {
  2481. // Some memory was committed so release it.
  2482. size_t bytes_to_release = bytes - bytes_remaining;
  2483. release_memory(p_buf, bytes_to_release);
  2484. }
  2485. #ifdef ASSERT
  2486. if (UseLargePagesIndividualAllocation &&
  2487. LargePagesIndividualAllocationInjectError) {
  2488. if (TracePageSizes && Verbose) {
  2489. tty->print_cr("Reserving large pages individually failed.");
  2490. }
  2491. }
  2492. #endif
  2493. return NULL;
  2494. }
  2495. bytes_remaining -= bytes_to_rq;
  2496. next_alloc_addr += bytes_to_rq;
  2497. }
  2498. return p_buf;
  2499. } else {
  2500. // normal policy just allocate it all at once
  2501. DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES;
  2502. char * res = (char *)VirtualAlloc(NULL, bytes, flag, prot);
  2503. return res;
  2504. }
  2505. }
  2506. bool os::release_memory_special(char* base, size_t bytes) {
  2507. return release_memory(base, bytes);
  2508. }
  2509. void os::print_statistics() {
  2510. }
  2511. bool os::commit_memory(char* addr, size_t bytes, bool exec) {
  2512. if (bytes == 0) {
  2513. // Don't bother the OS with noops.
  2514. return true;
  2515. }
  2516. assert((size_t) addr % os::vm_page_size() == 0, "commit on page boundaries");
  2517. assert(bytes % os::vm_page_size() == 0, "commit in page-sized chunks");
  2518. // Don't attempt to print anything if the OS call fails. We're
  2519. // probably low on resources, so the print itself may cause crashes.
  2520. bool result = VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) != 0;
  2521. if (result != NULL && exec) {
  2522. DWORD oldprot;
  2523. // Windows doc says to use VirtualProtect to get execute permissions
  2524. return VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot) != 0;
  2525. } else {
  2526. return result;
  2527. }
  2528. }
  2529. bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
  2530. bool exec) {
  2531. return commit_memory(addr, size, exec);
  2532. }
  2533. bool os::uncommit_memory(char* addr, size_t bytes) {
  2534. if (bytes == 0) {
  2535. // Don't bother the OS with noops.
  2536. return true;
  2537. }
  2538. assert((size_t) addr % os::vm_page_size() == 0, "uncommit on page boundaries");
  2539. assert(bytes % os::vm_page_size() == 0, "uncommit in page-sized chunks");
  2540. return VirtualFree(addr, bytes, MEM_DECOMMIT) != 0;
  2541. }
  2542. bool os::release_memory(char* addr, size_t bytes) {
  2543. return VirtualFree(addr, 0, MEM_RELEASE) != 0;
  2544. }
  2545. bool os::create_stack_guard_pages(char* addr, size_t size) {
  2546. return os::commit_memory(addr, size);
  2547. }
  2548. bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2549. return os::uncommit_memory(addr, size);
  2550. }
  2551. // Set protections specified
  2552. bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  2553. bool is_committed) {
  2554. unsigned int p = 0;
  2555. switch (prot) {
  2556. case MEM_PROT_NONE: p = PAGE_NOACCESS; break;
  2557. case MEM_PROT_READ: p = PAGE_READONLY; break;
  2558. case MEM_PROT_RW: p = PAGE_READWRITE; break;
  2559. case MEM_PROT_RWX: p = PAGE_EXECUTE_READWRITE; break;
  2560. default:
  2561. ShouldNotReachHere();
  2562. }
  2563. DWORD old_status;
  2564. // Strange enough, but on Win32 one can change protection only for committed
  2565. // memory, not a big deal anyway, as bytes less or equal than 64K
  2566. if (!is_committed && !commit_memory(addr, bytes, prot == MEM_PROT_RWX)) {
  2567. fatal("cannot commit protection page");
  2568. }
  2569. // One cannot use os::guard_memory() here, as on Win32 guard page
  2570. // have different (one-shot) semantics, from MSDN on PAGE_GUARD:
  2571. //
  2572. // Pages in the region become guard pages. Any attempt to access a guard page
  2573. // causes the system to raise a STATUS_GUARD_PAGE exception and turn off
  2574. // the guard page status. Guard pages thus act as a one-time access alarm.
  2575. return VirtualProtect(addr, bytes, p, &old_status) != 0;
  2576. }
  2577. bool os::guard_memory(char* addr, size_t bytes) {
  2578. DWORD old_status;
  2579. return VirtualProtect(addr, bytes, PAGE_READWRITE | PAGE_GUARD, &old_status) != 0;
  2580. }
  2581. bool os::unguard_memory(char* addr, size_t bytes) {
  2582. DWORD old_status;
  2583. return VirtualProtect(addr, bytes, PAGE_READWRITE, &old_status) != 0;
  2584. }
  2585. void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { }
  2586. void os::free_memory(char *addr, size_t bytes) { }
  2587. void os::numa_make_global(char *addr, size_t bytes) { }
  2588. void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { }
  2589. bool os::numa_topology_changed() { return false; }
  2590. size_t os::numa_get_groups_num() { return 1; }
  2591. int os::numa_get_group_id() { return 0; }
  2592. size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2593. if (size > 0) {
  2594. ids[0] = 0;
  2595. return 1;
  2596. }
  2597. return 0;
  2598. }
  2599. bool os::get_page_info(char *start, page_info* info) {
  2600. return false;
  2601. }
  2602. char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2603. return end;
  2604. }
  2605. char* os::non_memory_address_word() {
  2606. // Must never look like an address returned by reserve_memory,
  2607. // even in its subfields (as defined by the CPU immediate fields,
  2608. // if the CPU splits constants across multiple instructions).
  2609. return (char*)-1;
  2610. }
  2611. #define MAX_ERROR_COUNT 100
  2612. #define SYS_THREAD_ERROR 0xffffffffUL
  2613. void os::pd_start_thread(Thread* thread) {
  2614. DWORD ret = ResumeThread(thread->osthread()->thread_handle());
  2615. // Returns previous suspend state:
  2616. // 0: Thread was not suspended
  2617. // 1: Thread is running now
  2618. // >1: Thread is still suspended.
  2619. assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back
  2620. }
  2621. class HighResolutionInterval {
  2622. // The default timer resolution seems to be 10 milliseconds.
  2623. // (Where is this written down?)
  2624. // If someone wants to sleep for only a fraction of the default,
  2625. // then we set the timer resolution down to 1 millisecond for
  2626. // the duration of their interval.
  2627. // We carefully set the resolution back, since otherwise we
  2628. // seem to incur an overhead (3%?) that we don't need.
  2629. // CONSIDER: if ms is small, say 3, then we should run with a high resolution time.
  2630. // Buf if ms is large, say 500, or 503, we should avoid the call to timeBeginPeriod().
  2631. // Alternatively, we could compute the relative error (503/500 = .6%) and only use
  2632. // timeBeginPeriod() if the relative error exceeded some threshold.
  2633. // timeBeginPeriod() has been linked to problems with clock drift on win32 systems and
  2634. // to decreased efficiency related to increased timer "tick" rates. We want to minimize
  2635. // (a) calls to timeBeginPeriod() and timeEndPeriod() and (b) time spent with high
  2636. // resolution timers running.
  2637. private:
  2638. jlong resolution;
  2639. public:
  2640. HighResolutionInterval(jlong ms) {
  2641. resolution = ms % 10L;
  2642. if (resolution != 0) {
  2643. MMRESULT result = timeBeginPeriod(1L);
  2644. }
  2645. }
  2646. ~HighResolutionInterval() {
  2647. if (resolution != 0) {
  2648. MMRESULT result = timeEndPeriod(1L);
  2649. }
  2650. resolution = 0L;
  2651. }
  2652. };
  2653. int os::sleep(Thread* thread, jlong ms, bool interruptable) {
  2654. jlong limit = (jlong) MAXDWORD;
  2655. while(ms > limit) {
  2656. int res;
  2657. if ((res = sleep(thread, limit, interruptable)) != OS_TIMEOUT)
  2658. return res;
  2659. ms -= limit;
  2660. }
  2661. assert(thread == Thread::current(), "thread consistency check");
  2662. OSThread* osthread = thread->osthread();
  2663. OSThreadWaitState osts(osthread, false /* not Object.wait() */);
  2664. int result;
  2665. if (interruptable) {
  2666. assert(thread->is_Java_thread(), "must be java thread");
  2667. JavaThread *jt = (JavaThread *) thread;
  2668. ThreadBlockInVM tbivm(jt);
  2669. jt->set_suspend_equivalent();
  2670. // cleared by handle_special_suspend_equivalent_condition() or
  2671. // java_suspend_self() via check_and_wait_while_suspended()
  2672. HANDLE events[1];
  2673. events[0] = osthread->interrupt_event();
  2674. HighResolutionInterval *phri=NULL;
  2675. if(!ForceTimeHighResolution)
  2676. phri = new HighResolutionInterval( ms );
  2677. if (WaitForMultipleObjects(1, events, FALSE, (DWORD)ms) == WAIT_TIMEOUT) {
  2678. result = OS_TIMEOUT;
  2679. } else {
  2680. ResetEvent(osthread->interrupt_event());
  2681. osthread->set_interrupted(false);
  2682. result = OS_INTRPT;
  2683. }
  2684. delete phri; //if it is NULL, harmless
  2685. // were we externally suspended while we were waiting?
  2686. jt->check_and_wait_while_suspended();
  2687. } else {
  2688. assert(!thread->is_Java_thread(), "must not be java thread");
  2689. Sleep((long) ms);
  2690. result = OS_TIMEOUT;
  2691. }
  2692. return result;
  2693. }
  2694. // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  2695. void os::infinite_sleep() {
  2696. while (true) { // sleep forever ...
  2697. Sleep(100000); // ... 100 seconds at a time
  2698. }
  2699. }
  2700. typedef BOOL (WINAPI * STTSignature)(void) ;
  2701. os::YieldResult os::NakedYield() {
  2702. // Use either SwitchToThread() or Sleep(0)
  2703. // Consider passing back the return value from SwitchToThread().
  2704. // We use GetProcAddress() as ancient Win9X versions of windows doen't support SwitchToThread.
  2705. // In that case we revert to Sleep(0).
  2706. static volatile STTSignature stt = (STTSignature) 1 ;
  2707. if (stt == ((STTSignature) 1)) {
  2708. stt = (STTSignature) ::GetProcAddress (LoadLibrary ("Kernel32.dll"), "SwitchToThread") ;
  2709. // It's OK if threads race during initialization as the operation above is idempotent.
  2710. }
  2711. if (stt != NULL) {
  2712. return (*stt)() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ;
  2713. } else {
  2714. Sleep (0) ;
  2715. }
  2716. return os::YIELD_UNKNOWN ;
  2717. }
  2718. void os::yield() { os::NakedYield(); }
  2719. void os::yield_all(int attempts) {
  2720. // Yields to all threads, including threads with lower priorities
  2721. Sleep(1);
  2722. }
  2723. // Win32 only gives you access to seven real priorities at a time,
  2724. // so we compress Java's ten down to seven. It would be better
  2725. // if we dynamically adjusted relative priorities.
  2726. int os::java_to_os_priority[MaxPriority + 1] = {
  2727. THREAD_PRIORITY_IDLE, // 0 Entry should never be used
  2728. THREAD_PRIORITY_LOWEST, // 1 MinPriority
  2729. THREAD_PRIORITY_LOWEST, // 2
  2730. THREAD_PRIORITY_BELOW_NORMAL, // 3
  2731. THREAD_PRIORITY_BELOW_NORMAL, // 4
  2732. THREAD_PRIORITY_NORMAL, // 5 NormPriority
  2733. THREAD_PRIORITY_NORMAL, // 6
  2734. THREAD_PRIORITY_ABOVE_NORMAL, // 7
  2735. THREAD_PRIORITY_ABOVE_NORMAL, // 8
  2736. THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority
  2737. THREAD_PRIORITY_HIGHEST // 10 MaxPriority
  2738. };
  2739. int prio_policy1[MaxPriority + 1] = {
  2740. THREAD_PRIORITY_IDLE, // 0 Entry should never be used
  2741. THREAD_PRIORITY_LOWEST, // 1 MinPriority
  2742. THREAD_PRIORITY_LOWEST, // 2
  2743. THREAD_PRIORITY_BELOW_NORMAL, // 3
  2744. THREAD_PRIORITY_BELOW_NORMAL, // 4
  2745. THREAD_PRIORITY_NORMAL, // 5 NormPriority
  2746. THREAD_PRIORITY_ABOVE_NORMAL, // 6
  2747. THREAD_PRIORITY_ABOVE_NORMAL, // 7
  2748. THREAD_PRIORITY_HIGHEST, // 8
  2749. THREAD_PRIORITY_HIGHEST, // 9 NearMaxPriority
  2750. THREAD_PRIORITY_TIME_CRITICAL // 10 MaxPriority
  2751. };
  2752. static int prio_init() {
  2753. // If ThreadPriorityPolicy is 1, switch tables
  2754. if (ThreadPriorityPolicy == 1) {
  2755. int i;
  2756. for (i = 0; i < MaxPriority + 1; i++) {
  2757. os::java_to_os_priority[i] = prio_policy1[i];
  2758. }
  2759. }
  2760. return 0;
  2761. }
  2762. OSReturn os::set_native_priority(Thread* thread, int priority) {
  2763. if (!UseThreadPriorities) return OS_OK;
  2764. bool ret = SetThreadPriority(thread->osthread()->thread_handle(), priority) != 0;
  2765. return ret ? OS_OK : OS_ERR;
  2766. }
  2767. OSReturn os::get_native_priority(const Thread* const thread, int* priority_ptr) {
  2768. if ( !UseThreadPriorities ) {
  2769. *priority_ptr = java_to_os_priority[NormPriority];
  2770. return OS_OK;
  2771. }
  2772. int os_prio = GetThreadPriority(thread->osthread()->thread_handle());
  2773. if (os_prio == THREAD_PRIORITY_ERROR_RETURN) {
  2774. assert(false, "GetThreadPriority failed");
  2775. return OS_ERR;
  2776. }
  2777. *priority_ptr = os_prio;
  2778. return OS_OK;
  2779. }
  2780. // Hint to the underlying OS that a task switch would not be good.
  2781. // Void return because it's a hint and can fail.
  2782. void os::hint_no_preempt() {}
  2783. void os::interrupt(Thread* thread) {
  2784. assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
  2785. "possibility of dangling Thread pointer");
  2786. OSThread* osthread = thread->osthread();
  2787. osthread->set_interrupted(true);
  2788. // More than one thread can get here with the same value of osthread,
  2789. // resulting in multiple notifications. We do, however, want the store
  2790. // to interrupted() to be visible to other threads before we post
  2791. // the interrupt event.
  2792. OrderAccess::release();
  2793. SetEvent(osthread->interrupt_event());
  2794. // For JSR166: unpark after setting status
  2795. if (thread->is_Java_thread())
  2796. ((JavaThread*)thread)->parker()->unpark();
  2797. ParkEvent * ev = thread->_ParkEvent ;
  2798. if (ev != NULL) ev->unpark() ;
  2799. }
  2800. bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  2801. assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
  2802. "possibility of dangling Thread pointer");
  2803. OSThread* osthread = thread->osthread();
  2804. bool interrupted;
  2805. interrupted = osthread->interrupted();
  2806. if (clear_interrupted == true) {
  2807. osthread->set_interrupted(false);
  2808. ResetEvent(osthread->interrupt_event());
  2809. } // Otherwise leave the interrupted state alone
  2810. return interrupted;
  2811. }
  2812. // Get's a pc (hint) for a running thread. Currently used only for profiling.
  2813. ExtendedPC os::get_thread_pc(Thread* thread) {
  2814. CONTEXT context;
  2815. context.ContextFlags = CONTEXT_CONTROL;
  2816. HANDLE handle = thread->osthread()->thread_handle();
  2817. #ifdef _M_IA64
  2818. assert(0, "Fix get_thread_pc");
  2819. return ExtendedPC(NULL);
  2820. #else
  2821. if (GetThreadContext(handle, &context)) {
  2822. #ifdef _M_AMD64
  2823. return ExtendedPC((address) context.Rip);
  2824. #else
  2825. return ExtendedPC((address) context.Eip);
  2826. #endif
  2827. } else {
  2828. return ExtendedPC(NULL);
  2829. }
  2830. #endif
  2831. }
  2832. // GetCurrentThreadId() returns DWORD
  2833. intx os::current_thread_id() { return GetCurrentThreadId(); }
  2834. static int _initial_pid = 0;
  2835. int os::current_process_id()
  2836. {
  2837. return (_initial_pid ? _initial_pid : _getpid());
  2838. }
  2839. int os::win32::_vm_page_size = 0;
  2840. int os::win32::_vm_allocation_granularity = 0;
  2841. int os::win32::_processor_type = 0;
  2842. // Processor level is not available on non-NT systems, use vm_version instead
  2843. int os::win32::_processor_level = 0;
  2844. julong os::win32::_physical_memory = 0;
  2845. size_t os::win32::_default_stack_size = 0;
  2846. intx os::win32::_os_thread_limit = 0;
  2847. volatile intx os::win32::_os_thread_count = 0;
  2848. bool os::win32::_is_nt = false;
  2849. bool os::win32::_is_windows_2003 = false;
  2850. void os::win32::initialize_system_info() {
  2851. SYSTEM_INFO si;
  2852. GetSystemInfo(&si);
  2853. _vm_page_size = si.dwPageSize;
  2854. _vm_allocation_granularity = si.dwAllocationGranularity;
  2855. _processor_type = si.dwProcessorType;
  2856. _processor_level = si.wProcessorLevel;
  2857. set_processor_count(si.dwNumberOfProcessors);
  2858. MEMORYSTATUSEX ms;
  2859. ms.dwLength = sizeof(ms);
  2860. // also returns dwAvailPhys (free physical memory bytes), dwTotalVirtual, dwAvailVirtual,
  2861. // dwMemoryLoad (% of memory in use)
  2862. GlobalMemoryStatusEx(&ms);
  2863. _physical_memory = ms.ullTotalPhys;
  2864. OSVERSIONINFO oi;
  2865. oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  2866. GetVersionEx(&oi);
  2867. switch(oi.dwPlatformId) {
  2868. case VER_PLATFORM_WIN32_WINDOWS: _is_nt = false; break;
  2869. case VER_PLATFORM_WIN32_NT:
  2870. _is_nt = true;
  2871. {
  2872. int os_vers = oi.dwMajorVersion * 1000 + oi.dwMinorVersion;
  2873. if (os_vers == 5002) {
  2874. _is_windows_2003 = true;
  2875. }
  2876. }
  2877. break;
  2878. default: fatal("Unknown platform");
  2879. }
  2880. _default_stack_size = os::current_stack_size();
  2881. assert(_default_stack_size > (size_t) _vm_page_size, "invalid stack size");
  2882. assert((_default_stack_size & (_vm_page_size - 1)) == 0,
  2883. "stack size not a multiple of page size");
  2884. initialize_performance_counter();
  2885. // Win95/Win98 scheduler bug work-around. The Win95/98 scheduler is
  2886. // known to deadlock the system, if the VM issues to thread operations with
  2887. // a too high frequency, e.g., such as changing the priorities.
  2888. // The 6000 seems to work well - no deadlocks has been notices on the test
  2889. // programs that we have seen experience this problem.
  2890. if (!os::win32::is_nt()) {
  2891. StarvationMonitorInterval = 6000;
  2892. }
  2893. }
  2894. void os::win32::setmode_streams() {
  2895. _setmode(_fileno(stdin), _O_BINARY);
  2896. _setmode(_fileno(stdout), _O_BINARY);
  2897. _setmode(_fileno(stderr), _O_BINARY);
  2898. }
  2899. int os::message_box(const char* title, const char* message) {
  2900. int result = MessageBox(NULL, message, title,
  2901. MB_YESNO | MB_ICONERROR | MB_SYSTEMMODAL | MB_DEFAULT_DESKTOP_ONLY);
  2902. return result == IDYES;
  2903. }
  2904. int os::allocate_thread_local_storage() {
  2905. return TlsAlloc();
  2906. }
  2907. void os::free_thread_local_storage(int index) {
  2908. TlsFree(index);
  2909. }
  2910. void os::thread_local_storage_at_put(int index, void* value) {
  2911. TlsSetValue(index, value);
  2912. assert(thread_local_storage_at(index) == value, "Just checking");
  2913. }
  2914. void* os::thread_local_storage_at(int index) {
  2915. return TlsGetValue(index);
  2916. }
  2917. #ifndef PRODUCT
  2918. #ifndef _WIN64
  2919. // Helpers to check whether NX protection is enabled
  2920. int nx_exception_filter(_EXCEPTION_POINTERS *pex) {
  2921. if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
  2922. pex->ExceptionRecord->NumberParameters > 0 &&
  2923. pex->ExceptionRecord->ExceptionInformation[0] ==
  2924. EXCEPTION_INFO_EXEC_VIOLATION) {
  2925. return EXCEPTION_EXECUTE_HANDLER;
  2926. }
  2927. return EXCEPTION_CONTINUE_SEARCH;
  2928. }
  2929. void nx_check_protection() {
  2930. // If NX is enabled we'll get an exception calling into code on the stack
  2931. char code[] = { (char)0xC3 }; // ret
  2932. void *code_ptr = (void *)code;
  2933. __try {
  2934. __asm call code_ptr
  2935. } __except(nx_exception_filter((_EXCEPTION_POINTERS*)_exception_info())) {
  2936. tty->print_raw_cr("NX protection detected.");
  2937. }
  2938. }
  2939. #endif // _WIN64
  2940. #endif // PRODUCT
  2941. // this is called _before_ the global arguments have been parsed
  2942. void os::init(void) {
  2943. _initial_pid = _getpid();
  2944. init_random(1234567);
  2945. win32::initialize_system_info();
  2946. win32::setmode_streams();
  2947. init_page_sizes((size_t) win32::vm_page_size());
  2948. // For better scalability on MP systems (must be called after initialize_system_info)
  2949. #ifndef PRODUCT
  2950. if (is_MP()) {
  2951. NoYieldsInMicrolock = true;
  2952. }
  2953. #endif
  2954. // This may be overridden later when argument processing is done.
  2955. FLAG_SET_ERGO(bool, UseLargePagesIndividualAllocation,
  2956. os::win32::is_windows_2003());
  2957. // Initialize main_process and main_thread
  2958. main_process = GetCurrentProcess(); // Remember main_process is a pseudo handle
  2959. if (!DuplicateHandle(main_process, GetCurrentThread(), main_process,
  2960. &main_thread, THREAD_ALL_ACCESS, false, 0)) {
  2961. fatal("DuplicateHandle failed\n");
  2962. }
  2963. main_thread_id = (int) GetCurrentThreadId();
  2964. }
  2965. // To install functions for atexit processing
  2966. extern "C" {
  2967. static void perfMemory_exit_helper() {
  2968. perfMemory_exit();
  2969. }
  2970. }
  2971. // this is called _after_ the global arguments have been parsed
  2972. jint os::init_2(void) {
  2973. // Allocate a single page and mark it as readable for safepoint polling
  2974. address polling_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READONLY);
  2975. guarantee( polling_page != NULL, "Reserve Failed for polling page");
  2976. address return_page = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY);
  2977. guarantee( return_page != NULL, "Commit Failed for polling page");
  2978. os::set_polling_page( polling_page );
  2979. #ifndef PRODUCT
  2980. if( Verbose && PrintMiscellaneous )
  2981. tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  2982. #endif
  2983. if (!UseMembar) {
  2984. address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE);
  2985. guarantee( mem_serialize_page != NULL, "Reserve Failed for memory serialize page");
  2986. return_page = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE);
  2987. guarantee( return_page != NULL, "Commit Failed for memory serialize page");
  2988. os::set_memory_serialize_page( mem_serialize_page );
  2989. #ifndef PRODUCT
  2990. if(Verbose && PrintMiscellaneous)
  2991. tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  2992. #endif
  2993. }
  2994. FLAG_SET_DEFAULT(UseLargePages, os::large_page_init());
  2995. // Setup Windows Exceptions
  2996. // On Itanium systems, Structured Exception Handling does not
  2997. // work since stack frames must be walkable by the OS. Since
  2998. // much of our code is dynamically generated, and we do not have
  2999. // proper unwind .xdata sections, the system simply exits
  3000. // rather than delivering the exception. To work around
  3001. // this we use VectorExceptions instead.
  3002. #ifdef _WIN64
  3003. if (UseVectoredExceptions) {
  3004. topLevelVectoredExceptionHandler = AddVectoredExceptionHandler( 1, topLevelExceptionFilter);
  3005. }
  3006. #endif
  3007. // for debugging float code generation bugs
  3008. if (ForceFloatExceptions) {
  3009. #ifndef _WIN64
  3010. static long fp_control_word = 0;
  3011. __asm { fstcw fp_control_word }
  3012. // see Intel PPro Manual, Vol. 2, p 7-16
  3013. const long precision = 0x20;
  3014. const long underflow = 0x10;
  3015. const long overflow = 0x08;
  3016. const long zero_div = 0x04;
  3017. const long denorm = 0x02;
  3018. const long invalid = 0x01;
  3019. fp_control_word |= invalid;
  3020. __asm { fldcw fp_control_word }
  3021. #endif
  3022. }
  3023. // If stack_commit_size is 0, windows will reserve the default size,
  3024. // but only commit a small portion of it.
  3025. size_t stack_commit_size = round_to(ThreadStackSize*K, os::vm_page_size());
  3026. size_t default_reserve_size = os::win32::default_stack_size();
  3027. size_t actual_reserve_size = stack_commit_size;
  3028. if (stack_commit_size < default_reserve_size) {
  3029. // If stack_commit_size == 0, we want this too
  3030. actual_reserve_size = default_reserve_size;
  3031. }
  3032. // Check minimum allowable stack size for thread creation and to initialize
  3033. // the java system classes, including StackOverflowError - depends on page
  3034. // size. Add a page for compiler2 recursion in main thread.
  3035. // Add in 2*BytesPerWord times page size to account for VM stack during
  3036. // class initialization depending on 32 or 64 bit VM.
  3037. size_t min_stack_allowed =
  3038. (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3039. 2*BytesPerWord COMPILER2_PRESENT(+1)) * os::vm_page_size();
  3040. if (actual_reserve_size < min_stack_allowed) {
  3041. tty->print_cr("\nThe stack size specified is too small, "
  3042. "Specify at least %dk",
  3043. min_stack_allowed / K);
  3044. return JNI_ERR;
  3045. }
  3046. JavaThread::set_stack_size_at_create(stack_commit_size);
  3047. // Calculate theoretical max. size of Threads to guard gainst artifical
  3048. // out-of-memory situations, where all available address-space has been
  3049. // reserved by thread stacks.
  3050. assert(actual_reserve_size != 0, "Must have a stack");
  3051. // Calculate the thread limit when we should start doing Virtual Memory
  3052. // banging. Currently when the threads will have used all but 200Mb of space.
  3053. //
  3054. // TODO: consider performing a similar calculation for commit size instead
  3055. // as reserve size, since on a 64-bit platform we'll run into that more
  3056. // often than running out of virtual memory space. We can use the
  3057. // lower value of the two calculations as the os_thread_limit.
  3058. size_t max_address_space = ((size_t)1 << (BitsPerWord - 1)) - (200 * K * K);
  3059. win32::_os_thread_limit = (intx)(max_address_space / actual_reserve_size);
  3060. // at exit methods are called in the reverse order of their registration.
  3061. // there is no limit to the number of functions registered. atexit does
  3062. // not set errno.
  3063. if (PerfAllowAtExitRegistration) {
  3064. // only register atexit functions if PerfAllowAtExitRegistration is set.
  3065. // atexit functions can be delayed until process exit time, which
  3066. // can be problematic for embedded VM situations. Embedded VMs should
  3067. // call DestroyJavaVM() to assure that VM resources are released.
  3068. // note: perfMemory_exit_helper atexit function may be removed in
  3069. // the future if the appropriate cleanup code can be added to the
  3070. // VM_Exit VMOperation's doit method.
  3071. if (atexit(perfMemory_exit_helper) != 0) {
  3072. warning("os::init_2 atexit(perfMemory_exit_helper) failed");
  3073. }
  3074. }
  3075. // initialize PSAPI or ToolHelp for fatal error handler
  3076. if (win32::is_nt()) _init_psapi();
  3077. else _init_toolhelp();
  3078. #ifndef _WIN64
  3079. // Print something if NX is enabled (win32 on AMD64)
  3080. NOT_PRODUCT(if (PrintMiscellaneous && Verbose) nx_check_protection());
  3081. #endif
  3082. // initialize thread priority policy
  3083. prio_init();
  3084. if (UseNUMA && !ForceNUMA) {
  3085. UseNUMA = false; // Currently unsupported.
  3086. }
  3087. return JNI_OK;
  3088. }
  3089. void os::init_3(void) {
  3090. return;
  3091. }
  3092. // Mark the polling page as unreadable
  3093. void os::make_polling_page_unreadable(void) {
  3094. DWORD old_status;
  3095. if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_NOACCESS, &old_status) )
  3096. fatal("Could not disable polling page");
  3097. };
  3098. // Mark the polling page as readable
  3099. void os::make_polling_page_readable(void) {
  3100. DWORD old_status;
  3101. if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_READONLY, &old_status) )
  3102. fatal("Could not enable polling page");
  3103. };
  3104. int os::stat(const char *path, struct stat *sbuf) {
  3105. char pathbuf[MAX_PATH];
  3106. if (strlen(path) > MAX_PATH - 1) {
  3107. errno = ENAMETOOLONG;
  3108. return -1;
  3109. }
  3110. os::native_path(strcpy(pathbuf, path));
  3111. int ret = ::stat(pathbuf, sbuf);
  3112. if (sbuf != NULL && UseUTCFileTimestamp) {
  3113. // Fix for 6539723. st_mtime returned from stat() is dependent on
  3114. // the system timezone and so can return different values for the
  3115. // same file if/when daylight savings time changes. This adjustment
  3116. // makes sure the same timestamp is returned regardless of the TZ.
  3117. //
  3118. // See:
  3119. // http://msdn.microsoft.com/library/
  3120. // default.asp?url=/library/en-us/sysinfo/base/
  3121. // time_zone_information_str.asp
  3122. // and
  3123. // http://msdn.microsoft.com/library/default.asp?url=
  3124. // /library/en-us/sysinfo/base/settimezoneinformation.asp
  3125. //
  3126. // NOTE: there is a insidious bug here: If the timezone is changed
  3127. // after the call to stat() but before 'GetTimeZoneInformation()', then
  3128. // the adjustment we do here will be wrong and we'll return the wrong
  3129. // value (which will likely end up creating an invalid class data
  3130. // archive). Absent a better API for this, or some time zone locking
  3131. // mechanism, we'll have to live with this risk.
  3132. TIME_ZONE_INFORMATION tz;
  3133. DWORD tzid = GetTimeZoneInformation(&tz);
  3134. int daylightBias =
  3135. (tzid == TIME_ZONE_ID_DAYLIGHT) ? tz.DaylightBias : tz.StandardBias;
  3136. sbuf->st_mtime += (tz.Bias + daylightBias) * 60;
  3137. }
  3138. return ret;
  3139. }
  3140. #define FT2INT64(ft) \
  3141. ((jlong)((jlong)(ft).dwHighDateTime << 32 | (julong)(ft).dwLowDateTime))
  3142. // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  3143. // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  3144. // of a thread.
  3145. //
  3146. // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
  3147. // the fast estimate available on the platform.
  3148. // current_thread_cpu_time() is not optimized for Windows yet
  3149. jlong os::current_thread_cpu_time() {
  3150. // return user + sys since the cost is the same
  3151. return os::thread_cpu_time(Thread::current(), true /* user+sys */);
  3152. }
  3153. jlong os::thread_cpu_time(Thread* thread) {
  3154. // consistent with what current_thread_cpu_time() returns.
  3155. return os::thread_cpu_time(thread, true /* user+sys */);
  3156. }
  3157. jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  3158. return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  3159. }
  3160. jlong os::thread_cpu_time(Thread* thread, bool user_sys_cpu_time) {
  3161. // This code is copy from clasic VM -> hpi::sysThreadCPUTime
  3162. // If this function changes, os::is_thread_cpu_time_supported() should too
  3163. if (os::win32::is_nt()) {
  3164. FILETIME CreationTime;
  3165. FILETIME ExitTime;
  3166. FILETIME KernelTime;
  3167. FILETIME UserTime;
  3168. if ( GetThreadTimes(thread->osthread()->thread_handle(),
  3169. &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0)
  3170. return -1;
  3171. else
  3172. if (user_sys_cpu_time) {
  3173. return (FT2INT64(UserTime) + FT2INT64(KernelTime)) * 100;
  3174. } else {
  3175. return FT2INT64(UserTime) * 100;
  3176. }
  3177. } else {
  3178. return (jlong) timeGetTime() * 1000000;
  3179. }
  3180. }
  3181. void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  3182. info_ptr->max_value = ALL_64_BITS; // the max value -- all 64 bits
  3183. info_ptr->may_skip_backward = false; // GetThreadTimes returns absolute time
  3184. info_ptr->may_skip_forward = false; // GetThreadTimes returns absolute time
  3185. info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
  3186. }
  3187. void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  3188. info_ptr->max_value = ALL_64_BITS; // the max value -- all 64 bits
  3189. info_ptr->may_skip_backward = false; // GetThreadTimes returns absolute time
  3190. info_ptr->may_skip_forward = false; // GetThreadTimes returns absolute time
  3191. info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
  3192. }
  3193. bool os::is_thread_cpu_time_supported() {
  3194. // see os::thread_cpu_time
  3195. if (os::win32::is_nt()) {
  3196. FILETIME CreationTime;
  3197. FILETIME ExitTime;
  3198. FILETIME KernelTime;
  3199. FILETIME UserTime;
  3200. if ( GetThreadTimes(GetCurrentThread(),
  3201. &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0)
  3202. return false;
  3203. else
  3204. return true;
  3205. } else {
  3206. return false;
  3207. }
  3208. }
  3209. // Windows does't provide a loadavg primitive so this is stubbed out for now.
  3210. // It does have primitives (PDH API) to get CPU usage and run queue length.
  3211. // "\\Processor(_Total)\\% Processor Time", "\\System\\Processor Queue Length"
  3212. // If we wanted to implement loadavg on Windows, we have a few options:
  3213. //
  3214. // a) Query CPU usage and run queue length and "fake" an answer by
  3215. // returning the CPU usage if it's under 100%, and the run queue
  3216. // length otherwise. It turns out that querying is pretty slow
  3217. // on Windows, on the order of 200 microseconds on a fast machine.
  3218. // Note that on the Windows the CPU usage value is the % usage
  3219. // since the last time the API was called (and the first call
  3220. // returns 100%), so we'd have to deal with that as well.
  3221. //
  3222. // b) Sample the "fake" answer using a sampling thread and store
  3223. // the answer in a global variable. The call to loadavg would
  3224. // just return the value of the global, avoiding the slow query.
  3225. //
  3226. // c) Sample a better answer using exponential decay to smooth the
  3227. // value. This is basically the algorithm used by UNIX kernels.
  3228. //
  3229. // Note that sampling thread starvation could affect both (b) and (c).
  3230. int os::loadavg(double loadavg[], int nelem) {
  3231. return -1;
  3232. }
  3233. // DontYieldALot=false by default: dutifully perform all yields as requested by JVM_Yield()
  3234. bool os::dont_yield() {
  3235. return DontYieldALot;
  3236. }
  3237. // This method is a slightly reworked copy of JDK's sysOpen
  3238. // from src/windows/hpi/src/sys_api_md.c
  3239. int os::open(const char *path, int oflag, int mode) {
  3240. char pathbuf[MAX_PATH];
  3241. if (strlen(path) > MAX_PATH - 1) {
  3242. errno = ENAMETOOLONG;
  3243. return -1;
  3244. }
  3245. os::native_path(strcpy(pathbuf, path));
  3246. return ::open(pathbuf, oflag | O_BINARY | O_NOINHERIT, mode);
  3247. }
  3248. // Is a (classpath) directory empty?
  3249. bool os::dir_is_empty(const char* path) {
  3250. WIN32_FIND_DATA fd;
  3251. HANDLE f = FindFirstFile(path, &fd);
  3252. if (f == INVALID_HANDLE_VALUE) {
  3253. return true;
  3254. }
  3255. FindClose(f);
  3256. return false;
  3257. }
  3258. // create binary file, rewriting existing file if required
  3259. int os::create_binary_file(const char* path, bool rewrite_existing) {
  3260. int oflags = _O_CREAT | _O_WRONLY | _O_BINARY;
  3261. if (!rewrite_existing) {
  3262. oflags |= _O_EXCL;
  3263. }
  3264. return ::open(path, oflags, _S_IREAD | _S_IWRITE);
  3265. }
  3266. // return current position of file pointer
  3267. jlong os::current_file_offset(int fd) {
  3268. return (jlong)::_lseeki64(fd, (__int64)0L, SEEK_CUR);
  3269. }
  3270. // move file pointer to the specified offset
  3271. jlong os::seek_to_file_offset(int fd, jlong offset) {
  3272. return (jlong)::_lseeki64(fd, (__int64)offset, SEEK_SET);
  3273. }
  3274. jlong os::lseek(int fd, jlong offset, int whence) {
  3275. return (jlong) ::_lseeki64(fd, offset, whence);
  3276. }
  3277. // This method is a slightly reworked copy of JDK's sysNativePath
  3278. // from src/windows/hpi/src/path_md.c
  3279. /* Convert a pathname to native format. On win32, this involves forcing all
  3280. separators to be '\\' rather than '/' (both are legal inputs, but Win95
  3281. sometimes rejects '/') and removing redundant separators. The input path is
  3282. assumed to have been converted into the character encoding used by the local
  3283. system. Because this might be a double-byte encoding, care is taken to
  3284. treat double-byte lead characters correctly.
  3285. This procedure modifies the given path in place, as the result is never
  3286. longer than the original. There is no error return; this operation always
  3287. succeeds. */
  3288. char * os::native_path(char *path) {
  3289. char *src = path, *dst = path, *end = path;
  3290. char *colon = NULL; /* If a drive specifier is found, this will
  3291. point to the colon following the drive
  3292. letter */
  3293. /* Assumption: '/', '\\', ':', and drive letters are never lead bytes */
  3294. assert(((!::IsDBCSLeadByte('/'))
  3295. && (!::IsDBCSLeadByte('\\'))
  3296. && (!::IsDBCSLeadByte(':'))),
  3297. "Illegal lead byte");
  3298. /* Check for leading separators */
  3299. #define isfilesep(c) ((c) == '/' || (c) == '\\')
  3300. while (isfilesep(*src)) {
  3301. src++;
  3302. }
  3303. if (::isalpha(*src) && !::IsDBCSLeadByte(*src) && src[1] == ':') {
  3304. /* Remove leading separators if followed by drive specifier. This
  3305. hack is necessary to support file URLs containing drive
  3306. specifiers (e.g., "file://c:/path"). As a side effect,
  3307. "/c:/path" can be used as an alternative to "c:/path". */
  3308. *dst++ = *src++;
  3309. colon = dst;
  3310. *dst++ = ':';
  3311. src++;
  3312. } else {
  3313. src = path;
  3314. if (isfilesep(src[0]) && isfilesep(src[1])) {
  3315. /* UNC pathname: Retain first separator; leave src pointed at
  3316. second separator so that further separators will be collapsed
  3317. into the second separator. The result will be a pathname
  3318. beginning with "\\\\" followed (most likely) by a host name. */
  3319. src = dst = path + 1;
  3320. path[0] = '\\'; /* Force first separator to '\\' */
  3321. }
  3322. }
  3323. end = dst;
  3324. /* Remove redundant separators from remainder of path, forcing all
  3325. separators to be '\\' rather than '/'. Also, single byte space
  3326. characters are removed from the end of the path because those
  3327. are not legal ending characters on this operating system.
  3328. */
  3329. while (*src != '\0') {
  3330. if (isfilesep(*src)) {
  3331. *dst++ = '\\'; src++;
  3332. while (isfilesep(*src)) src++;
  3333. if (*src == '\0') {
  3334. /* Check for trailing separator */
  3335. end = dst;
  3336. if (colon == dst - 2) break; /* "z:\\" */
  3337. if (dst == path + 1) break; /* "\\" */
  3338. if (dst == path + 2 && isfilesep(path[0])) {
  3339. /* "\\\\" is not collapsed to "\\" because "\\\\" marks the
  3340. beginning of a UNC pathname. Even though it is not, by
  3341. itself, a valid UNC pathname, we leave it as is in order
  3342. to be consistent with the path canonicalizer as well
  3343. as the win32 APIs, which treat this case as an invalid
  3344. UNC pathname rather than as an alias for the root
  3345. directory of the current drive. */
  3346. break;
  3347. }
  3348. end = --dst; /* Path does not denote a root directory, so
  3349. remove trailing separator */
  3350. break;
  3351. }
  3352. end = dst;
  3353. } else {
  3354. if (::IsDBCSLeadByte(*src)) { /* Copy a double-byte character */
  3355. *dst++ = *src++;
  3356. if (*src) *dst++ = *src++;
  3357. end = dst;
  3358. } else { /* Copy a single-byte character */
  3359. char c = *src++;
  3360. *dst++ = c;
  3361. /* Space is not a legal ending character */
  3362. if (c != ' ') end = dst;
  3363. }
  3364. }
  3365. }
  3366. *end = '\0';
  3367. /* For "z:", add "." to work around a bug in the C runtime library */
  3368. if (colon == dst - 1) {
  3369. path[2] = '.';
  3370. path[3] = '\0';
  3371. }
  3372. #ifdef DEBUG
  3373. jio_fprintf(stderr, "sysNativePath: %s\n", path);
  3374. #endif DEBUG
  3375. return path;
  3376. }
  3377. // This code is a copy of JDK's sysSetLength
  3378. // from src/windows/hpi/src/sys_api_md.c
  3379. int os::ftruncate(int fd, jlong length) {
  3380. HANDLE h = (HANDLE)::_get_osfhandle(fd);
  3381. long high = (long)(length >> 32);
  3382. DWORD ret;
  3383. if (h == (HANDLE)(-1)) {
  3384. return -1;
  3385. }
  3386. ret = ::SetFilePointer(h, (long)(length), &high, FILE_BEGIN);
  3387. if ((ret == 0xFFFFFFFF) && (::GetLastError() != NO_ERROR)) {
  3388. return -1;
  3389. }
  3390. if (::SetEndOfFile(h) == FALSE) {
  3391. return -1;
  3392. }
  3393. return 0;
  3394. }
  3395. // This code is a copy of JDK's sysSync
  3396. // from src/windows/hpi/src/sys_api_md.c
  3397. // except for the legacy workaround for a bug in Win 98
  3398. int os::fsync(int fd) {
  3399. HANDLE handle = (HANDLE)::_get_osfhandle(fd);
  3400. if ( (!::FlushFileBuffers(handle)) &&
  3401. (GetLastError() != ERROR_ACCESS_DENIED) ) {
  3402. /* from winerror.h */
  3403. return -1;
  3404. }
  3405. return 0;
  3406. }
  3407. static int nonSeekAvailable(int, long *);
  3408. static int stdinAvailable(int, long *);
  3409. #define S_ISCHR(mode) (((mode) & _S_IFCHR) == _S_IFCHR)
  3410. #define S_ISFIFO(mode) (((mode) & _S_IFIFO) == _S_IFIFO)
  3411. // This code is a copy of JDK's sysAvailable
  3412. // from src/windows/hpi/src/sys_api_md.c
  3413. int os::available(int fd, jlong *bytes) {
  3414. jlong cur, end;
  3415. struct _stati64 stbuf64;
  3416. if (::_fstati64(fd, &stbuf64) >= 0) {
  3417. int mode = stbuf64.st_mode;
  3418. if (S_ISCHR(mode) || S_ISFIFO(mode)) {
  3419. int ret;
  3420. long lpbytes;
  3421. if (fd == 0) {
  3422. ret = stdinAvailable(fd, &lpbytes);
  3423. } else {
  3424. ret = nonSeekAvailable(fd, &lpbytes);
  3425. }
  3426. (*bytes) = (jlong)(lpbytes);
  3427. return ret;
  3428. }
  3429. if ((cur = ::_lseeki64(fd, 0L, SEEK_CUR)) == -1) {
  3430. return FALSE;
  3431. } else if ((end = ::_lseeki64(fd, 0L, SEEK_END)) == -1) {
  3432. return FALSE;
  3433. } else if (::_lseeki64(fd, cur, SEEK_SET) == -1) {
  3434. return FALSE;
  3435. }
  3436. *bytes = end - cur;
  3437. return TRUE;
  3438. } else {
  3439. return FALSE;
  3440. }
  3441. }
  3442. // This code is a copy of JDK's nonSeekAvailable
  3443. // from src/windows/hpi/src/sys_api_md.c
  3444. static int nonSeekAvailable(int fd, long *pbytes) {
  3445. /* This is used for available on non-seekable devices
  3446. * (like both named and anonymous pipes, such as pipes
  3447. * connected to an exec'd process).
  3448. * Standard Input is a special case.
  3449. *
  3450. */
  3451. HANDLE han;
  3452. if ((han = (HANDLE) ::_get_osfhandle(fd)) == (HANDLE)(-1)) {
  3453. return FALSE;
  3454. }
  3455. if (! ::PeekNamedPipe(han, NULL, 0, NULL, (LPDWORD)pbytes, NULL)) {
  3456. /* PeekNamedPipe fails when at EOF. In that case we
  3457. * simply make *pbytes = 0 which is consistent with the
  3458. * behavior we get on Solaris when an fd is at EOF.
  3459. * The only alternative is to raise an Exception,
  3460. * which isn't really warranted.
  3461. */
  3462. if (::GetLastError() != ERROR_BROKEN_PIPE) {
  3463. return FALSE;
  3464. }
  3465. *pbytes = 0;
  3466. }
  3467. return TRUE;
  3468. }
  3469. #define MAX_INPUT_EVENTS 2000
  3470. // This code is a copy of JDK's stdinAvailable
  3471. // from src/windows/hpi/src/sys_api_md.c
  3472. static int stdinAvailable(int fd, long *pbytes) {
  3473. HANDLE han;
  3474. DWORD numEventsRead = 0; /* Number of events read from buffer */
  3475. DWORD numEvents = 0; /* Number of events in buffer */
  3476. DWORD i = 0; /* Loop index */
  3477. DWORD curLength = 0; /* Position marker */
  3478. DWORD actualLength = 0; /* Number of bytes readable */
  3479. BOOL error = FALSE; /* Error holder */
  3480. INPUT_RECORD *lpBuffer; /* Pointer to records of input events */
  3481. if ((han = ::GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) {
  3482. return FALSE;
  3483. }
  3484. /* Construct an array of input records in the console buffer */
  3485. error = ::GetNumberOfConsoleInputEvents(han, &numEvents);
  3486. if (error == 0) {
  3487. return nonSeekAvailable(fd, pbytes);
  3488. }
  3489. /* lpBuffer must fit into 64K or else PeekConsoleInput fails */
  3490. if (numEvents > MAX_INPUT_EVENTS) {
  3491. numEvents = MAX_INPUT_EVENTS;
  3492. }
  3493. lpBuffer = (INPUT_RECORD *)os::malloc(numEvents * sizeof(INPUT_RECORD));
  3494. if (lpBuffer == NULL) {
  3495. return FALSE;
  3496. }
  3497. error = ::PeekConsoleInput(han, lpBuffer, numEvents, &numEventsRead);
  3498. if (error == 0) {
  3499. os::free(lpBuffer);
  3500. return FALSE;
  3501. }
  3502. /* Examine input records for the number of bytes available */
  3503. for(i=0; i<numEvents; i++) {
  3504. if (lpBuffer[i].EventType == KEY_EVENT) {
  3505. KEY_EVENT_RECORD *keyRecord = (KEY_EVENT_RECORD *)
  3506. &(lpBuffer[i].Event);
  3507. if (keyRecord->bKeyDown == TRUE) {
  3508. CHAR *keyPressed = (CHAR *) &(keyRecord->uChar);
  3509. curLength++;
  3510. if (*keyPressed == '\r') {
  3511. actualLength = curLength;
  3512. }
  3513. }
  3514. }
  3515. }
  3516. if(lpBuffer != NULL) {
  3517. os::free(lpBuffer);
  3518. }
  3519. *pbytes = (long) actualLength;
  3520. return TRUE;
  3521. }
  3522. // Map a block of memory.
  3523. char* os::map_memory(int fd, const char* file_name, size_t file_offset,
  3524. char *addr, size_t bytes, bool read_only,
  3525. bool allow_exec) {
  3526. HANDLE hFile;
  3527. char* base;
  3528. hFile = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, NULL,
  3529. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  3530. if (hFile == NULL) {
  3531. if (PrintMiscellaneous && Verbose) {
  3532. DWORD err = GetLastError();
  3533. tty->print_cr("CreateFile() failed: GetLastError->%ld.");
  3534. }
  3535. return NULL;
  3536. }
  3537. if (allow_exec) {
  3538. // CreateFileMapping/MapViewOfFileEx can't map executable memory
  3539. // unless it comes from a PE image (which the shared archive is not.)
  3540. // Even VirtualProtect refuses to give execute access to mapped memory
  3541. // that was not previously executable.
  3542. //
  3543. // Instead, stick the executable region in anonymous memory. Yuck.
  3544. // Penalty is that ~4 pages will not be shareable - in the future
  3545. // we might consider DLLizing the shared archive with a proper PE
  3546. // header so that mapping executable + sharing is possible.
  3547. base = (char*) VirtualAlloc(addr, bytes, MEM_COMMIT | MEM_RESERVE,
  3548. PAGE_READWRITE);
  3549. if (base == NULL) {
  3550. if (PrintMiscellaneous && Verbose) {
  3551. DWORD err = GetLastError();
  3552. tty->print_cr("VirtualAlloc() failed: GetLastError->%ld.", err);
  3553. }
  3554. CloseHandle(hFile);
  3555. return NULL;
  3556. }
  3557. DWORD bytes_read;
  3558. OVERLAPPED overlapped;
  3559. overlapped.Offset = (DWORD)file_offset;
  3560. overlapped.OffsetHigh = 0;
  3561. overlapped.hEvent = NULL;
  3562. // ReadFile guarantees that if the return value is true, the requested
  3563. // number of bytes were read before returning.
  3564. bool res = ReadFile(hFile, base, (DWORD)bytes, &bytes_read, &overlapped) != 0;
  3565. if (!res) {
  3566. if (PrintMiscellaneous && Verbose) {
  3567. DWORD err = GetLastError();
  3568. tty->print_cr("ReadFile() failed: GetLastError->%ld.", err);
  3569. }
  3570. release_memory(base, bytes);
  3571. CloseHandle(hFile);
  3572. return NULL;
  3573. }
  3574. } else {
  3575. HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0,
  3576. NULL /*file_name*/);
  3577. if (hMap == NULL) {
  3578. if (PrintMiscellaneous && Verbose) {
  3579. DWORD err = GetLastError();
  3580. tty->print_cr("CreateFileMapping() failed: GetLastError->%ld.");
  3581. }
  3582. CloseHandle(hFile);
  3583. return NULL;
  3584. }
  3585. DWORD access = read_only ? FILE_MAP_READ : FILE_MAP_COPY;
  3586. base = (char*)MapViewOfFileEx(hMap, access, 0, (DWORD)file_offset,
  3587. (DWORD)bytes, addr);
  3588. if (base == NULL) {
  3589. if (PrintMiscellaneous && Verbose) {
  3590. DWORD err = GetLastError();
  3591. tty->print_cr("MapViewOfFileEx() failed: GetLastError->%ld.", err);
  3592. }
  3593. CloseHandle(hMap);
  3594. CloseHandle(hFile);
  3595. return NULL;
  3596. }
  3597. if (CloseHandle(hMap) == 0) {
  3598. if (PrintMiscellaneous && Verbose) {
  3599. DWORD err = GetLastError();
  3600. tty->print_cr("CloseHandle(hMap) failed: GetLastError->%ld.", err);
  3601. }
  3602. CloseHandle(hFile);
  3603. return base;
  3604. }
  3605. }
  3606. if (allow_exec) {
  3607. DWORD old_protect;
  3608. DWORD exec_access = read_only ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE;
  3609. bool res = VirtualProtect(base, bytes, exec_access, &old_protect) != 0;
  3610. if (!res) {
  3611. if (PrintMiscellaneous && Verbose) {
  3612. DWORD err = GetLastError();
  3613. tty->print_cr("VirtualProtect() failed: GetLastError->%ld.", err);
  3614. }
  3615. // Don't consider this a hard error, on IA32 even if the
  3616. // VirtualProtect fails, we should still be able to execute
  3617. CloseHandle(hFile);
  3618. return base;
  3619. }
  3620. }
  3621. if (CloseHandle(hFile) == 0) {
  3622. if (PrintMiscellaneous && Verbose) {
  3623. DWORD err = GetLastError();
  3624. tty->print_cr("CloseHandle(hFile) failed: GetLastError->%ld.", err);
  3625. }
  3626. return base;
  3627. }
  3628. return base;
  3629. }
  3630. // Remap a block of memory.
  3631. char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
  3632. char *addr, size_t bytes, bool read_only,
  3633. bool allow_exec) {
  3634. // This OS does not allow existing memory maps to be remapped so we
  3635. // have to unmap the memory before we remap it.
  3636. if (!os::unmap_memory(addr, bytes)) {
  3637. return NULL;
  3638. }
  3639. // There is a very small theoretical window between the unmap_memory()
  3640. // call above and the map_memory() call below where a thread in native
  3641. // code may be able to access an address that is no longer mapped.
  3642. return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  3643. allow_exec);
  3644. }
  3645. // Unmap a block of memory.
  3646. // Returns true=success, otherwise false.
  3647. bool os::unmap_memory(char* addr, size_t bytes) {
  3648. BOOL result = UnmapViewOfFile(addr);
  3649. if (result == 0) {
  3650. if (PrintMiscellaneous && Verbose) {
  3651. DWORD err = GetLastError();
  3652. tty->print_cr("UnmapViewOfFile() failed: GetLastError->%ld.", err);
  3653. }
  3654. return false;
  3655. }
  3656. return true;
  3657. }
  3658. void os::pause() {
  3659. char filename[MAX_PATH];
  3660. if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  3661. jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  3662. } else {
  3663. jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  3664. }
  3665. int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  3666. if (fd != -1) {
  3667. struct stat buf;
  3668. ::close(fd);
  3669. while (::stat(filename, &buf) == 0) {
  3670. Sleep(100);
  3671. }
  3672. } else {
  3673. jio_fprintf(stderr,
  3674. "Could not open pause file '%s', continuing immediately.\n", filename);
  3675. }
  3676. }
  3677. // An Event wraps a win32 "CreateEvent" kernel handle.
  3678. //
  3679. // We have a number of choices regarding "CreateEvent" win32 handle leakage:
  3680. //
  3681. // 1: When a thread dies return the Event to the EventFreeList, clear the ParkHandle
  3682. // field, and call CloseHandle() on the win32 event handle. Unpark() would
  3683. // need to be modified to tolerate finding a NULL (invalid) win32 event handle.
  3684. // In addition, an unpark() operation might fetch the handle field, but the
  3685. // event could recycle between the fetch and the SetEvent() operation.
  3686. // SetEvent() would either fail because the handle was invalid, or inadvertently work,
  3687. // as the win32 handle value had been recycled. In an ideal world calling SetEvent()
  3688. // on an stale but recycled handle would be harmless, but in practice this might
  3689. // confuse other non-Sun code, so it's not a viable approach.
  3690. //
  3691. // 2: Once a win32 event handle is associated with an Event, it remains associated
  3692. // with the Event. The event handle is never closed. This could be construed
  3693. // as handle leakage, but only up to the maximum # of threads that have been extant
  3694. // at any one time. This shouldn't be an issue, as windows platforms typically
  3695. // permit a process to have hundreds of thousands of open handles.
  3696. //
  3697. // 3: Same as (1), but periodically, at stop-the-world time, rundown the EventFreeList
  3698. // and release unused handles.
  3699. //
  3700. // 4: Add a CRITICAL_SECTION to the Event to protect LD+SetEvent from LD;ST(null);CloseHandle.
  3701. // It's not clear, however, that we wouldn't be trading one type of leak for another.
  3702. //
  3703. // 5. Use an RCU-like mechanism (Read-Copy Update).
  3704. // Or perhaps something similar to Maged Michael's "Hazard pointers".
  3705. //
  3706. // We use (2).
  3707. //
  3708. // TODO-FIXME:
  3709. // 1. Reconcile Doug's JSR166 j.u.c park-unpark with the objectmonitor implementation.
  3710. // 2. Consider wrapping the WaitForSingleObject(Ex) calls in SEH try/finally blocks
  3711. // to recover from (or at least detect) the dreaded Windows 841176 bug.
  3712. // 3. Collapse the interrupt_event, the JSR166 parker event, and the objectmonitor ParkEvent
  3713. // into a single win32 CreateEvent() handle.
  3714. //
  3715. // _Event transitions in park()
  3716. // -1 => -1 : illegal
  3717. // 1 => 0 : pass - return immediately
  3718. // 0 => -1 : block
  3719. //
  3720. // _Event serves as a restricted-range semaphore :
  3721. // -1 : thread is blocked
  3722. // 0 : neutral - thread is running or ready
  3723. // 1 : signaled - thread is running or ready
  3724. //
  3725. // Another possible encoding of _Event would be
  3726. // with explicit "PARKED" and "SIGNALED" bits.
  3727. int os::PlatformEvent::park (jlong Millis) {
  3728. guarantee (_ParkHandle != NULL , "Invariant") ;
  3729. guarantee (Millis > 0 , "Invariant") ;
  3730. int v ;
  3731. // CONSIDER: defer assigning a CreateEvent() handle to the Event until
  3732. // the initial park() operation.
  3733. for (;;) {
  3734. v = _Event ;
  3735. if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  3736. }
  3737. guarantee ((v == 0) || (v == 1), "invariant") ;
  3738. if (v != 0) return OS_OK ;
  3739. // Do this the hard way by blocking ...
  3740. // TODO: consider a brief spin here, gated on the success of recent
  3741. // spin attempts by this thread.
  3742. //
  3743. // We decompose long timeouts into series of shorter timed waits.
  3744. // Evidently large timo values passed in WaitForSingleObject() are problematic on some
  3745. // versions of Windows. See EventWait() for details. This may be superstition. Or not.
  3746. // We trust the WAIT_TIMEOUT indication and don't track the elapsed wait time
  3747. // with os::javaTimeNanos(). Furthermore, we assume that spurious returns from
  3748. // ::WaitForSingleObject() caused by latent ::setEvent() operations will tend
  3749. // to happen early in the wait interval. Specifically, after a spurious wakeup (rv ==
  3750. // WAIT_OBJECT_0 but _Event is still < 0) we don't bother to recompute Millis to compensate
  3751. // for the already waited time. This policy does not admit any new outcomes.
  3752. // In the future, however, we might want to track the accumulated wait time and
  3753. // adjust Millis accordingly if we encounter a spurious wakeup.
  3754. const int MAXTIMEOUT = 0x10000000 ;
  3755. DWORD rv = WAIT_TIMEOUT ;
  3756. while (_Event < 0 && Millis > 0) {
  3757. DWORD prd = Millis ; // set prd = MAX (Millis, MAXTIMEOUT)
  3758. if (Millis > MAXTIMEOUT) {
  3759. prd = MAXTIMEOUT ;
  3760. }
  3761. rv = ::WaitForSingleObject (_ParkHandle, prd) ;
  3762. assert (rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed") ;
  3763. if (rv == WAIT_TIMEOUT) {
  3764. Millis -= prd ;
  3765. }
  3766. }
  3767. v = _Event ;
  3768. _Event = 0 ;
  3769. OrderAccess::fence() ;
  3770. // If we encounter a nearly simultanous timeout expiry and unpark()
  3771. // we return OS_OK indicating we awoke via unpark().
  3772. // Implementor's license -- returning OS_TIMEOUT would be equally valid, however.
  3773. return (v >= 0) ? OS_OK : OS_TIMEOUT ;
  3774. }
  3775. void os::PlatformEvent::park () {
  3776. guarantee (_ParkHandle != NULL, "Invariant") ;
  3777. // Invariant: Only the thread associated with the Event/PlatformEvent
  3778. // may call park().
  3779. int v ;
  3780. for (;;) {
  3781. v = _Event ;
  3782. if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  3783. }
  3784. guarantee ((v == 0) || (v == 1), "invariant") ;
  3785. if (v != 0) return ;
  3786. // Do this the hard way by blocking ...
  3787. // TODO: consider a brief spin here, gated on the success of recent
  3788. // spin attempts by this thread.
  3789. while (_Event < 0) {
  3790. DWORD rv = ::WaitForSingleObject (_ParkHandle, INFINITE) ;
  3791. assert (rv == WAIT_OBJECT_0, "WaitForSingleObject failed") ;
  3792. }
  3793. // Usually we'll find _Event == 0 at this point, but as
  3794. // an optional optimization we clear it, just in case can
  3795. // multiple unpark() operations drove _Event up to 1.
  3796. _Event = 0 ;
  3797. OrderAccess::fence() ;
  3798. guarantee (_Event >= 0, "invariant") ;
  3799. }
  3800. void os::PlatformEvent::unpark() {
  3801. guarantee (_ParkHandle != NULL, "Invariant") ;
  3802. int v ;
  3803. for (;;) {
  3804. v = _Event ; // Increment _Event if it's < 1.
  3805. if (v > 0) {
  3806. // If it's already signaled just return.
  3807. // The LD of _Event could have reordered or be satisfied
  3808. // by a read-aside from this processor's write buffer.
  3809. // To avoid problems execute a barrier and then
  3810. // ratify the value. A degenerate CAS() would also work.
  3811. // Viz., CAS (v+0, &_Event, v) == v).
  3812. OrderAccess::fence() ;
  3813. if (_Event == v) return ;
  3814. continue ;
  3815. }
  3816. if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
  3817. }
  3818. if (v < 0) {
  3819. ::SetEvent (_ParkHandle) ;
  3820. }
  3821. }
  3822. // JSR166
  3823. // -------------------------------------------------------
  3824. /*
  3825. * The Windows implementation of Park is very straightforward: Basic
  3826. * operations on Win32 Events turn out to have the right semantics to
  3827. * use them directly. We opportunistically resuse the event inherited
  3828. * from Monitor.
  3829. */
  3830. void Parker::park(bool isAbsolute, jlong time) {
  3831. guarantee (_ParkEvent != NULL, "invariant") ;
  3832. // First, demultiplex/decode time arguments
  3833. if (time < 0) { // don't wait
  3834. return;
  3835. }
  3836. else if (time == 0 && !isAbsolute) {
  3837. time = INFINITE;
  3838. }
  3839. else if (isAbsolute) {
  3840. time -= os::javaTimeMillis(); // convert to relative time
  3841. if (time <= 0) // already elapsed
  3842. return;
  3843. }
  3844. else { // relative
  3845. time /= 1000000; // Must coarsen from nanos to millis
  3846. if (time == 0) // Wait for the minimal time unit if zero
  3847. time = 1;
  3848. }
  3849. JavaThread* thread = (JavaThread*)(Thread::current());
  3850. assert(thread->is_Java_thread(), "Must be JavaThread");
  3851. JavaThread *jt = (JavaThread *)thread;
  3852. // Don't wait if interrupted or already triggered
  3853. if (Thread::is_interrupted(thread, false) ||
  3854. WaitForSingleObject(_ParkEvent, 0) == WAIT_OBJECT_0) {
  3855. ResetEvent(_ParkEvent);
  3856. return;
  3857. }
  3858. else {
  3859. ThreadBlockInVM tbivm(jt);
  3860. OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  3861. jt->set_suspend_equivalent();
  3862. WaitForSingleObject(_ParkEvent, time);
  3863. ResetEvent(_ParkEvent);
  3864. // If externally suspended while waiting, re-suspend
  3865. if (jt->handle_special_suspend_equivalent_condition()) {
  3866. jt->java_suspend_self();
  3867. }
  3868. }
  3869. }
  3870. void Parker::unpark() {
  3871. guarantee (_ParkEvent != NULL, "invariant") ;
  3872. SetEvent(_ParkEvent);
  3873. }
  3874. // Run the specified command in a separate process. Return its exit value,
  3875. // or -1 on failure (e.g. can't create a new process).
  3876. int os::fork_and_exec(char* cmd) {
  3877. STARTUPINFO si;
  3878. PROCESS_INFORMATION pi;
  3879. memset(&si, 0, sizeof(si));
  3880. si.cb = sizeof(si);
  3881. memset(&pi, 0, sizeof(pi));
  3882. BOOL rslt = CreateProcess(NULL, // executable name - use command line
  3883. cmd, // command line
  3884. NULL, // process security attribute
  3885. NULL, // thread security attribute
  3886. TRUE, // inherits system handles
  3887. 0, // no creation flags
  3888. NULL, // use parent's environment block
  3889. NULL, // use parent's starting directory
  3890. &si, // (in) startup information
  3891. &pi); // (out) process information
  3892. if (rslt) {
  3893. // Wait until child process exits.
  3894. WaitForSingleObject(pi.hProcess, INFINITE);
  3895. DWORD exit_code;
  3896. GetExitCodeProcess(pi.hProcess, &exit_code);
  3897. // Close process and thread handles.
  3898. CloseHandle(pi.hProcess);
  3899. CloseHandle(pi.hThread);
  3900. return (int)exit_code;
  3901. } else {
  3902. return -1;
  3903. }
  3904. }
  3905. //--------------------------------------------------------------------------------------------------
  3906. // Non-product code
  3907. static int mallocDebugIntervalCounter = 0;
  3908. static int mallocDebugCounter = 0;
  3909. bool os::check_heap(bool force) {
  3910. if (++mallocDebugCounter < MallocVerifyStart && !force) return true;
  3911. if (++mallocDebugIntervalCounter >= MallocVerifyInterval || force) {
  3912. // Note: HeapValidate executes two hardware breakpoints when it finds something
  3913. // wrong; at these points, eax contains the address of the offending block (I think).
  3914. // To get to the exlicit error message(s) below, just continue twice.
  3915. HANDLE heap = GetProcessHeap();
  3916. { HeapLock(heap);
  3917. PROCESS_HEAP_ENTRY phe;
  3918. phe.lpData = NULL;
  3919. while (HeapWalk(heap, &phe) != 0) {
  3920. if ((phe.wFlags & PROCESS_HEAP_ENTRY_BUSY) &&
  3921. !HeapValidate(heap, 0, phe.lpData)) {
  3922. tty->print_cr("C heap has been corrupted (time: %d allocations)", mallocDebugCounter);
  3923. tty->print_cr("corrupted block near address %#x, length %d", phe.lpData, phe.cbData);
  3924. fatal("corrupted C heap");
  3925. }
  3926. }
  3927. int err = GetLastError();
  3928. if (err != ERROR_NO_MORE_ITEMS && err != ERROR_CALL_NOT_IMPLEMENTED) {
  3929. fatal(err_msg("heap walk aborted with error %d", err));
  3930. }
  3931. HeapUnlock(heap);
  3932. }
  3933. mallocDebugIntervalCounter = 0;
  3934. }
  3935. return true;
  3936. }
  3937. bool os::find(address addr, outputStream* st) {
  3938. // Nothing yet
  3939. return false;
  3940. }
  3941. LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) {
  3942. DWORD exception_code = e->ExceptionRecord->ExceptionCode;
  3943. if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) {
  3944. JavaThread* thread = (JavaThread*)ThreadLocalStorage::get_thread_slow();
  3945. PEXCEPTION_RECORD exceptionRecord = e->ExceptionRecord;
  3946. address addr = (address) exceptionRecord->ExceptionInformation[1];
  3947. if (os::is_memory_serialize_page(thread, addr))
  3948. return EXCEPTION_CONTINUE_EXECUTION;
  3949. }
  3950. return EXCEPTION_CONTINUE_SEARCH;
  3951. }
  3952. static int getLastErrorString(char *buf, size_t len)
  3953. {
  3954. long errval;
  3955. if ((errval = GetLastError()) != 0)
  3956. {
  3957. /* DOS error */
  3958. size_t n = (size_t)FormatMessage(
  3959. FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  3960. NULL,
  3961. errval,
  3962. 0,
  3963. buf,
  3964. (DWORD)len,
  3965. NULL);
  3966. if (n > 3) {
  3967. /* Drop final '.', CR, LF */
  3968. if (buf[n - 1] == '\n') n--;
  3969. if (buf[n - 1] == '\r') n--;
  3970. if (buf[n - 1] == '.') n--;
  3971. buf[n] = '\0';
  3972. }
  3973. return (int)n;
  3974. }
  3975. if (errno != 0)
  3976. {
  3977. /* C runtime error that has no corresponding DOS error code */
  3978. const char *s = strerror(errno);
  3979. size_t n = strlen(s);
  3980. if (n >= len) n = len - 1;
  3981. strncpy(buf, s, n);
  3982. buf[n] = '\0';
  3983. return (int)n;
  3984. }
  3985. return 0;
  3986. }
  3987. // We don't build a headless jre for Windows
  3988. bool os::is_headless_jre() { return false; }
  3989. // OS_SocketInterface
  3990. // Not used on Windows
  3991. // OS_SocketInterface
  3992. typedef struct hostent * (PASCAL FAR *ws2_ifn_ptr_t)(...);
  3993. ws2_ifn_ptr_t *get_host_by_name_fn = NULL;
  3994. typedef CRITICAL_SECTION mutex_t;
  3995. #define mutexInit(m) InitializeCriticalSection(m)
  3996. #define mutexDestroy(m) DeleteCriticalSection(m)
  3997. #define mutexLock(m) EnterCriticalSection(m)
  3998. #define mutexUnlock(m) LeaveCriticalSection(m)
  3999. static bool sockfnptrs_initialized = FALSE;
  4000. static mutex_t sockFnTableMutex;
  4001. /* is Winsock2 loaded? better to be explicit than to rely on sockfnptrs */
  4002. static bool winsock2Available = FALSE;
  4003. static void initSockFnTable() {
  4004. int (PASCAL FAR* WSAStartupPtr)(WORD, LPWSADATA);
  4005. WSADATA wsadata;
  4006. ::mutexInit(&sockFnTableMutex);
  4007. ::mutexLock(&sockFnTableMutex);
  4008. if (sockfnptrs_initialized == FALSE) {
  4009. HMODULE hWinsock;
  4010. /* try to load Winsock2, and if that fails, load Winsock */
  4011. hWinsock = ::LoadLibrary("ws2_32.dll");
  4012. if (hWinsock == NULL) {
  4013. jio_fprintf(stderr, "Could not load Winsock 2 (error: %d)\n",
  4014. ::GetLastError());
  4015. return;
  4016. }
  4017. /* If we loaded a DLL, then we might as well initialize it. */
  4018. WSAStartupPtr = (int (PASCAL FAR *)(WORD, LPWSADATA))
  4019. ::GetProcAddress(hWinsock, "WSAStartup");
  4020. if (WSAStartupPtr(MAKEWORD(1,1), &wsadata) != 0) {
  4021. jio_fprintf(stderr, "Could not initialize Winsock\n");
  4022. }
  4023. get_host_by_name_fn
  4024. = (ws2_ifn_ptr_t*) GetProcAddress(hWinsock, "gethostbyname");
  4025. }
  4026. assert(get_host_by_name_fn != NULL,
  4027. "gethostbyname function not found");
  4028. sockfnptrs_initialized = TRUE;
  4029. ::mutexUnlock(&sockFnTableMutex);
  4030. }
  4031. struct hostent* os::get_host_by_name(char* name) {
  4032. if (!sockfnptrs_initialized) {
  4033. initSockFnTable();
  4034. }
  4035. assert(sockfnptrs_initialized == TRUE && get_host_by_name_fn != NULL,
  4036. "sockfnptrs is not initialized or pointer to gethostbyname function is NULL");
  4037. return (*get_host_by_name_fn)(name);
  4038. }
  4039. int os::socket_close(int fd) {
  4040. ShouldNotReachHere();
  4041. return 0;
  4042. }
  4043. int os::socket_available(int fd, jint *pbytes) {
  4044. ShouldNotReachHere();
  4045. return 0;
  4046. }
  4047. int os::socket(int domain, int type, int protocol) {
  4048. ShouldNotReachHere();
  4049. return 0;
  4050. }
  4051. int os::listen(int fd, int count) {
  4052. ShouldNotReachHere();
  4053. return 0;
  4054. }
  4055. int os::connect(int fd, struct sockaddr *him, int len) {
  4056. ShouldNotReachHere();
  4057. return 0;
  4058. }
  4059. int os::accept(int fd, struct sockaddr *him, int *len) {
  4060. ShouldNotReachHere();
  4061. return 0;
  4062. }
  4063. int os::sendto(int fd, char *buf, int len, int flags,
  4064. struct sockaddr *to, int tolen) {
  4065. ShouldNotReachHere();
  4066. return 0;
  4067. }
  4068. int os::recvfrom(int fd, char *buf, int nBytes, int flags,
  4069. sockaddr *from, int *fromlen) {
  4070. ShouldNotReachHere();
  4071. return 0;
  4072. }
  4073. int os::recv(int fd, char *buf, int nBytes, int flags) {
  4074. ShouldNotReachHere();
  4075. return 0;
  4076. }
  4077. int os::send(int fd, char *buf, int nBytes, int flags) {
  4078. ShouldNotReachHere();
  4079. return 0;
  4080. }
  4081. int os::raw_send(int fd, char *buf, int nBytes, int flags) {
  4082. ShouldNotReachHere();
  4083. return 0;
  4084. }
  4085. int os::timeout(int fd, long timeout) {
  4086. ShouldNotReachHere();
  4087. return 0;
  4088. }
  4089. int os::get_host_name(char* name, int namelen) {
  4090. ShouldNotReachHere();
  4091. return 0;
  4092. }
  4093. int os::socket_shutdown(int fd, int howto) {
  4094. ShouldNotReachHere();
  4095. return 0;
  4096. }
  4097. int os::bind(int fd, struct sockaddr *him, int len) {
  4098. ShouldNotReachHere();
  4099. return 0;
  4100. }
  4101. int os::get_sock_name(int fd, struct sockaddr *him, int *len) {
  4102. ShouldNotReachHere();
  4103. return 0;
  4104. }
  4105. int os::get_sock_opt(int fd, int level, int optname,
  4106. char *optval, int* optlen) {
  4107. ShouldNotReachHere();
  4108. return 0;
  4109. }
  4110. int os::set_sock_opt(int fd, int level, int optname,
  4111. const char *optval, int optlen) {
  4112. ShouldNotReachHere();
  4113. return 0;
  4114. }