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