Mercurial > hg > truffle
annotate src/os/bsd/vm/os_bsd.cpp @ 4935:df4927a3b82e
Merge
author | coleenp |
---|---|
date | Thu, 16 Feb 2012 17:19:40 -0500 |
parents | de268c8a8075 |
children | 86ce3208eb18 |
rev | line source |
---|---|
3960 | 1 /* |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. |
3960 | 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 // no precompiled headers | |
26 #include "classfile/classLoader.hpp" | |
27 #include "classfile/systemDictionary.hpp" | |
28 #include "classfile/vmSymbols.hpp" | |
29 #include "code/icBuffer.hpp" | |
30 #include "code/vtableStubs.hpp" | |
31 #include "compiler/compileBroker.hpp" | |
32 #include "interpreter/interpreter.hpp" | |
33 #include "jvm_bsd.h" | |
34 #include "memory/allocation.inline.hpp" | |
35 #include "memory/filemap.hpp" | |
36 #include "mutex_bsd.inline.hpp" | |
37 #include "oops/oop.inline.hpp" | |
38 #include "os_share_bsd.hpp" | |
39 #include "prims/jniFastGetField.hpp" | |
40 #include "prims/jvm.h" | |
41 #include "prims/jvm_misc.hpp" | |
42 #include "runtime/arguments.hpp" | |
43 #include "runtime/extendedPC.hpp" | |
44 #include "runtime/globals.hpp" | |
45 #include "runtime/interfaceSupport.hpp" | |
46 #include "runtime/java.hpp" | |
47 #include "runtime/javaCalls.hpp" | |
48 #include "runtime/mutexLocker.hpp" | |
49 #include "runtime/objectMonitor.hpp" | |
50 #include "runtime/osThread.hpp" | |
51 #include "runtime/perfMemory.hpp" | |
52 #include "runtime/sharedRuntime.hpp" | |
53 #include "runtime/statSampler.hpp" | |
54 #include "runtime/stubRoutines.hpp" | |
55 #include "runtime/threadCritical.hpp" | |
56 #include "runtime/timer.hpp" | |
57 #include "services/attachListener.hpp" | |
58 #include "services/runtimeService.hpp" | |
59 #include "thread_bsd.inline.hpp" | |
60 #include "utilities/decoder.hpp" | |
61 #include "utilities/defaultStream.hpp" | |
62 #include "utilities/events.hpp" | |
63 #include "utilities/growableArray.hpp" | |
64 #include "utilities/vmError.hpp" | |
65 #ifdef TARGET_ARCH_x86 | |
66 # include "assembler_x86.inline.hpp" | |
67 # include "nativeInst_x86.hpp" | |
68 #endif | |
69 #ifdef TARGET_ARCH_sparc | |
70 # include "assembler_sparc.inline.hpp" | |
71 # include "nativeInst_sparc.hpp" | |
72 #endif | |
73 #ifdef TARGET_ARCH_zero | |
74 # include "assembler_zero.inline.hpp" | |
75 # include "nativeInst_zero.hpp" | |
76 #endif | |
77 #ifdef TARGET_ARCH_arm | |
78 # include "assembler_arm.inline.hpp" | |
79 # include "nativeInst_arm.hpp" | |
80 #endif | |
81 #ifdef TARGET_ARCH_ppc | |
82 # include "assembler_ppc.inline.hpp" | |
83 # include "nativeInst_ppc.hpp" | |
84 #endif | |
85 #ifdef COMPILER1 | |
86 #include "c1/c1_Runtime1.hpp" | |
87 #endif | |
88 #ifdef COMPILER2 | |
89 #include "opto/runtime.hpp" | |
90 #endif | |
91 | |
92 // put OS-includes here | |
93 # include <sys/types.h> | |
94 # include <sys/mman.h> | |
95 # include <sys/stat.h> | |
96 # include <sys/select.h> | |
97 # include <pthread.h> | |
98 # include <signal.h> | |
99 # include <errno.h> | |
100 # include <dlfcn.h> | |
101 # include <stdio.h> | |
102 # include <unistd.h> | |
103 # include <sys/resource.h> | |
104 # include <pthread.h> | |
105 # include <sys/stat.h> | |
106 # include <sys/time.h> | |
107 # include <sys/times.h> | |
108 # include <sys/utsname.h> | |
109 # include <sys/socket.h> | |
110 # include <sys/wait.h> | |
111 # include <time.h> | |
112 # include <pwd.h> | |
113 # include <poll.h> | |
114 # include <semaphore.h> | |
115 # include <fcntl.h> | |
116 # include <string.h> | |
117 #ifdef _ALLBSD_SOURCE | |
118 # include <sys/param.h> | |
119 # include <sys/sysctl.h> | |
120 #else | |
121 # include <syscall.h> | |
122 # include <sys/sysinfo.h> | |
123 # include <gnu/libc-version.h> | |
124 #endif | |
125 # include <sys/ipc.h> | |
126 # include <sys/shm.h> | |
127 #ifndef __APPLE__ | |
128 # include <link.h> | |
129 #endif | |
130 # include <stdint.h> | |
131 # include <inttypes.h> | |
132 # include <sys/ioctl.h> | |
133 | |
134 #if defined(__FreeBSD__) || defined(__NetBSD__) | |
135 # include <elf.h> | |
136 #endif | |
137 | |
138 #ifdef __APPLE__ | |
4006 | 139 # include <mach/mach.h> // semaphore_* API |
140 # include <mach-o/dyld.h> | |
141 # include <sys/proc_info.h> | |
142 # include <objc/objc-auto.h> | |
3960 | 143 #endif |
144 | |
145 #ifndef MAP_ANONYMOUS | |
146 #define MAP_ANONYMOUS MAP_ANON | |
147 #endif | |
148 | |
149 #define MAX_PATH (2 * K) | |
150 | |
151 // for timer info max values which include all bits | |
152 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) | |
153 | |
154 #define LARGEPAGES_BIT (1 << 6) | |
155 //////////////////////////////////////////////////////////////////////////////// | |
156 // global variables | |
157 julong os::Bsd::_physical_memory = 0; | |
158 | |
159 #ifndef _ALLBSD_SOURCE | |
160 address os::Bsd::_initial_thread_stack_bottom = NULL; | |
161 uintptr_t os::Bsd::_initial_thread_stack_size = 0; | |
162 #endif | |
163 | |
164 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL; | |
165 #ifndef _ALLBSD_SOURCE | |
166 int (*os::Bsd::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL; | |
167 Mutex* os::Bsd::_createThread_lock = NULL; | |
168 #endif | |
169 pthread_t os::Bsd::_main_thread; | |
170 int os::Bsd::_page_size = -1; | |
171 #ifndef _ALLBSD_SOURCE | |
172 bool os::Bsd::_is_floating_stack = false; | |
173 bool os::Bsd::_is_NPTL = false; | |
174 bool os::Bsd::_supports_fast_thread_cpu_time = false; | |
175 const char * os::Bsd::_glibc_version = NULL; | |
176 const char * os::Bsd::_libpthread_version = NULL; | |
177 #endif | |
178 | |
179 static jlong initial_time_count=0; | |
180 | |
181 static int clock_tics_per_sec = 100; | |
182 | |
183 // For diagnostics to print a message once. see run_periodic_checks | |
184 static sigset_t check_signal_done; | |
185 static bool check_signals = true;; | |
186 | |
187 static pid_t _initial_pid = 0; | |
188 | |
189 /* Signal number used to suspend/resume a thread */ | |
190 | |
191 /* do not use any signal number less than SIGSEGV, see 4355769 */ | |
192 static int SR_signum = SIGUSR2; | |
193 sigset_t SR_sigset; | |
194 | |
195 | |
196 //////////////////////////////////////////////////////////////////////////////// | |
197 // utility functions | |
198 | |
199 static int SR_initialize(); | |
200 static int SR_finalize(); | |
201 | |
202 julong os::available_memory() { | |
203 return Bsd::available_memory(); | |
204 } | |
205 | |
206 julong os::Bsd::available_memory() { | |
207 #ifdef _ALLBSD_SOURCE | |
208 // XXXBSD: this is just a stopgap implementation | |
209 return physical_memory() >> 2; | |
210 #else | |
211 // values in struct sysinfo are "unsigned long" | |
212 struct sysinfo si; | |
213 sysinfo(&si); | |
214 | |
215 return (julong)si.freeram * si.mem_unit; | |
216 #endif | |
217 } | |
218 | |
219 julong os::physical_memory() { | |
220 return Bsd::physical_memory(); | |
221 } | |
222 | |
223 julong os::allocatable_physical_memory(julong size) { | |
224 #ifdef _LP64 | |
225 return size; | |
226 #else | |
227 julong result = MIN2(size, (julong)3800*M); | |
228 if (!is_allocatable(result)) { | |
229 // See comments under solaris for alignment considerations | |
230 julong reasonable_size = (julong)2*G - 2 * os::vm_page_size(); | |
231 result = MIN2(size, reasonable_size); | |
232 } | |
233 return result; | |
234 #endif // _LP64 | |
235 } | |
236 | |
237 //////////////////////////////////////////////////////////////////////////////// | |
238 // environment support | |
239 | |
240 bool os::getenv(const char* name, char* buf, int len) { | |
241 const char* val = ::getenv(name); | |
242 if (val != NULL && strlen(val) < (size_t)len) { | |
243 strcpy(buf, val); | |
244 return true; | |
245 } | |
246 if (len > 0) buf[0] = 0; // return a null string | |
247 return false; | |
248 } | |
249 | |
250 | |
251 // Return true if user is running as root. | |
252 | |
253 bool os::have_special_privileges() { | |
254 static bool init = false; | |
255 static bool privileges = false; | |
256 if (!init) { | |
257 privileges = (getuid() != geteuid()) || (getgid() != getegid()); | |
258 init = true; | |
259 } | |
260 return privileges; | |
261 } | |
262 | |
263 | |
264 #ifndef _ALLBSD_SOURCE | |
265 #ifndef SYS_gettid | |
266 // i386: 224, ia64: 1105, amd64: 186, sparc 143 | |
267 #ifdef __ia64__ | |
268 #define SYS_gettid 1105 | |
269 #elif __i386__ | |
270 #define SYS_gettid 224 | |
271 #elif __amd64__ | |
272 #define SYS_gettid 186 | |
273 #elif __sparc__ | |
274 #define SYS_gettid 143 | |
275 #else | |
276 #error define gettid for the arch | |
277 #endif | |
278 #endif | |
279 #endif | |
280 | |
281 // Cpu architecture string | |
282 #if defined(ZERO) | |
283 static char cpu_arch[] = ZERO_LIBARCH; | |
284 #elif defined(IA64) | |
285 static char cpu_arch[] = "ia64"; | |
286 #elif defined(IA32) | |
287 static char cpu_arch[] = "i386"; | |
288 #elif defined(AMD64) | |
289 static char cpu_arch[] = "amd64"; | |
290 #elif defined(ARM) | |
291 static char cpu_arch[] = "arm"; | |
292 #elif defined(PPC) | |
293 static char cpu_arch[] = "ppc"; | |
294 #elif defined(SPARC) | |
295 # ifdef _LP64 | |
296 static char cpu_arch[] = "sparcv9"; | |
297 # else | |
298 static char cpu_arch[] = "sparc"; | |
299 # endif | |
300 #else | |
301 #error Add appropriate cpu_arch setting | |
302 #endif | |
303 | |
4846 | 304 // Compiler variant |
305 #ifdef COMPILER2 | |
306 #define COMPILER_VARIANT "server" | |
307 #else | |
308 #define COMPILER_VARIANT "client" | |
309 #endif | |
3960 | 310 |
311 #ifndef _ALLBSD_SOURCE | |
312 // pid_t gettid() | |
313 // | |
314 // Returns the kernel thread id of the currently running thread. Kernel | |
315 // thread id is used to access /proc. | |
316 // | |
317 // (Note that getpid() on BsdThreads returns kernel thread id too; but | |
318 // on NPTL, it returns the same pid for all threads, as required by POSIX.) | |
319 // | |
320 pid_t os::Bsd::gettid() { | |
321 int rslt = syscall(SYS_gettid); | |
322 if (rslt == -1) { | |
323 // old kernel, no NPTL support | |
324 return getpid(); | |
325 } else { | |
326 return (pid_t)rslt; | |
327 } | |
328 } | |
329 | |
330 // Most versions of bsd have a bug where the number of processors are | |
331 // determined by looking at the /proc file system. In a chroot environment, | |
332 // the system call returns 1. This causes the VM to act as if it is | |
333 // a single processor and elide locking (see is_MP() call). | |
334 static bool unsafe_chroot_detected = false; | |
335 static const char *unstable_chroot_error = "/proc file system not found.\n" | |
336 "Java may be unstable running multithreaded in a chroot " | |
337 "environment on Bsd when /proc filesystem is not mounted."; | |
338 #endif | |
339 | |
340 #ifdef _ALLBSD_SOURCE | |
341 void os::Bsd::initialize_system_info() { | |
342 int mib[2]; | |
343 size_t len; | |
344 int cpu_val; | |
345 u_long mem_val; | |
346 | |
347 /* get processors count via hw.ncpus sysctl */ | |
348 mib[0] = CTL_HW; | |
349 mib[1] = HW_NCPU; | |
350 len = sizeof(cpu_val); | |
351 if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) { | |
352 set_processor_count(cpu_val); | |
353 } | |
354 else { | |
355 set_processor_count(1); // fallback | |
356 } | |
357 | |
358 /* get physical memory via hw.usermem sysctl (hw.usermem is used | |
359 * instead of hw.physmem because we need size of allocatable memory | |
360 */ | |
361 mib[0] = CTL_HW; | |
362 mib[1] = HW_USERMEM; | |
363 len = sizeof(mem_val); | |
364 if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) | |
365 _physical_memory = mem_val; | |
366 else | |
367 _physical_memory = 256*1024*1024; // fallback (XXXBSD?) | |
368 | |
369 #ifdef __OpenBSD__ | |
370 { | |
371 // limit _physical_memory memory view on OpenBSD since | |
372 // datasize rlimit restricts us anyway. | |
373 struct rlimit limits; | |
374 getrlimit(RLIMIT_DATA, &limits); | |
375 _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur); | |
376 } | |
377 #endif | |
378 } | |
379 #else | |
380 void os::Bsd::initialize_system_info() { | |
381 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); | |
382 if (processor_count() == 1) { | |
383 pid_t pid = os::Bsd::gettid(); | |
384 char fname[32]; | |
385 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid); | |
386 FILE *fp = fopen(fname, "r"); | |
387 if (fp == NULL) { | |
388 unsafe_chroot_detected = true; | |
389 } else { | |
390 fclose(fp); | |
391 } | |
392 } | |
393 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); | |
394 assert(processor_count() > 0, "bsd error"); | |
395 } | |
396 #endif | |
397 | |
4006 | 398 #ifdef __APPLE__ |
399 static const char *get_home() { | |
400 const char *home_dir = ::getenv("HOME"); | |
401 if ((home_dir == NULL) || (*home_dir == '\0')) { | |
402 struct passwd *passwd_info = getpwuid(geteuid()); | |
403 if (passwd_info != NULL) { | |
404 home_dir = passwd_info->pw_dir; | |
405 } | |
406 } | |
407 | |
408 return home_dir; | |
409 } | |
410 #endif | |
411 | |
3960 | 412 void os::init_system_properties_values() { |
413 // char arch[12]; | |
414 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch)); | |
415 | |
416 // The next steps are taken in the product version: | |
417 // | |
418 // Obtain the JAVA_HOME value from the location of libjvm[_g].so. | |
419 // This library should be located at: | |
420 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so. | |
421 // | |
422 // If "/jre/lib/" appears at the right place in the path, then we | |
423 // assume libjvm[_g].so is installed in a JDK and we use this path. | |
424 // | |
425 // Otherwise exit with message: "Could not create the Java virtual machine." | |
426 // | |
427 // The following extra steps are taken in the debugging version: | |
428 // | |
429 // If "/jre/lib/" does NOT appear at the right place in the path | |
430 // instead of exit check for $JAVA_HOME environment variable. | |
431 // | |
432 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, | |
433 // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so | |
434 // it looks like libjvm[_g].so is installed there | |
435 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so. | |
436 // | |
437 // Otherwise exit. | |
438 // | |
439 // Important note: if the location of libjvm.so changes this | |
440 // code needs to be changed accordingly. | |
441 | |
442 // The next few definitions allow the code to be verbatim: | |
443 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n)) | |
444 #define getenv(n) ::getenv(n) | |
445 | |
446 /* | |
447 * See ld(1): | |
448 * The linker uses the following search paths to locate required | |
449 * shared libraries: | |
450 * 1: ... | |
451 * ... | |
452 * 7: The default directories, normally /lib and /usr/lib. | |
453 */ | |
454 #ifndef DEFAULT_LIBPATH | |
455 #define DEFAULT_LIBPATH "/lib:/usr/lib" | |
456 #endif | |
457 | |
458 #define EXTENSIONS_DIR "/lib/ext" | |
459 #define ENDORSED_DIR "/lib/endorsed" | |
460 #define REG_DIR "/usr/java/packages" | |
461 | |
4006 | 462 #ifdef __APPLE__ |
463 #define SYS_EXTENSIONS_DIR "/Library/Java/Extensions" | |
464 #define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java" | |
465 const char *user_home_dir = get_home(); | |
466 // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir | |
467 int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) + | |
468 sizeof(SYS_EXTENSIONS_DIRS); | |
469 #endif | |
470 | |
3960 | 471 { |
472 /* sysclasspath, java_home, dll_dir */ | |
473 { | |
474 char *home_path; | |
475 char *dll_path; | |
476 char *pslash; | |
477 char buf[MAXPATHLEN]; | |
478 os::jvm_path(buf, sizeof(buf)); | |
479 | |
480 // Found the full path to libjvm.so. | |
481 // Now cut the path to <java_home>/jre if we can. | |
482 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */ | |
483 pslash = strrchr(buf, '/'); | |
484 if (pslash != NULL) | |
485 *pslash = '\0'; /* get rid of /{client|server|hotspot} */ | |
486 dll_path = malloc(strlen(buf) + 1); | |
487 if (dll_path == NULL) | |
488 return; | |
489 strcpy(dll_path, buf); | |
490 Arguments::set_dll_dir(dll_path); | |
491 | |
492 if (pslash != NULL) { | |
493 pslash = strrchr(buf, '/'); | |
494 if (pslash != NULL) { | |
4006 | 495 *pslash = '\0'; /* get rid of /<arch> (/lib on macosx) */ |
496 #ifndef __APPLE__ | |
3960 | 497 pslash = strrchr(buf, '/'); |
498 if (pslash != NULL) | |
499 *pslash = '\0'; /* get rid of /lib */ | |
4006 | 500 #endif |
3960 | 501 } |
502 } | |
503 | |
504 home_path = malloc(strlen(buf) + 1); | |
505 if (home_path == NULL) | |
506 return; | |
507 strcpy(home_path, buf); | |
508 Arguments::set_java_home(home_path); | |
509 | |
510 if (!set_boot_path('/', ':')) | |
511 return; | |
512 } | |
513 | |
514 /* | |
515 * Where to look for native libraries | |
516 * | |
517 * Note: Due to a legacy implementation, most of the library path | |
518 * is set in the launcher. This was to accomodate linking restrictions | |
519 * on legacy Bsd implementations (which are no longer supported). | |
520 * Eventually, all the library path setting will be done here. | |
521 * | |
522 * However, to prevent the proliferation of improperly built native | |
523 * libraries, the new path component /usr/java/packages is added here. | |
524 * Eventually, all the library path setting will be done here. | |
525 */ | |
526 { | |
527 char *ld_library_path; | |
528 | |
529 /* | |
530 * Construct the invariant part of ld_library_path. Note that the | |
531 * space for the colon and the trailing null are provided by the | |
532 * nulls included by the sizeof operator (so actually we allocate | |
533 * a byte more than necessary). | |
534 */ | |
4006 | 535 #ifdef __APPLE__ |
536 ld_library_path = (char *) malloc(system_ext_size); | |
537 sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir); | |
538 #else | |
3960 | 539 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") + |
540 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH)); | |
541 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch); | |
4006 | 542 #endif |
3960 | 543 |
544 /* | |
545 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It | |
546 * should always exist (until the legacy problem cited above is | |
547 * addressed). | |
548 */ | |
549 #ifdef __APPLE__ | |
4006 | 550 // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper |
551 char *l = getenv("JAVA_LIBRARY_PATH"); | |
552 if (l != NULL) { | |
553 char *t = ld_library_path; | |
554 /* That's +1 for the colon and +1 for the trailing '\0' */ | |
555 ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1); | |
556 sprintf(ld_library_path, "%s:%s", l, t); | |
557 free(t); | |
558 } | |
559 | |
3960 | 560 char *v = getenv("DYLD_LIBRARY_PATH"); |
561 #else | |
562 char *v = getenv("LD_LIBRARY_PATH"); | |
563 #endif | |
564 if (v != NULL) { | |
565 char *t = ld_library_path; | |
566 /* That's +1 for the colon and +1 for the trailing '\0' */ | |
567 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1); | |
568 sprintf(ld_library_path, "%s:%s", v, t); | |
4006 | 569 free(t); |
3960 | 570 } |
571 Arguments::set_library_path(ld_library_path); | |
572 } | |
573 | |
574 /* | |
575 * Extensions directories. | |
576 * | |
577 * Note that the space for the colon and the trailing null are provided | |
578 * by the nulls included by the sizeof operator (so actually one byte more | |
579 * than necessary is allocated). | |
580 */ | |
581 { | |
4006 | 582 #ifdef __APPLE__ |
583 char *buf = malloc(strlen(Arguments::get_java_home()) + | |
584 sizeof(EXTENSIONS_DIR) + system_ext_size); | |
585 sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" | |
586 SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home()); | |
587 #else | |
3960 | 588 char *buf = malloc(strlen(Arguments::get_java_home()) + |
589 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR)); | |
590 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR, | |
591 Arguments::get_java_home()); | |
4006 | 592 #endif |
593 | |
3960 | 594 Arguments::set_ext_dirs(buf); |
595 } | |
596 | |
597 /* Endorsed standards default directory. */ | |
598 { | |
599 char * buf; | |
600 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR)); | |
601 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); | |
602 Arguments::set_endorsed_dirs(buf); | |
603 } | |
604 } | |
605 | |
4006 | 606 #ifdef __APPLE__ |
607 #undef SYS_EXTENSIONS_DIR | |
608 #endif | |
3960 | 609 #undef malloc |
610 #undef getenv | |
611 #undef EXTENSIONS_DIR | |
612 #undef ENDORSED_DIR | |
613 | |
614 // Done | |
615 return; | |
616 } | |
617 | |
618 //////////////////////////////////////////////////////////////////////////////// | |
619 // breakpoint support | |
620 | |
621 void os::breakpoint() { | |
622 BREAKPOINT; | |
623 } | |
624 | |
625 extern "C" void breakpoint() { | |
626 // use debugger to set breakpoint here | |
627 } | |
628 | |
629 //////////////////////////////////////////////////////////////////////////////// | |
630 // signal support | |
631 | |
632 debug_only(static bool signal_sets_initialized = false); | |
633 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; | |
634 | |
635 bool os::Bsd::is_sig_ignored(int sig) { | |
636 struct sigaction oact; | |
637 sigaction(sig, (struct sigaction*)NULL, &oact); | |
638 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) | |
639 : CAST_FROM_FN_PTR(void*, oact.sa_handler); | |
640 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) | |
641 return true; | |
642 else | |
643 return false; | |
644 } | |
645 | |
646 void os::Bsd::signal_sets_init() { | |
647 // Should also have an assertion stating we are still single-threaded. | |
648 assert(!signal_sets_initialized, "Already initialized"); | |
649 // Fill in signals that are necessarily unblocked for all threads in | |
650 // the VM. Currently, we unblock the following signals: | |
651 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden | |
652 // by -Xrs (=ReduceSignalUsage)); | |
653 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all | |
654 // other threads. The "ReduceSignalUsage" boolean tells us not to alter | |
655 // the dispositions or masks wrt these signals. | |
656 // Programs embedding the VM that want to use the above signals for their | |
657 // own purposes must, at this time, use the "-Xrs" option to prevent | |
658 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. | |
659 // (See bug 4345157, and other related bugs). | |
660 // In reality, though, unblocking these signals is really a nop, since | |
661 // these signals are not blocked by default. | |
662 sigemptyset(&unblocked_sigs); | |
663 sigemptyset(&allowdebug_blocked_sigs); | |
664 sigaddset(&unblocked_sigs, SIGILL); | |
665 sigaddset(&unblocked_sigs, SIGSEGV); | |
666 sigaddset(&unblocked_sigs, SIGBUS); | |
667 sigaddset(&unblocked_sigs, SIGFPE); | |
668 sigaddset(&unblocked_sigs, SR_signum); | |
669 | |
670 if (!ReduceSignalUsage) { | |
671 if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) { | |
672 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); | |
673 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); | |
674 } | |
675 if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) { | |
676 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); | |
677 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); | |
678 } | |
679 if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) { | |
680 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); | |
681 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); | |
682 } | |
683 } | |
684 // Fill in signals that are blocked by all but the VM thread. | |
685 sigemptyset(&vm_sigs); | |
686 if (!ReduceSignalUsage) | |
687 sigaddset(&vm_sigs, BREAK_SIGNAL); | |
688 debug_only(signal_sets_initialized = true); | |
689 | |
690 } | |
691 | |
692 // These are signals that are unblocked while a thread is running Java. | |
693 // (For some reason, they get blocked by default.) | |
694 sigset_t* os::Bsd::unblocked_signals() { | |
695 assert(signal_sets_initialized, "Not initialized"); | |
696 return &unblocked_sigs; | |
697 } | |
698 | |
699 // These are the signals that are blocked while a (non-VM) thread is | |
700 // running Java. Only the VM thread handles these signals. | |
701 sigset_t* os::Bsd::vm_signals() { | |
702 assert(signal_sets_initialized, "Not initialized"); | |
703 return &vm_sigs; | |
704 } | |
705 | |
706 // These are signals that are blocked during cond_wait to allow debugger in | |
707 sigset_t* os::Bsd::allowdebug_blocked_signals() { | |
708 assert(signal_sets_initialized, "Not initialized"); | |
709 return &allowdebug_blocked_sigs; | |
710 } | |
711 | |
712 void os::Bsd::hotspot_sigmask(Thread* thread) { | |
713 | |
714 //Save caller's signal mask before setting VM signal mask | |
715 sigset_t caller_sigmask; | |
716 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); | |
717 | |
718 OSThread* osthread = thread->osthread(); | |
719 osthread->set_caller_sigmask(caller_sigmask); | |
720 | |
721 pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL); | |
722 | |
723 if (!ReduceSignalUsage) { | |
724 if (thread->is_VM_thread()) { | |
725 // Only the VM thread handles BREAK_SIGNAL ... | |
726 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); | |
727 } else { | |
728 // ... all other threads block BREAK_SIGNAL | |
729 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); | |
730 } | |
731 } | |
732 } | |
733 | |
734 #ifndef _ALLBSD_SOURCE | |
735 ////////////////////////////////////////////////////////////////////////////// | |
736 // detecting pthread library | |
737 | |
738 void os::Bsd::libpthread_init() { | |
739 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION | |
740 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a | |
741 // generic name for earlier versions. | |
742 // Define macros here so we can build HotSpot on old systems. | |
743 # ifndef _CS_GNU_LIBC_VERSION | |
744 # define _CS_GNU_LIBC_VERSION 2 | |
745 # endif | |
746 # ifndef _CS_GNU_LIBPTHREAD_VERSION | |
747 # define _CS_GNU_LIBPTHREAD_VERSION 3 | |
748 # endif | |
749 | |
750 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0); | |
751 if (n > 0) { | |
752 char *str = (char *)malloc(n); | |
753 confstr(_CS_GNU_LIBC_VERSION, str, n); | |
754 os::Bsd::set_glibc_version(str); | |
755 } else { | |
756 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version() | |
757 static char _gnu_libc_version[32]; | |
758 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), | |
759 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release()); | |
760 os::Bsd::set_glibc_version(_gnu_libc_version); | |
761 } | |
762 | |
763 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0); | |
764 if (n > 0) { | |
765 char *str = (char *)malloc(n); | |
766 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n); | |
767 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells | |
768 // us "NPTL-0.29" even we are running with BsdThreads. Check if this | |
769 // is the case. BsdThreads has a hard limit on max number of threads. | |
770 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value. | |
771 // On the other hand, NPTL does not have such a limit, sysconf() | |
772 // will return -1 and errno is not changed. Check if it is really NPTL. | |
773 if (strcmp(os::Bsd::glibc_version(), "glibc 2.3.2") == 0 && | |
774 strstr(str, "NPTL") && | |
775 sysconf(_SC_THREAD_THREADS_MAX) > 0) { | |
776 free(str); | |
777 os::Bsd::set_libpthread_version("bsdthreads"); | |
778 } else { | |
779 os::Bsd::set_libpthread_version(str); | |
780 } | |
781 } else { | |
782 // glibc before 2.3.2 only has BsdThreads. | |
783 os::Bsd::set_libpthread_version("bsdthreads"); | |
784 } | |
785 | |
786 if (strstr(libpthread_version(), "NPTL")) { | |
787 os::Bsd::set_is_NPTL(); | |
788 } else { | |
789 os::Bsd::set_is_BsdThreads(); | |
790 } | |
791 | |
792 // BsdThreads have two flavors: floating-stack mode, which allows variable | |
793 // stack size; and fixed-stack mode. NPTL is always floating-stack. | |
794 if (os::Bsd::is_NPTL() || os::Bsd::supports_variable_stack_size()) { | |
795 os::Bsd::set_is_floating_stack(); | |
796 } | |
797 } | |
798 | |
799 ///////////////////////////////////////////////////////////////////////////// | |
800 // thread stack | |
801 | |
802 // Force Bsd kernel to expand current thread stack. If "bottom" is close | |
803 // to the stack guard, caller should block all signals. | |
804 // | |
805 // MAP_GROWSDOWN: | |
806 // A special mmap() flag that is used to implement thread stacks. It tells | |
807 // kernel that the memory region should extend downwards when needed. This | |
808 // allows early versions of BsdThreads to only mmap the first few pages | |
809 // when creating a new thread. Bsd kernel will automatically expand thread | |
810 // stack as needed (on page faults). | |
811 // | |
812 // However, because the memory region of a MAP_GROWSDOWN stack can grow on | |
813 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN | |
814 // region, it's hard to tell if the fault is due to a legitimate stack | |
815 // access or because of reading/writing non-exist memory (e.g. buffer | |
816 // overrun). As a rule, if the fault happens below current stack pointer, | |
817 // Bsd kernel does not expand stack, instead a SIGSEGV is sent to the | |
818 // application (see Bsd kernel fault.c). | |
819 // | |
820 // This Bsd feature can cause SIGSEGV when VM bangs thread stack for | |
821 // stack overflow detection. | |
822 // | |
823 // Newer version of BsdThreads (since glibc-2.2, or, RH-7.x) and NPTL do | |
824 // not use this flag. However, the stack of initial thread is not created | |
825 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though | |
826 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack | |
827 // and then attach the thread to JVM. | |
828 // | |
829 // To get around the problem and allow stack banging on Bsd, we need to | |
830 // manually expand thread stack after receiving the SIGSEGV. | |
831 // | |
832 // There are two ways to expand thread stack to address "bottom", we used | |
833 // both of them in JVM before 1.5: | |
834 // 1. adjust stack pointer first so that it is below "bottom", and then | |
835 // touch "bottom" | |
836 // 2. mmap() the page in question | |
837 // | |
838 // Now alternate signal stack is gone, it's harder to use 2. For instance, | |
839 // if current sp is already near the lower end of page 101, and we need to | |
840 // call mmap() to map page 100, it is possible that part of the mmap() frame | |
841 // will be placed in page 100. When page 100 is mapped, it is zero-filled. | |
842 // That will destroy the mmap() frame and cause VM to crash. | |
843 // | |
844 // The following code works by adjusting sp first, then accessing the "bottom" | |
845 // page to force a page fault. Bsd kernel will then automatically expand the | |
846 // stack mapping. | |
847 // | |
848 // _expand_stack_to() assumes its frame size is less than page size, which | |
849 // should always be true if the function is not inlined. | |
850 | |
851 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute | |
852 #define NOINLINE | |
853 #else | |
854 #define NOINLINE __attribute__ ((noinline)) | |
855 #endif | |
856 | |
857 static void _expand_stack_to(address bottom) NOINLINE; | |
858 | |
859 static void _expand_stack_to(address bottom) { | |
860 address sp; | |
861 size_t size; | |
862 volatile char *p; | |
863 | |
864 // Adjust bottom to point to the largest address within the same page, it | |
865 // gives us a one-page buffer if alloca() allocates slightly more memory. | |
866 bottom = (address)align_size_down((uintptr_t)bottom, os::Bsd::page_size()); | |
867 bottom += os::Bsd::page_size() - 1; | |
868 | |
869 // sp might be slightly above current stack pointer; if that's the case, we | |
870 // will alloca() a little more space than necessary, which is OK. Don't use | |
871 // os::current_stack_pointer(), as its result can be slightly below current | |
872 // stack pointer, causing us to not alloca enough to reach "bottom". | |
873 sp = (address)&sp; | |
874 | |
875 if (sp > bottom) { | |
876 size = sp - bottom; | |
877 p = (volatile char *)alloca(size); | |
878 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?"); | |
879 p[0] = '\0'; | |
880 } | |
881 } | |
882 | |
883 bool os::Bsd::manually_expand_stack(JavaThread * t, address addr) { | |
884 assert(t!=NULL, "just checking"); | |
885 assert(t->osthread()->expanding_stack(), "expand should be set"); | |
886 assert(t->stack_base() != NULL, "stack_base was not initialized"); | |
887 | |
888 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) { | |
889 sigset_t mask_all, old_sigset; | |
890 sigfillset(&mask_all); | |
891 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset); | |
892 _expand_stack_to(addr); | |
893 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); | |
894 return true; | |
895 } | |
896 return false; | |
897 } | |
898 #endif | |
899 | |
900 ////////////////////////////////////////////////////////////////////////////// | |
901 // create new thread | |
902 | |
903 static address highest_vm_reserved_address(); | |
904 | |
905 // check if it's safe to start a new thread | |
906 static bool _thread_safety_check(Thread* thread) { | |
907 #ifdef _ALLBSD_SOURCE | |
908 return true; | |
909 #else | |
910 if (os::Bsd::is_BsdThreads() && !os::Bsd::is_floating_stack()) { | |
911 // Fixed stack BsdThreads (SuSE Bsd/x86, and some versions of Redhat) | |
912 // Heap is mmap'ed at lower end of memory space. Thread stacks are | |
913 // allocated (MAP_FIXED) from high address space. Every thread stack | |
914 // occupies a fixed size slot (usually 2Mbytes, but user can change | |
915 // it to other values if they rebuild BsdThreads). | |
916 // | |
917 // Problem with MAP_FIXED is that mmap() can still succeed even part of | |
918 // the memory region has already been mmap'ed. That means if we have too | |
919 // many threads and/or very large heap, eventually thread stack will | |
920 // collide with heap. | |
921 // | |
922 // Here we try to prevent heap/stack collision by comparing current | |
923 // stack bottom with the highest address that has been mmap'ed by JVM | |
924 // plus a safety margin for memory maps created by native code. | |
925 // | |
926 // This feature can be disabled by setting ThreadSafetyMargin to 0 | |
927 // | |
928 if (ThreadSafetyMargin > 0) { | |
929 address stack_bottom = os::current_stack_base() - os::current_stack_size(); | |
930 | |
931 // not safe if our stack extends below the safety margin | |
932 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address(); | |
933 } else { | |
934 return true; | |
935 } | |
936 } else { | |
937 // Floating stack BsdThreads or NPTL: | |
938 // Unlike fixed stack BsdThreads, thread stacks are not MAP_FIXED. When | |
939 // there's not enough space left, pthread_create() will fail. If we come | |
940 // here, that means enough space has been reserved for stack. | |
941 return true; | |
942 } | |
943 #endif | |
944 } | |
945 | |
4006 | 946 #ifdef __APPLE__ |
947 // library handle for calling objc_registerThreadWithCollector() | |
948 // without static linking to the libobjc library | |
949 #define OBJC_LIB "/usr/lib/libobjc.dylib" | |
950 #define OBJC_GCREGISTER "objc_registerThreadWithCollector" | |
951 typedef void (*objc_registerThreadWithCollector_t)(); | |
952 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction; | |
953 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL; | |
954 #endif | |
955 | |
3960 | 956 // Thread start routine for all newly created threads |
957 static void *java_start(Thread *thread) { | |
958 // Try to randomize the cache line index of hot stack frames. | |
959 // This helps when threads of the same stack traces evict each other's | |
960 // cache lines. The threads can be either from the same JVM instance, or | |
961 // from different JVM instances. The benefit is especially true for | |
962 // processors with hyperthreading technology. | |
963 static int counter = 0; | |
964 int pid = os::current_process_id(); | |
965 alloca(((pid ^ counter++) & 7) * 128); | |
966 | |
967 ThreadLocalStorage::set_thread(thread); | |
968 | |
969 OSThread* osthread = thread->osthread(); | |
970 Monitor* sync = osthread->startThread_lock(); | |
971 | |
972 // non floating stack BsdThreads needs extra check, see above | |
973 if (!_thread_safety_check(thread)) { | |
974 // notify parent thread | |
975 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); | |
976 osthread->set_state(ZOMBIE); | |
977 sync->notify_all(); | |
978 return NULL; | |
979 } | |
980 | |
981 #ifdef _ALLBSD_SOURCE | |
982 // thread_id is pthread_id on BSD | |
983 osthread->set_thread_id(::pthread_self()); | |
984 #else | |
985 // thread_id is kernel thread id (similar to Solaris LWP id) | |
986 osthread->set_thread_id(os::Bsd::gettid()); | |
987 | |
988 if (UseNUMA) { | |
989 int lgrp_id = os::numa_get_group_id(); | |
990 if (lgrp_id != -1) { | |
991 thread->set_lgrp_id(lgrp_id); | |
992 } | |
993 } | |
994 #endif | |
995 // initialize signal mask for this thread | |
996 os::Bsd::hotspot_sigmask(thread); | |
997 | |
998 // initialize floating point control register | |
999 os::Bsd::init_thread_fpu_state(); | |
1000 | |
4006 | 1001 #ifdef __APPLE__ |
1002 // register thread with objc gc | |
1003 if (objc_registerThreadWithCollectorFunction != NULL) { | |
1004 objc_registerThreadWithCollectorFunction(); | |
1005 } | |
1006 #endif | |
1007 | |
3960 | 1008 // handshaking with parent thread |
1009 { | |
1010 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); | |
1011 | |
1012 // notify parent thread | |
1013 osthread->set_state(INITIALIZED); | |
1014 sync->notify_all(); | |
1015 | |
1016 // wait until os::start_thread() | |
1017 while (osthread->get_state() == INITIALIZED) { | |
1018 sync->wait(Mutex::_no_safepoint_check_flag); | |
1019 } | |
1020 } | |
1021 | |
1022 // call one more level start routine | |
1023 thread->run(); | |
1024 | |
1025 return 0; | |
1026 } | |
1027 | |
1028 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { | |
1029 assert(thread->osthread() == NULL, "caller responsible"); | |
1030 | |
1031 // Allocate the OSThread object | |
1032 OSThread* osthread = new OSThread(NULL, NULL); | |
1033 if (osthread == NULL) { | |
1034 return false; | |
1035 } | |
1036 | |
1037 // set the correct thread state | |
1038 osthread->set_thread_type(thr_type); | |
1039 | |
1040 // Initial state is ALLOCATED but not INITIALIZED | |
1041 osthread->set_state(ALLOCATED); | |
1042 | |
1043 thread->set_osthread(osthread); | |
1044 | |
1045 // init thread attributes | |
1046 pthread_attr_t attr; | |
1047 pthread_attr_init(&attr); | |
1048 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); | |
1049 | |
1050 // stack size | |
1051 if (os::Bsd::supports_variable_stack_size()) { | |
1052 // calculate stack size if it's not specified by caller | |
1053 if (stack_size == 0) { | |
1054 stack_size = os::Bsd::default_stack_size(thr_type); | |
1055 | |
1056 switch (thr_type) { | |
1057 case os::java_thread: | |
1058 // Java threads use ThreadStackSize which default value can be | |
1059 // changed with the flag -Xss | |
1060 assert (JavaThread::stack_size_at_create() > 0, "this should be set"); | |
1061 stack_size = JavaThread::stack_size_at_create(); | |
1062 break; | |
1063 case os::compiler_thread: | |
1064 if (CompilerThreadStackSize > 0) { | |
1065 stack_size = (size_t)(CompilerThreadStackSize * K); | |
1066 break; | |
1067 } // else fall through: | |
1068 // use VMThreadStackSize if CompilerThreadStackSize is not defined | |
1069 case os::vm_thread: | |
1070 case os::pgc_thread: | |
1071 case os::cgc_thread: | |
1072 case os::watcher_thread: | |
1073 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); | |
1074 break; | |
1075 } | |
1076 } | |
1077 | |
1078 stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed); | |
1079 pthread_attr_setstacksize(&attr, stack_size); | |
1080 } else { | |
1081 // let pthread_create() pick the default value. | |
1082 } | |
1083 | |
1084 #ifndef _ALLBSD_SOURCE | |
1085 // glibc guard page | |
1086 pthread_attr_setguardsize(&attr, os::Bsd::default_guard_size(thr_type)); | |
1087 #endif | |
1088 | |
1089 ThreadState state; | |
1090 | |
1091 { | |
1092 | |
1093 #ifndef _ALLBSD_SOURCE | |
1094 // Serialize thread creation if we are running with fixed stack BsdThreads | |
1095 bool lock = os::Bsd::is_BsdThreads() && !os::Bsd::is_floating_stack(); | |
1096 if (lock) { | |
1097 os::Bsd::createThread_lock()->lock_without_safepoint_check(); | |
1098 } | |
1099 #endif | |
1100 | |
1101 pthread_t tid; | |
1102 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); | |
1103 | |
1104 pthread_attr_destroy(&attr); | |
1105 | |
1106 if (ret != 0) { | |
1107 if (PrintMiscellaneous && (Verbose || WizardMode)) { | |
1108 perror("pthread_create()"); | |
1109 } | |
1110 // Need to clean up stuff we've allocated so far | |
1111 thread->set_osthread(NULL); | |
1112 delete osthread; | |
1113 #ifndef _ALLBSD_SOURCE | |
1114 if (lock) os::Bsd::createThread_lock()->unlock(); | |
1115 #endif | |
1116 return false; | |
1117 } | |
1118 | |
1119 // Store pthread info into the OSThread | |
1120 osthread->set_pthread_id(tid); | |
1121 | |
1122 // Wait until child thread is either initialized or aborted | |
1123 { | |
1124 Monitor* sync_with_child = osthread->startThread_lock(); | |
1125 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); | |
1126 while ((state = osthread->get_state()) == ALLOCATED) { | |
1127 sync_with_child->wait(Mutex::_no_safepoint_check_flag); | |
1128 } | |
1129 } | |
1130 | |
1131 #ifndef _ALLBSD_SOURCE | |
1132 if (lock) { | |
1133 os::Bsd::createThread_lock()->unlock(); | |
1134 } | |
1135 #endif | |
1136 } | |
1137 | |
1138 // Aborted due to thread limit being reached | |
1139 if (state == ZOMBIE) { | |
1140 thread->set_osthread(NULL); | |
1141 delete osthread; | |
1142 return false; | |
1143 } | |
1144 | |
1145 // The thread is returned suspended (in state INITIALIZED), | |
1146 // and is started higher up in the call chain | |
1147 assert(state == INITIALIZED, "race condition"); | |
1148 return true; | |
1149 } | |
1150 | |
1151 ///////////////////////////////////////////////////////////////////////////// | |
1152 // attach existing thread | |
1153 | |
1154 // bootstrap the main thread | |
1155 bool os::create_main_thread(JavaThread* thread) { | |
1156 assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread"); | |
1157 return create_attached_thread(thread); | |
1158 } | |
1159 | |
1160 bool os::create_attached_thread(JavaThread* thread) { | |
1161 #ifdef ASSERT | |
1162 thread->verify_not_published(); | |
1163 #endif | |
1164 | |
1165 // Allocate the OSThread object | |
1166 OSThread* osthread = new OSThread(NULL, NULL); | |
1167 | |
1168 if (osthread == NULL) { | |
1169 return false; | |
1170 } | |
1171 | |
1172 // Store pthread info into the OSThread | |
1173 #ifdef _ALLBSD_SOURCE | |
1174 osthread->set_thread_id(::pthread_self()); | |
1175 #else | |
1176 osthread->set_thread_id(os::Bsd::gettid()); | |
1177 #endif | |
1178 osthread->set_pthread_id(::pthread_self()); | |
1179 | |
1180 // initialize floating point control register | |
1181 os::Bsd::init_thread_fpu_state(); | |
1182 | |
1183 // Initial thread state is RUNNABLE | |
1184 osthread->set_state(RUNNABLE); | |
1185 | |
1186 thread->set_osthread(osthread); | |
1187 | |
1188 #ifndef _ALLBSD_SOURCE | |
1189 if (UseNUMA) { | |
1190 int lgrp_id = os::numa_get_group_id(); | |
1191 if (lgrp_id != -1) { | |
1192 thread->set_lgrp_id(lgrp_id); | |
1193 } | |
1194 } | |
1195 | |
1196 if (os::Bsd::is_initial_thread()) { | |
1197 // If current thread is initial thread, its stack is mapped on demand, | |
1198 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map | |
1199 // the entire stack region to avoid SEGV in stack banging. | |
1200 // It is also useful to get around the heap-stack-gap problem on SuSE | |
1201 // kernel (see 4821821 for details). We first expand stack to the top | |
1202 // of yellow zone, then enable stack yellow zone (order is significant, | |
1203 // enabling yellow zone first will crash JVM on SuSE Bsd), so there | |
1204 // is no gap between the last two virtual memory regions. | |
1205 | |
1206 JavaThread *jt = (JavaThread *)thread; | |
1207 address addr = jt->stack_yellow_zone_base(); | |
1208 assert(addr != NULL, "initialization problem?"); | |
1209 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled"); | |
1210 | |
1211 osthread->set_expanding_stack(); | |
1212 os::Bsd::manually_expand_stack(jt, addr); | |
1213 osthread->clear_expanding_stack(); | |
1214 } | |
1215 #endif | |
1216 | |
1217 // initialize signal mask for this thread | |
1218 // and save the caller's signal mask | |
1219 os::Bsd::hotspot_sigmask(thread); | |
1220 | |
1221 return true; | |
1222 } | |
1223 | |
1224 void os::pd_start_thread(Thread* thread) { | |
1225 OSThread * osthread = thread->osthread(); | |
1226 assert(osthread->get_state() != INITIALIZED, "just checking"); | |
1227 Monitor* sync_with_child = osthread->startThread_lock(); | |
1228 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); | |
1229 sync_with_child->notify(); | |
1230 } | |
1231 | |
1232 // Free Bsd resources related to the OSThread | |
1233 void os::free_thread(OSThread* osthread) { | |
1234 assert(osthread != NULL, "osthread not set"); | |
1235 | |
1236 if (Thread::current()->osthread() == osthread) { | |
1237 // Restore caller's signal mask | |
1238 sigset_t sigmask = osthread->caller_sigmask(); | |
1239 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); | |
1240 } | |
1241 | |
1242 delete osthread; | |
1243 } | |
1244 | |
1245 ////////////////////////////////////////////////////////////////////////////// | |
1246 // thread local storage | |
1247 | |
1248 int os::allocate_thread_local_storage() { | |
1249 pthread_key_t key; | |
1250 int rslt = pthread_key_create(&key, NULL); | |
1251 assert(rslt == 0, "cannot allocate thread local storage"); | |
1252 return (int)key; | |
1253 } | |
1254 | |
1255 // Note: This is currently not used by VM, as we don't destroy TLS key | |
1256 // on VM exit. | |
1257 void os::free_thread_local_storage(int index) { | |
1258 int rslt = pthread_key_delete((pthread_key_t)index); | |
1259 assert(rslt == 0, "invalid index"); | |
1260 } | |
1261 | |
1262 void os::thread_local_storage_at_put(int index, void* value) { | |
1263 int rslt = pthread_setspecific((pthread_key_t)index, value); | |
1264 assert(rslt == 0, "pthread_setspecific failed"); | |
1265 } | |
1266 | |
1267 extern "C" Thread* get_thread() { | |
1268 return ThreadLocalStorage::thread(); | |
1269 } | |
1270 | |
1271 ////////////////////////////////////////////////////////////////////////////// | |
1272 // initial thread | |
1273 | |
1274 #ifndef _ALLBSD_SOURCE | |
1275 // Check if current thread is the initial thread, similar to Solaris thr_main. | |
1276 bool os::Bsd::is_initial_thread(void) { | |
1277 char dummy; | |
1278 // If called before init complete, thread stack bottom will be null. | |
1279 // Can be called if fatal error occurs before initialization. | |
1280 if (initial_thread_stack_bottom() == NULL) return false; | |
1281 assert(initial_thread_stack_bottom() != NULL && | |
1282 initial_thread_stack_size() != 0, | |
1283 "os::init did not locate initial thread's stack region"); | |
1284 if ((address)&dummy >= initial_thread_stack_bottom() && | |
1285 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) | |
1286 return true; | |
1287 else return false; | |
1288 } | |
1289 | |
1290 // Find the virtual memory area that contains addr | |
1291 static bool find_vma(address addr, address* vma_low, address* vma_high) { | |
1292 FILE *fp = fopen("/proc/self/maps", "r"); | |
1293 if (fp) { | |
1294 address low, high; | |
1295 while (!feof(fp)) { | |
1296 if (fscanf(fp, "%p-%p", &low, &high) == 2) { | |
1297 if (low <= addr && addr < high) { | |
1298 if (vma_low) *vma_low = low; | |
1299 if (vma_high) *vma_high = high; | |
1300 fclose (fp); | |
1301 return true; | |
1302 } | |
1303 } | |
1304 for (;;) { | |
1305 int ch = fgetc(fp); | |
1306 if (ch == EOF || ch == (int)'\n') break; | |
1307 } | |
1308 } | |
1309 fclose(fp); | |
1310 } | |
1311 return false; | |
1312 } | |
1313 | |
1314 // Locate initial thread stack. This special handling of initial thread stack | |
1315 // is needed because pthread_getattr_np() on most (all?) Bsd distros returns | |
1316 // bogus value for initial thread. | |
1317 void os::Bsd::capture_initial_stack(size_t max_size) { | |
1318 // stack size is the easy part, get it from RLIMIT_STACK | |
1319 size_t stack_size; | |
1320 struct rlimit rlim; | |
1321 getrlimit(RLIMIT_STACK, &rlim); | |
1322 stack_size = rlim.rlim_cur; | |
1323 | |
1324 // 6308388: a bug in ld.so will relocate its own .data section to the | |
1325 // lower end of primordial stack; reduce ulimit -s value a little bit | |
1326 // so we won't install guard page on ld.so's data section. | |
1327 stack_size -= 2 * page_size(); | |
1328 | |
1329 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat | |
1330 // 7.1, in both cases we will get 2G in return value. | |
1331 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0, | |
1332 // SuSE 7.2, Debian) can not handle alternate signal stack correctly | |
1333 // for initial thread if its stack size exceeds 6M. Cap it at 2M, | |
1334 // in case other parts in glibc still assumes 2M max stack size. | |
1335 // FIXME: alt signal stack is gone, maybe we can relax this constraint? | |
1336 #ifndef IA64 | |
1337 if (stack_size > 2 * K * K) stack_size = 2 * K * K; | |
1338 #else | |
1339 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small | |
1340 if (stack_size > 4 * K * K) stack_size = 4 * K * K; | |
1341 #endif | |
1342 | |
1343 // Try to figure out where the stack base (top) is. This is harder. | |
1344 // | |
1345 // When an application is started, glibc saves the initial stack pointer in | |
1346 // a global variable "__libc_stack_end", which is then used by system | |
1347 // libraries. __libc_stack_end should be pretty close to stack top. The | |
1348 // variable is available since the very early days. However, because it is | |
1349 // a private interface, it could disappear in the future. | |
1350 // | |
1351 // Bsd kernel saves start_stack information in /proc/<pid>/stat. Similar | |
1352 // to __libc_stack_end, it is very close to stack top, but isn't the real | |
1353 // stack top. Note that /proc may not exist if VM is running as a chroot | |
1354 // program, so reading /proc/<pid>/stat could fail. Also the contents of | |
1355 // /proc/<pid>/stat could change in the future (though unlikely). | |
1356 // | |
1357 // We try __libc_stack_end first. If that doesn't work, look for | |
1358 // /proc/<pid>/stat. If neither of them works, we use current stack pointer | |
1359 // as a hint, which should work well in most cases. | |
1360 | |
1361 uintptr_t stack_start; | |
1362 | |
1363 // try __libc_stack_end first | |
1364 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end"); | |
1365 if (p && *p) { | |
1366 stack_start = *p; | |
1367 } else { | |
1368 // see if we can get the start_stack field from /proc/self/stat | |
1369 FILE *fp; | |
1370 int pid; | |
1371 char state; | |
1372 int ppid; | |
1373 int pgrp; | |
1374 int session; | |
1375 int nr; | |
1376 int tpgrp; | |
1377 unsigned long flags; | |
1378 unsigned long minflt; | |
1379 unsigned long cminflt; | |
1380 unsigned long majflt; | |
1381 unsigned long cmajflt; | |
1382 unsigned long utime; | |
1383 unsigned long stime; | |
1384 long cutime; | |
1385 long cstime; | |
1386 long prio; | |
1387 long nice; | |
1388 long junk; | |
1389 long it_real; | |
1390 uintptr_t start; | |
1391 uintptr_t vsize; | |
1392 intptr_t rss; | |
1393 uintptr_t rsslim; | |
1394 uintptr_t scodes; | |
1395 uintptr_t ecode; | |
1396 int i; | |
1397 | |
1398 // Figure what the primordial thread stack base is. Code is inspired | |
1399 // by email from Hans Boehm. /proc/self/stat begins with current pid, | |
1400 // followed by command name surrounded by parentheses, state, etc. | |
1401 char stat[2048]; | |
1402 int statlen; | |
1403 | |
1404 fp = fopen("/proc/self/stat", "r"); | |
1405 if (fp) { | |
1406 statlen = fread(stat, 1, 2047, fp); | |
1407 stat[statlen] = '\0'; | |
1408 fclose(fp); | |
1409 | |
1410 // Skip pid and the command string. Note that we could be dealing with | |
1411 // weird command names, e.g. user could decide to rename java launcher | |
1412 // to "java 1.4.2 :)", then the stat file would look like | |
1413 // 1234 (java 1.4.2 :)) R ... ... | |
1414 // We don't really need to know the command string, just find the last | |
1415 // occurrence of ")" and then start parsing from there. See bug 4726580. | |
1416 char * s = strrchr(stat, ')'); | |
1417 | |
1418 i = 0; | |
1419 if (s) { | |
1420 // Skip blank chars | |
1421 do s++; while (isspace(*s)); | |
1422 | |
1423 #define _UFM UINTX_FORMAT | |
1424 #define _DFM INTX_FORMAT | |
1425 | |
1426 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */ | |
1427 /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */ | |
1428 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM, | |
1429 &state, /* 3 %c */ | |
1430 &ppid, /* 4 %d */ | |
1431 &pgrp, /* 5 %d */ | |
1432 &session, /* 6 %d */ | |
1433 &nr, /* 7 %d */ | |
1434 &tpgrp, /* 8 %d */ | |
1435 &flags, /* 9 %lu */ | |
1436 &minflt, /* 10 %lu */ | |
1437 &cminflt, /* 11 %lu */ | |
1438 &majflt, /* 12 %lu */ | |
1439 &cmajflt, /* 13 %lu */ | |
1440 &utime, /* 14 %lu */ | |
1441 &stime, /* 15 %lu */ | |
1442 &cutime, /* 16 %ld */ | |
1443 &cstime, /* 17 %ld */ | |
1444 &prio, /* 18 %ld */ | |
1445 &nice, /* 19 %ld */ | |
1446 &junk, /* 20 %ld */ | |
1447 &it_real, /* 21 %ld */ | |
1448 &start, /* 22 UINTX_FORMAT */ | |
1449 &vsize, /* 23 UINTX_FORMAT */ | |
1450 &rss, /* 24 INTX_FORMAT */ | |
1451 &rsslim, /* 25 UINTX_FORMAT */ | |
1452 &scodes, /* 26 UINTX_FORMAT */ | |
1453 &ecode, /* 27 UINTX_FORMAT */ | |
1454 &stack_start); /* 28 UINTX_FORMAT */ | |
1455 } | |
1456 | |
1457 #undef _UFM | |
1458 #undef _DFM | |
1459 | |
1460 if (i != 28 - 2) { | |
1461 assert(false, "Bad conversion from /proc/self/stat"); | |
1462 // product mode - assume we are the initial thread, good luck in the | |
1463 // embedded case. | |
1464 warning("Can't detect initial thread stack location - bad conversion"); | |
1465 stack_start = (uintptr_t) &rlim; | |
1466 } | |
1467 } else { | |
1468 // For some reason we can't open /proc/self/stat (for example, running on | |
1469 // FreeBSD with a Bsd emulator, or inside chroot), this should work for | |
1470 // most cases, so don't abort: | |
1471 warning("Can't detect initial thread stack location - no /proc/self/stat"); | |
1472 stack_start = (uintptr_t) &rlim; | |
1473 } | |
1474 } | |
1475 | |
1476 // Now we have a pointer (stack_start) very close to the stack top, the | |
1477 // next thing to do is to figure out the exact location of stack top. We | |
1478 // can find out the virtual memory area that contains stack_start by | |
1479 // reading /proc/self/maps, it should be the last vma in /proc/self/maps, | |
1480 // and its upper limit is the real stack top. (again, this would fail if | |
1481 // running inside chroot, because /proc may not exist.) | |
1482 | |
1483 uintptr_t stack_top; | |
1484 address low, high; | |
1485 if (find_vma((address)stack_start, &low, &high)) { | |
1486 // success, "high" is the true stack top. (ignore "low", because initial | |
1487 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.) | |
1488 stack_top = (uintptr_t)high; | |
1489 } else { | |
1490 // failed, likely because /proc/self/maps does not exist | |
1491 warning("Can't detect initial thread stack location - find_vma failed"); | |
1492 // best effort: stack_start is normally within a few pages below the real | |
1493 // stack top, use it as stack top, and reduce stack size so we won't put | |
1494 // guard page outside stack. | |
1495 stack_top = stack_start; | |
1496 stack_size -= 16 * page_size(); | |
1497 } | |
1498 | |
1499 // stack_top could be partially down the page so align it | |
1500 stack_top = align_size_up(stack_top, page_size()); | |
1501 | |
1502 if (max_size && stack_size > max_size) { | |
1503 _initial_thread_stack_size = max_size; | |
1504 } else { | |
1505 _initial_thread_stack_size = stack_size; | |
1506 } | |
1507 | |
1508 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size()); | |
1509 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size; | |
1510 } | |
1511 #endif | |
1512 | |
1513 //////////////////////////////////////////////////////////////////////////////// | |
1514 // time support | |
1515 | |
1516 // Time since start-up in seconds to a fine granularity. | |
1517 // Used by VMSelfDestructTimer and the MemProfiler. | |
1518 double os::elapsedTime() { | |
1519 | |
1520 return (double)(os::elapsed_counter()) * 0.000001; | |
1521 } | |
1522 | |
1523 jlong os::elapsed_counter() { | |
1524 timeval time; | |
1525 int status = gettimeofday(&time, NULL); | |
1526 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count; | |
1527 } | |
1528 | |
1529 jlong os::elapsed_frequency() { | |
1530 return (1000 * 1000); | |
1531 } | |
1532 | |
1533 // XXX: For now, code this as if BSD does not support vtime. | |
1534 bool os::supports_vtime() { return false; } | |
1535 bool os::enable_vtime() { return false; } | |
1536 bool os::vtime_enabled() { return false; } | |
1537 double os::elapsedVTime() { | |
1538 // better than nothing, but not much | |
1539 return elapsedTime(); | |
1540 } | |
1541 | |
1542 jlong os::javaTimeMillis() { | |
1543 timeval time; | |
1544 int status = gettimeofday(&time, NULL); | |
1545 assert(status != -1, "bsd error"); | |
1546 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); | |
1547 } | |
1548 | |
1549 #ifndef CLOCK_MONOTONIC | |
1550 #define CLOCK_MONOTONIC (1) | |
1551 #endif | |
1552 | |
1553 #ifdef __APPLE__ | |
1554 void os::Bsd::clock_init() { | |
1555 // XXXDARWIN: Investigate replacement monotonic clock | |
1556 } | |
1557 #elif defined(_ALLBSD_SOURCE) | |
1558 void os::Bsd::clock_init() { | |
1559 struct timespec res; | |
1560 struct timespec tp; | |
1561 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 && | |
1562 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) { | |
1563 // yes, monotonic clock is supported | |
1564 _clock_gettime = ::clock_gettime; | |
1565 } | |
1566 } | |
1567 #else | |
1568 void os::Bsd::clock_init() { | |
1569 // we do dlopen's in this particular order due to bug in bsd | |
1570 // dynamical loader (see 6348968) leading to crash on exit | |
1571 void* handle = dlopen("librt.so.1", RTLD_LAZY); | |
1572 if (handle == NULL) { | |
1573 handle = dlopen("librt.so", RTLD_LAZY); | |
1574 } | |
1575 | |
1576 if (handle) { | |
1577 int (*clock_getres_func)(clockid_t, struct timespec*) = | |
1578 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); | |
1579 int (*clock_gettime_func)(clockid_t, struct timespec*) = | |
1580 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); | |
1581 if (clock_getres_func && clock_gettime_func) { | |
1582 // See if monotonic clock is supported by the kernel. Note that some | |
1583 // early implementations simply return kernel jiffies (updated every | |
1584 // 1/100 or 1/1000 second). It would be bad to use such a low res clock | |
1585 // for nano time (though the monotonic property is still nice to have). | |
1586 // It's fixed in newer kernels, however clock_getres() still returns | |
1587 // 1/HZ. We check if clock_getres() works, but will ignore its reported | |
1588 // resolution for now. Hopefully as people move to new kernels, this | |
1589 // won't be a problem. | |
1590 struct timespec res; | |
1591 struct timespec tp; | |
1592 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 && | |
1593 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { | |
1594 // yes, monotonic clock is supported | |
1595 _clock_gettime = clock_gettime_func; | |
1596 } else { | |
1597 // close librt if there is no monotonic clock | |
1598 dlclose(handle); | |
1599 } | |
1600 } | |
1601 } | |
1602 } | |
1603 #endif | |
1604 | |
1605 #ifndef _ALLBSD_SOURCE | |
1606 #ifndef SYS_clock_getres | |
1607 | |
1608 #if defined(IA32) || defined(AMD64) | |
1609 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) | |
1610 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) | |
1611 #else | |
1612 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time" | |
1613 #define sys_clock_getres(x,y) -1 | |
1614 #endif | |
1615 | |
1616 #else | |
1617 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) | |
1618 #endif | |
1619 | |
1620 void os::Bsd::fast_thread_clock_init() { | |
1621 if (!UseBsdPosixThreadCPUClocks) { | |
1622 return; | |
1623 } | |
1624 clockid_t clockid; | |
1625 struct timespec tp; | |
1626 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) = | |
1627 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid"); | |
1628 | |
1629 // Switch to using fast clocks for thread cpu time if | |
1630 // the sys_clock_getres() returns 0 error code. | |
1631 // Note, that some kernels may support the current thread | |
1632 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks | |
1633 // returned by the pthread_getcpuclockid(). | |
1634 // If the fast Posix clocks are supported then the sys_clock_getres() | |
1635 // must return at least tp.tv_sec == 0 which means a resolution | |
1636 // better than 1 sec. This is extra check for reliability. | |
1637 | |
1638 if(pthread_getcpuclockid_func && | |
1639 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && | |
1640 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { | |
1641 | |
1642 _supports_fast_thread_cpu_time = true; | |
1643 _pthread_getcpuclockid = pthread_getcpuclockid_func; | |
1644 } | |
1645 } | |
1646 #endif | |
1647 | |
1648 jlong os::javaTimeNanos() { | |
1649 if (Bsd::supports_monotonic_clock()) { | |
1650 struct timespec tp; | |
1651 int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp); | |
1652 assert(status == 0, "gettime error"); | |
1653 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); | |
1654 return result; | |
1655 } else { | |
1656 timeval time; | |
1657 int status = gettimeofday(&time, NULL); | |
1658 assert(status != -1, "bsd error"); | |
1659 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); | |
1660 return 1000 * usecs; | |
1661 } | |
1662 } | |
1663 | |
1664 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { | |
1665 if (Bsd::supports_monotonic_clock()) { | |
1666 info_ptr->max_value = ALL_64_BITS; | |
1667 | |
1668 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past | |
1669 info_ptr->may_skip_backward = false; // not subject to resetting or drifting | |
1670 info_ptr->may_skip_forward = false; // not subject to resetting or drifting | |
1671 } else { | |
1672 // gettimeofday - based on time in seconds since the Epoch thus does not wrap | |
1673 info_ptr->max_value = ALL_64_BITS; | |
1674 | |
1675 // gettimeofday is a real time clock so it skips | |
1676 info_ptr->may_skip_backward = true; | |
1677 info_ptr->may_skip_forward = true; | |
1678 } | |
1679 | |
1680 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time | |
1681 } | |
1682 | |
1683 // Return the real, user, and system times in seconds from an | |
1684 // arbitrary fixed point in the past. | |
1685 bool os::getTimesSecs(double* process_real_time, | |
1686 double* process_user_time, | |
1687 double* process_system_time) { | |
1688 struct tms ticks; | |
1689 clock_t real_ticks = times(&ticks); | |
1690 | |
1691 if (real_ticks == (clock_t) (-1)) { | |
1692 return false; | |
1693 } else { | |
1694 double ticks_per_second = (double) clock_tics_per_sec; | |
1695 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; | |
1696 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; | |
1697 *process_real_time = ((double) real_ticks) / ticks_per_second; | |
1698 | |
1699 return true; | |
1700 } | |
1701 } | |
1702 | |
1703 | |
1704 char * os::local_time_string(char *buf, size_t buflen) { | |
1705 struct tm t; | |
1706 time_t long_time; | |
1707 time(&long_time); | |
1708 localtime_r(&long_time, &t); | |
1709 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", | |
1710 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, | |
1711 t.tm_hour, t.tm_min, t.tm_sec); | |
1712 return buf; | |
1713 } | |
1714 | |
1715 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { | |
1716 return localtime_r(clock, res); | |
1717 } | |
1718 | |
1719 //////////////////////////////////////////////////////////////////////////////// | |
1720 // runtime exit support | |
1721 | |
1722 // Note: os::shutdown() might be called very early during initialization, or | |
1723 // called from signal handler. Before adding something to os::shutdown(), make | |
1724 // sure it is async-safe and can handle partially initialized VM. | |
1725 void os::shutdown() { | |
1726 | |
1727 // allow PerfMemory to attempt cleanup of any persistent resources | |
1728 perfMemory_exit(); | |
1729 | |
1730 // needs to remove object in file system | |
1731 AttachListener::abort(); | |
1732 | |
1733 // flush buffered output, finish log files | |
1734 ostream_abort(); | |
1735 | |
1736 // Check for abort hook | |
1737 abort_hook_t abort_hook = Arguments::abort_hook(); | |
1738 if (abort_hook != NULL) { | |
1739 abort_hook(); | |
1740 } | |
1741 | |
1742 } | |
1743 | |
1744 // Note: os::abort() might be called very early during initialization, or | |
1745 // called from signal handler. Before adding something to os::abort(), make | |
1746 // sure it is async-safe and can handle partially initialized VM. | |
1747 void os::abort(bool dump_core) { | |
1748 os::shutdown(); | |
1749 if (dump_core) { | |
1750 #ifndef PRODUCT | |
1751 fdStream out(defaultStream::output_fd()); | |
1752 out.print_raw("Current thread is "); | |
1753 char buf[16]; | |
1754 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); | |
1755 out.print_raw_cr(buf); | |
1756 out.print_raw_cr("Dumping core ..."); | |
1757 #endif | |
1758 ::abort(); // dump core | |
1759 } | |
1760 | |
1761 ::exit(1); | |
1762 } | |
1763 | |
1764 // Die immediately, no exit hook, no abort hook, no cleanup. | |
1765 void os::die() { | |
1766 // _exit() on BsdThreads only kills current thread | |
1767 ::abort(); | |
1768 } | |
1769 | |
1770 // unused on bsd for now. | |
1771 void os::set_error_file(const char *logfile) {} | |
1772 | |
1773 | |
1774 // This method is a copy of JDK's sysGetLastErrorString | |
1775 // from src/solaris/hpi/src/system_md.c | |
1776 | |
1777 size_t os::lasterror(char *buf, size_t len) { | |
1778 | |
1779 if (errno == 0) return 0; | |
1780 | |
1781 const char *s = ::strerror(errno); | |
1782 size_t n = ::strlen(s); | |
1783 if (n >= len) { | |
1784 n = len - 1; | |
1785 } | |
1786 ::strncpy(buf, s, n); | |
1787 buf[n] = '\0'; | |
1788 return n; | |
1789 } | |
1790 | |
1791 intx os::current_thread_id() { return (intx)pthread_self(); } | |
1792 int os::current_process_id() { | |
1793 | |
1794 // Under the old bsd thread library, bsd gives each thread | |
1795 // its own process id. Because of this each thread will return | |
1796 // a different pid if this method were to return the result | |
1797 // of getpid(2). Bsd provides no api that returns the pid | |
1798 // of the launcher thread for the vm. This implementation | |
1799 // returns a unique pid, the pid of the launcher thread | |
1800 // that starts the vm 'process'. | |
1801 | |
1802 // Under the NPTL, getpid() returns the same pid as the | |
1803 // launcher thread rather than a unique pid per thread. | |
1804 // Use gettid() if you want the old pre NPTL behaviour. | |
1805 | |
1806 // if you are looking for the result of a call to getpid() that | |
1807 // returns a unique pid for the calling thread, then look at the | |
1808 // OSThread::thread_id() method in osThread_bsd.hpp file | |
1809 | |
1810 return (int)(_initial_pid ? _initial_pid : getpid()); | |
1811 } | |
1812 | |
1813 // DLL functions | |
1814 | |
1815 #define JNI_LIB_PREFIX "lib" | |
1816 #ifdef __APPLE__ | |
1817 #define JNI_LIB_SUFFIX ".dylib" | |
1818 #else | |
1819 #define JNI_LIB_SUFFIX ".so" | |
1820 #endif | |
1821 | |
1822 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; } | |
1823 | |
1824 // This must be hard coded because it's the system's temporary | |
1825 // directory not the java application's temp directory, ala java.io.tmpdir. | |
4006 | 1826 #ifdef __APPLE__ |
1827 // macosx has a secure per-user temporary directory | |
1828 char temp_path_storage[PATH_MAX]; | |
1829 const char* os::get_temp_directory() { | |
1830 static char *temp_path = NULL; | |
1831 if (temp_path == NULL) { | |
1832 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX); | |
1833 if (pathSize == 0 || pathSize > PATH_MAX) { | |
1834 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage)); | |
1835 } | |
1836 temp_path = temp_path_storage; | |
1837 } | |
1838 return temp_path; | |
1839 } | |
1840 #else /* __APPLE__ */ | |
3960 | 1841 const char* os::get_temp_directory() { return "/tmp"; } |
4006 | 1842 #endif /* __APPLE__ */ |
3960 | 1843 |
1844 static bool file_exists(const char* filename) { | |
1845 struct stat statbuf; | |
1846 if (filename == NULL || strlen(filename) == 0) { | |
1847 return false; | |
1848 } | |
1849 return os::stat(filename, &statbuf) == 0; | |
1850 } | |
1851 | |
1852 void os::dll_build_name(char* buffer, size_t buflen, | |
1853 const char* pname, const char* fname) { | |
1854 // Copied from libhpi | |
1855 const size_t pnamelen = pname ? strlen(pname) : 0; | |
1856 | |
1857 // Quietly truncate on buffer overflow. Should be an error. | |
1858 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) { | |
1859 *buffer = '\0'; | |
1860 return; | |
1861 } | |
1862 | |
1863 if (pnamelen == 0) { | |
1864 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname); | |
1865 } else if (strchr(pname, *os::path_separator()) != NULL) { | |
1866 int n; | |
1867 char** pelements = split_path(pname, &n); | |
1868 for (int i = 0 ; i < n ; i++) { | |
1869 // Really shouldn't be NULL, but check can't hurt | |
1870 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { | |
1871 continue; // skip the empty path values | |
1872 } | |
1873 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, | |
1874 pelements[i], fname); | |
1875 if (file_exists(buffer)) { | |
1876 break; | |
1877 } | |
1878 } | |
1879 // release the storage | |
1880 for (int i = 0 ; i < n ; i++) { | |
1881 if (pelements[i] != NULL) { | |
1882 FREE_C_HEAP_ARRAY(char, pelements[i]); | |
1883 } | |
1884 } | |
1885 if (pelements != NULL) { | |
1886 FREE_C_HEAP_ARRAY(char*, pelements); | |
1887 } | |
1888 } else { | |
1889 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname); | |
1890 } | |
1891 } | |
1892 | |
1893 const char* os::get_current_directory(char *buf, int buflen) { | |
1894 return getcwd(buf, buflen); | |
1895 } | |
1896 | |
1897 // check if addr is inside libjvm[_g].so | |
1898 bool os::address_is_in_vm(address addr) { | |
1899 static address libjvm_base_addr; | |
1900 Dl_info dlinfo; | |
1901 | |
1902 if (libjvm_base_addr == NULL) { | |
1903 dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); | |
1904 libjvm_base_addr = (address)dlinfo.dli_fbase; | |
1905 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); | |
1906 } | |
1907 | |
1908 if (dladdr((void *)addr, &dlinfo)) { | |
1909 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; | |
1910 } | |
1911 | |
1912 return false; | |
1913 } | |
1914 | |
1915 bool os::dll_address_to_function_name(address addr, char *buf, | |
1916 int buflen, int *offset) { | |
1917 Dl_info dlinfo; | |
1918 | |
1919 if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) { | |
1920 if (buf != NULL) { | |
1921 if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { | |
1922 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); | |
1923 } | |
1924 } | |
1925 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; | |
1926 return true; | |
1927 } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) { | |
1928 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), | |
4805
db18ca98d237
7131050: fix for "7071311 Decoder enhancement" does not build on MacOS X
zgu
parents:
4734
diff
changeset
|
1929 buf, buflen, offset, dlinfo.dli_fname)) { |
3960 | 1930 return true; |
1931 } | |
1932 } | |
1933 | |
1934 if (buf != NULL) buf[0] = '\0'; | |
1935 if (offset != NULL) *offset = -1; | |
1936 return false; | |
1937 } | |
1938 | |
1939 #ifdef _ALLBSD_SOURCE | |
1940 // ported from solaris version | |
1941 bool os::dll_address_to_library_name(address addr, char* buf, | |
1942 int buflen, int* offset) { | |
1943 Dl_info dlinfo; | |
1944 | |
1945 if (dladdr((void*)addr, &dlinfo)){ | |
1946 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); | |
1947 if (offset) *offset = addr - (address)dlinfo.dli_fbase; | |
1948 return true; | |
1949 } else { | |
1950 if (buf) buf[0] = '\0'; | |
1951 if (offset) *offset = -1; | |
1952 return false; | |
1953 } | |
1954 } | |
1955 #else | |
1956 struct _address_to_library_name { | |
1957 address addr; // input : memory address | |
1958 size_t buflen; // size of fname | |
1959 char* fname; // output: library name | |
1960 address base; // library base addr | |
1961 }; | |
1962 | |
1963 static int address_to_library_name_callback(struct dl_phdr_info *info, | |
1964 size_t size, void *data) { | |
1965 int i; | |
1966 bool found = false; | |
1967 address libbase = NULL; | |
1968 struct _address_to_library_name * d = (struct _address_to_library_name *)data; | |
1969 | |
1970 // iterate through all loadable segments | |
1971 for (i = 0; i < info->dlpi_phnum; i++) { | |
1972 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); | |
1973 if (info->dlpi_phdr[i].p_type == PT_LOAD) { | |
1974 // base address of a library is the lowest address of its loaded | |
1975 // segments. | |
1976 if (libbase == NULL || libbase > segbase) { | |
1977 libbase = segbase; | |
1978 } | |
1979 // see if 'addr' is within current segment | |
1980 if (segbase <= d->addr && | |
1981 d->addr < segbase + info->dlpi_phdr[i].p_memsz) { | |
1982 found = true; | |
1983 } | |
1984 } | |
1985 } | |
1986 | |
1987 // dlpi_name is NULL or empty if the ELF file is executable, return 0 | |
1988 // so dll_address_to_library_name() can fall through to use dladdr() which | |
1989 // can figure out executable name from argv[0]. | |
1990 if (found && info->dlpi_name && info->dlpi_name[0]) { | |
1991 d->base = libbase; | |
1992 if (d->fname) { | |
1993 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name); | |
1994 } | |
1995 return 1; | |
1996 } | |
1997 return 0; | |
1998 } | |
1999 | |
2000 bool os::dll_address_to_library_name(address addr, char* buf, | |
2001 int buflen, int* offset) { | |
2002 Dl_info dlinfo; | |
2003 struct _address_to_library_name data; | |
2004 | |
2005 // There is a bug in old glibc dladdr() implementation that it could resolve | |
2006 // to wrong library name if the .so file has a base address != NULL. Here | |
2007 // we iterate through the program headers of all loaded libraries to find | |
2008 // out which library 'addr' really belongs to. This workaround can be | |
2009 // removed once the minimum requirement for glibc is moved to 2.3.x. | |
2010 data.addr = addr; | |
2011 data.fname = buf; | |
2012 data.buflen = buflen; | |
2013 data.base = NULL; | |
2014 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data); | |
2015 | |
2016 if (rslt) { | |
2017 // buf already contains library name | |
2018 if (offset) *offset = addr - data.base; | |
2019 return true; | |
2020 } else if (dladdr((void*)addr, &dlinfo)){ | |
2021 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); | |
2022 if (offset) *offset = addr - (address)dlinfo.dli_fbase; | |
2023 return true; | |
2024 } else { | |
2025 if (buf) buf[0] = '\0'; | |
2026 if (offset) *offset = -1; | |
2027 return false; | |
2028 } | |
2029 } | |
2030 #endif | |
2031 | |
2032 // Loads .dll/.so and | |
2033 // in case of error it checks if .dll/.so was built for the | |
2034 // same architecture as Hotspot is running on | |
2035 | |
2036 #ifdef __APPLE__ | |
2037 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { | |
2038 void * result= ::dlopen(filename, RTLD_LAZY); | |
2039 if (result != NULL) { | |
2040 // Successful loading | |
2041 return result; | |
2042 } | |
2043 | |
2044 // Read system error message into ebuf | |
2045 ::strncpy(ebuf, ::dlerror(), ebuflen-1); | |
2046 ebuf[ebuflen-1]='\0'; | |
2047 | |
2048 return NULL; | |
2049 } | |
2050 #else | |
2051 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) | |
2052 { | |
2053 void * result= ::dlopen(filename, RTLD_LAZY); | |
2054 if (result != NULL) { | |
2055 // Successful loading | |
2056 return result; | |
2057 } | |
2058 | |
2059 Elf32_Ehdr elf_head; | |
2060 | |
2061 // Read system error message into ebuf | |
2062 // It may or may not be overwritten below | |
2063 ::strncpy(ebuf, ::dlerror(), ebuflen-1); | |
2064 ebuf[ebuflen-1]='\0'; | |
2065 int diag_msg_max_length=ebuflen-strlen(ebuf); | |
2066 char* diag_msg_buf=ebuf+strlen(ebuf); | |
2067 | |
2068 if (diag_msg_max_length==0) { | |
2069 // No more space in ebuf for additional diagnostics message | |
2070 return NULL; | |
2071 } | |
2072 | |
2073 | |
2074 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); | |
2075 | |
2076 if (file_descriptor < 0) { | |
2077 // Can't open library, report dlerror() message | |
2078 return NULL; | |
2079 } | |
2080 | |
2081 bool failed_to_read_elf_head= | |
2082 (sizeof(elf_head)!= | |
2083 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; | |
2084 | |
2085 ::close(file_descriptor); | |
2086 if (failed_to_read_elf_head) { | |
2087 // file i/o error - report dlerror() msg | |
2088 return NULL; | |
2089 } | |
2090 | |
2091 typedef struct { | |
2092 Elf32_Half code; // Actual value as defined in elf.h | |
2093 Elf32_Half compat_class; // Compatibility of archs at VM's sense | |
2094 char elf_class; // 32 or 64 bit | |
2095 char endianess; // MSB or LSB | |
2096 char* name; // String representation | |
2097 } arch_t; | |
2098 | |
2099 #ifndef EM_486 | |
2100 #define EM_486 6 /* Intel 80486 */ | |
2101 #endif | |
2102 | |
2103 #ifndef EM_MIPS_RS3_LE | |
2104 #define EM_MIPS_RS3_LE 10 /* MIPS */ | |
2105 #endif | |
2106 | |
2107 #ifndef EM_PPC64 | |
2108 #define EM_PPC64 21 /* PowerPC64 */ | |
2109 #endif | |
2110 | |
2111 #ifndef EM_S390 | |
2112 #define EM_S390 22 /* IBM System/390 */ | |
2113 #endif | |
2114 | |
2115 #ifndef EM_IA_64 | |
2116 #define EM_IA_64 50 /* HP/Intel IA-64 */ | |
2117 #endif | |
2118 | |
2119 #ifndef EM_X86_64 | |
2120 #define EM_X86_64 62 /* AMD x86-64 */ | |
2121 #endif | |
2122 | |
2123 static const arch_t arch_array[]={ | |
2124 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, | |
2125 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, | |
2126 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, | |
2127 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, | |
2128 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, | |
2129 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, | |
2130 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, | |
2131 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, | |
2132 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, | |
2133 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, | |
2134 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, | |
2135 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, | |
2136 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, | |
2137 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, | |
2138 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, | |
2139 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"} | |
2140 }; | |
2141 | |
2142 #if (defined IA32) | |
2143 static Elf32_Half running_arch_code=EM_386; | |
2144 #elif (defined AMD64) | |
2145 static Elf32_Half running_arch_code=EM_X86_64; | |
2146 #elif (defined IA64) | |
2147 static Elf32_Half running_arch_code=EM_IA_64; | |
2148 #elif (defined __sparc) && (defined _LP64) | |
2149 static Elf32_Half running_arch_code=EM_SPARCV9; | |
2150 #elif (defined __sparc) && (!defined _LP64) | |
2151 static Elf32_Half running_arch_code=EM_SPARC; | |
2152 #elif (defined __powerpc64__) | |
2153 static Elf32_Half running_arch_code=EM_PPC64; | |
2154 #elif (defined __powerpc__) | |
2155 static Elf32_Half running_arch_code=EM_PPC; | |
2156 #elif (defined ARM) | |
2157 static Elf32_Half running_arch_code=EM_ARM; | |
2158 #elif (defined S390) | |
2159 static Elf32_Half running_arch_code=EM_S390; | |
2160 #elif (defined ALPHA) | |
2161 static Elf32_Half running_arch_code=EM_ALPHA; | |
2162 #elif (defined MIPSEL) | |
2163 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; | |
2164 #elif (defined PARISC) | |
2165 static Elf32_Half running_arch_code=EM_PARISC; | |
2166 #elif (defined MIPS) | |
2167 static Elf32_Half running_arch_code=EM_MIPS; | |
2168 #elif (defined M68K) | |
2169 static Elf32_Half running_arch_code=EM_68K; | |
2170 #else | |
2171 #error Method os::dll_load requires that one of following is defined:\ | |
2172 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K | |
2173 #endif | |
2174 | |
2175 // Identify compatability class for VM's architecture and library's architecture | |
2176 // Obtain string descriptions for architectures | |
2177 | |
2178 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; | |
2179 int running_arch_index=-1; | |
2180 | |
2181 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { | |
2182 if (running_arch_code == arch_array[i].code) { | |
2183 running_arch_index = i; | |
2184 } | |
2185 if (lib_arch.code == arch_array[i].code) { | |
2186 lib_arch.compat_class = arch_array[i].compat_class; | |
2187 lib_arch.name = arch_array[i].name; | |
2188 } | |
2189 } | |
2190 | |
2191 assert(running_arch_index != -1, | |
2192 "Didn't find running architecture code (running_arch_code) in arch_array"); | |
2193 if (running_arch_index == -1) { | |
2194 // Even though running architecture detection failed | |
2195 // we may still continue with reporting dlerror() message | |
2196 return NULL; | |
2197 } | |
2198 | |
2199 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { | |
2200 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); | |
2201 return NULL; | |
2202 } | |
2203 | |
2204 #ifndef S390 | |
2205 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { | |
2206 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); | |
2207 return NULL; | |
2208 } | |
2209 #endif // !S390 | |
2210 | |
2211 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { | |
2212 if ( lib_arch.name!=NULL ) { | |
2213 ::snprintf(diag_msg_buf, diag_msg_max_length-1, | |
2214 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", | |
2215 lib_arch.name, arch_array[running_arch_index].name); | |
2216 } else { | |
2217 ::snprintf(diag_msg_buf, diag_msg_max_length-1, | |
2218 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", | |
2219 lib_arch.code, | |
2220 arch_array[running_arch_index].name); | |
2221 } | |
2222 } | |
2223 | |
2224 return NULL; | |
2225 } | |
2226 #endif /* !__APPLE__ */ | |
2227 | |
2228 // XXX: Do we need a lock around this as per Linux? | |
2229 void* os::dll_lookup(void* handle, const char* name) { | |
2230 return dlsym(handle, name); | |
2231 } | |
2232 | |
2233 | |
2234 static bool _print_ascii_file(const char* filename, outputStream* st) { | |
2235 int fd = ::open(filename, O_RDONLY); | |
2236 if (fd == -1) { | |
2237 return false; | |
2238 } | |
2239 | |
2240 char buf[32]; | |
2241 int bytes; | |
2242 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { | |
2243 st->print_raw(buf, bytes); | |
2244 } | |
2245 | |
2246 ::close(fd); | |
2247 | |
2248 return true; | |
2249 } | |
2250 | |
2251 void os::print_dll_info(outputStream *st) { | |
2252 st->print_cr("Dynamic libraries:"); | |
2253 #ifdef _ALLBSD_SOURCE | |
2254 #ifdef RTLD_DI_LINKMAP | |
2255 Dl_info dli; | |
2256 void *handle; | |
2257 Link_map *map; | |
2258 Link_map *p; | |
2259 | |
2260 if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) { | |
2261 st->print_cr("Error: Cannot print dynamic libraries."); | |
2262 return; | |
2263 } | |
2264 handle = dlopen(dli.dli_fname, RTLD_LAZY); | |
2265 if (handle == NULL) { | |
2266 st->print_cr("Error: Cannot print dynamic libraries."); | |
2267 return; | |
2268 } | |
2269 dlinfo(handle, RTLD_DI_LINKMAP, &map); | |
2270 if (map == NULL) { | |
2271 st->print_cr("Error: Cannot print dynamic libraries."); | |
2272 return; | |
2273 } | |
2274 | |
2275 while (map->l_prev != NULL) | |
2276 map = map->l_prev; | |
2277 | |
2278 while (map != NULL) { | |
2279 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); | |
2280 map = map->l_next; | |
2281 } | |
2282 | |
2283 dlclose(handle); | |
2284 #elif defined(__APPLE__) | |
2285 uint32_t count; | |
2286 uint32_t i; | |
2287 | |
2288 count = _dyld_image_count(); | |
2289 for (i = 1; i < count; i++) { | |
2290 const char *name = _dyld_get_image_name(i); | |
2291 intptr_t slide = _dyld_get_image_vmaddr_slide(i); | |
2292 st->print_cr(PTR_FORMAT " \t%s", slide, name); | |
2293 } | |
2294 #else | |
2295 st->print_cr("Error: Cannot print dynamic libraries."); | |
2296 #endif | |
2297 #else | |
2298 char fname[32]; | |
2299 pid_t pid = os::Bsd::gettid(); | |
2300 | |
2301 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid); | |
2302 | |
2303 if (!_print_ascii_file(fname, st)) { | |
2304 st->print("Can not get library information for pid = %d\n", pid); | |
2305 } | |
2306 #endif | |
2307 } | |
2308 | |
2309 | |
2310 void os::print_os_info(outputStream* st) { | |
2311 st->print("OS:"); | |
2312 | |
2313 // Try to identify popular distros. | |
2314 // Most Bsd distributions have /etc/XXX-release file, which contains | |
2315 // the OS version string. Some have more than one /etc/XXX-release file | |
2316 // (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.), | |
2317 // so the order is important. | |
2318 if (!_print_ascii_file("/etc/mandrake-release", st) && | |
2319 !_print_ascii_file("/etc/sun-release", st) && | |
2320 !_print_ascii_file("/etc/redhat-release", st) && | |
2321 !_print_ascii_file("/etc/SuSE-release", st) && | |
2322 !_print_ascii_file("/etc/turbobsd-release", st) && | |
2323 !_print_ascii_file("/etc/gentoo-release", st) && | |
2324 !_print_ascii_file("/etc/debian_version", st) && | |
2325 !_print_ascii_file("/etc/ltib-release", st) && | |
2326 !_print_ascii_file("/etc/angstrom-version", st)) { | |
2327 st->print("Bsd"); | |
2328 } | |
2329 st->cr(); | |
2330 | |
2331 // kernel | |
2332 st->print("uname:"); | |
2333 struct utsname name; | |
2334 uname(&name); | |
2335 st->print(name.sysname); st->print(" "); | |
2336 st->print(name.release); st->print(" "); | |
2337 st->print(name.version); st->print(" "); | |
2338 st->print(name.machine); | |
2339 st->cr(); | |
2340 | |
2341 #ifndef _ALLBSD_SOURCE | |
2342 // Print warning if unsafe chroot environment detected | |
2343 if (unsafe_chroot_detected) { | |
2344 st->print("WARNING!! "); | |
2345 st->print_cr(unstable_chroot_error); | |
2346 } | |
2347 | |
2348 // libc, pthread | |
2349 st->print("libc:"); | |
2350 st->print(os::Bsd::glibc_version()); st->print(" "); | |
2351 st->print(os::Bsd::libpthread_version()); st->print(" "); | |
2352 if (os::Bsd::is_BsdThreads()) { | |
2353 st->print("(%s stack)", os::Bsd::is_floating_stack() ? "floating" : "fixed"); | |
2354 } | |
2355 st->cr(); | |
2356 #endif | |
2357 | |
2358 // rlimit | |
2359 st->print("rlimit:"); | |
2360 struct rlimit rlim; | |
2361 | |
2362 st->print(" STACK "); | |
2363 getrlimit(RLIMIT_STACK, &rlim); | |
2364 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
2365 else st->print("%uk", rlim.rlim_cur >> 10); | |
2366 | |
2367 st->print(", CORE "); | |
2368 getrlimit(RLIMIT_CORE, &rlim); | |
2369 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
2370 else st->print("%uk", rlim.rlim_cur >> 10); | |
2371 | |
2372 st->print(", NPROC "); | |
2373 getrlimit(RLIMIT_NPROC, &rlim); | |
2374 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
2375 else st->print("%d", rlim.rlim_cur); | |
2376 | |
2377 st->print(", NOFILE "); | |
2378 getrlimit(RLIMIT_NOFILE, &rlim); | |
2379 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
2380 else st->print("%d", rlim.rlim_cur); | |
2381 | |
2382 #ifndef _ALLBSD_SOURCE | |
2383 st->print(", AS "); | |
2384 getrlimit(RLIMIT_AS, &rlim); | |
2385 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
2386 else st->print("%uk", rlim.rlim_cur >> 10); | |
2387 st->cr(); | |
2388 | |
2389 // load average | |
2390 st->print("load average:"); | |
2391 double loadavg[3]; | |
2392 os::loadavg(loadavg, 3); | |
2393 st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); | |
2394 st->cr(); | |
2395 #endif | |
2396 } | |
2397 | |
2398 void os::pd_print_cpu_info(outputStream* st) { | |
2399 // Nothing to do for now. | |
2400 } | |
2401 | |
2402 void os::print_memory_info(outputStream* st) { | |
2403 | |
2404 st->print("Memory:"); | |
2405 st->print(" %dk page", os::vm_page_size()>>10); | |
2406 | |
2407 #ifndef _ALLBSD_SOURCE | |
2408 // values in struct sysinfo are "unsigned long" | |
2409 struct sysinfo si; | |
2410 sysinfo(&si); | |
2411 #endif | |
2412 | |
2413 st->print(", physical " UINT64_FORMAT "k", | |
2414 os::physical_memory() >> 10); | |
2415 st->print("(" UINT64_FORMAT "k free)", | |
2416 os::available_memory() >> 10); | |
2417 #ifndef _ALLBSD_SOURCE | |
2418 st->print(", swap " UINT64_FORMAT "k", | |
2419 ((jlong)si.totalswap * si.mem_unit) >> 10); | |
2420 st->print("(" UINT64_FORMAT "k free)", | |
2421 ((jlong)si.freeswap * si.mem_unit) >> 10); | |
2422 #endif | |
2423 st->cr(); | |
2424 | |
2425 // meminfo | |
2426 st->print("\n/proc/meminfo:\n"); | |
2427 _print_ascii_file("/proc/meminfo", st); | |
2428 st->cr(); | |
2429 } | |
2430 | |
2431 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific | |
2432 // but they're the same for all the bsd arch that we support | |
2433 // and they're the same for solaris but there's no common place to put this. | |
2434 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR", | |
2435 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG", | |
2436 "ILL_COPROC", "ILL_BADSTK" }; | |
2437 | |
2438 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV", | |
2439 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES", | |
2440 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" }; | |
2441 | |
2442 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" }; | |
2443 | |
2444 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" }; | |
2445 | |
2446 void os::print_siginfo(outputStream* st, void* siginfo) { | |
2447 st->print("siginfo:"); | |
2448 | |
2449 const int buflen = 100; | |
2450 char buf[buflen]; | |
2451 siginfo_t *si = (siginfo_t*)siginfo; | |
2452 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen)); | |
2453 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) { | |
2454 st->print("si_errno=%s", buf); | |
2455 } else { | |
2456 st->print("si_errno=%d", si->si_errno); | |
2457 } | |
2458 const int c = si->si_code; | |
2459 assert(c > 0, "unexpected si_code"); | |
2460 switch (si->si_signo) { | |
2461 case SIGILL: | |
2462 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]); | |
2463 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2464 break; | |
2465 case SIGFPE: | |
2466 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]); | |
2467 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2468 break; | |
2469 case SIGSEGV: | |
2470 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]); | |
2471 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2472 break; | |
2473 case SIGBUS: | |
2474 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]); | |
2475 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2476 break; | |
2477 default: | |
2478 st->print(", si_code=%d", si->si_code); | |
2479 // no si_addr | |
2480 } | |
2481 | |
2482 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && | |
2483 UseSharedSpaces) { | |
2484 FileMapInfo* mapinfo = FileMapInfo::current_info(); | |
2485 if (mapinfo->is_in_shared_space(si->si_addr)) { | |
2486 st->print("\n\nError accessing class data sharing archive." \ | |
2487 " Mapped file inaccessible during execution, " \ | |
2488 " possible disk/network problem."); | |
2489 } | |
2490 } | |
2491 st->cr(); | |
2492 } | |
2493 | |
2494 | |
2495 static void print_signal_handler(outputStream* st, int sig, | |
2496 char* buf, size_t buflen); | |
2497 | |
2498 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { | |
2499 st->print_cr("Signal Handlers:"); | |
2500 print_signal_handler(st, SIGSEGV, buf, buflen); | |
2501 print_signal_handler(st, SIGBUS , buf, buflen); | |
2502 print_signal_handler(st, SIGFPE , buf, buflen); | |
2503 print_signal_handler(st, SIGPIPE, buf, buflen); | |
2504 print_signal_handler(st, SIGXFSZ, buf, buflen); | |
2505 print_signal_handler(st, SIGILL , buf, buflen); | |
2506 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); | |
2507 print_signal_handler(st, SR_signum, buf, buflen); | |
2508 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); | |
2509 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); | |
2510 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); | |
2511 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); | |
2512 } | |
2513 | |
2514 static char saved_jvm_path[MAXPATHLEN] = {0}; | |
2515 | |
4846 | 2516 // Find the full path to the current module, libjvm or libjvm_g |
3960 | 2517 void os::jvm_path(char *buf, jint buflen) { |
2518 // Error checking. | |
2519 if (buflen < MAXPATHLEN) { | |
2520 assert(false, "must use a large-enough buffer"); | |
2521 buf[0] = '\0'; | |
2522 return; | |
2523 } | |
2524 // Lazy resolve the path to current module. | |
2525 if (saved_jvm_path[0] != 0) { | |
2526 strcpy(buf, saved_jvm_path); | |
2527 return; | |
2528 } | |
2529 | |
2530 char dli_fname[MAXPATHLEN]; | |
2531 bool ret = dll_address_to_library_name( | |
2532 CAST_FROM_FN_PTR(address, os::jvm_path), | |
2533 dli_fname, sizeof(dli_fname), NULL); | |
2534 assert(ret != 0, "cannot locate libjvm"); | |
2535 char *rp = realpath(dli_fname, buf); | |
2536 if (rp == NULL) | |
2537 return; | |
2538 | |
2539 if (Arguments::created_by_gamma_launcher()) { | |
2540 // Support for the gamma launcher. Typical value for buf is | |
4846 | 2541 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at |
3960 | 2542 // the right place in the string, then assume we are installed in a JDK and |
4846 | 2543 // we're done. Otherwise, check for a JAVA_HOME environment variable and |
2544 // construct a path to the JVM being overridden. | |
2545 | |
3960 | 2546 const char *p = buf + strlen(buf) - 1; |
2547 for (int count = 0; p > buf && count < 5; ++count) { | |
2548 for (--p; p > buf && *p != '/'; --p) | |
2549 /* empty */ ; | |
2550 } | |
2551 | |
2552 if (strncmp(p, "/jre/lib/", 9) != 0) { | |
2553 // Look for JAVA_HOME in the environment. | |
2554 char* java_home_var = ::getenv("JAVA_HOME"); | |
2555 if (java_home_var != NULL && java_home_var[0] != 0) { | |
2556 char* jrelib_p; | |
2557 int len; | |
2558 | |
4846 | 2559 // Check the current module name "libjvm" or "libjvm_g". |
3960 | 2560 p = strrchr(buf, '/'); |
2561 assert(strstr(p, "/libjvm") == p, "invalid library name"); | |
2562 p = strstr(p, "_g") ? "_g" : ""; | |
2563 | |
2564 rp = realpath(java_home_var, buf); | |
2565 if (rp == NULL) | |
2566 return; | |
2567 | |
2568 // determine if this is a legacy image or modules image | |
2569 // modules image doesn't have "jre" subdirectory | |
2570 len = strlen(buf); | |
2571 jrelib_p = buf + len; | |
4846 | 2572 |
2573 // Add the appropriate library subdir | |
2574 snprintf(jrelib_p, buflen-len, "/jre/lib"); | |
3960 | 2575 if (0 != access(buf, F_OK)) { |
4846 | 2576 snprintf(jrelib_p, buflen-len, "/lib"); |
3960 | 2577 } |
2578 | |
4846 | 2579 // Add the appropriate client or server subdir |
2580 len = strlen(buf); | |
2581 jrelib_p = buf + len; | |
2582 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT); | |
2583 if (0 != access(buf, F_OK)) { | |
2584 snprintf(jrelib_p, buflen-len, ""); | |
2585 } | |
2586 | |
2587 // If the path exists within JAVA_HOME, add the JVM library name | |
2588 // to complete the path to JVM being overridden. Otherwise fallback | |
2589 // to the path to the current library. | |
3960 | 2590 if (0 == access(buf, F_OK)) { |
4846 | 2591 // Use current module name "libjvm[_g]" instead of |
2592 // "libjvm"debug_only("_g")"" since for fastdebug version | |
2593 // we should have "libjvm" but debug_only("_g") adds "_g"! | |
3960 | 2594 len = strlen(buf); |
4846 | 2595 snprintf(buf + len, buflen-len, "/libjvm%s%s", p, JNI_LIB_SUFFIX); |
3960 | 2596 } else { |
4846 | 2597 // Fall back to path of current library |
3960 | 2598 rp = realpath(dli_fname, buf); |
2599 if (rp == NULL) | |
2600 return; | |
2601 } | |
2602 } | |
2603 } | |
2604 } | |
2605 | |
2606 strcpy(saved_jvm_path, buf); | |
2607 } | |
2608 | |
2609 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { | |
2610 // no prefix required, not even "_" | |
2611 } | |
2612 | |
2613 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { | |
2614 // no suffix required | |
2615 } | |
2616 | |
2617 //////////////////////////////////////////////////////////////////////////////// | |
2618 // sun.misc.Signal support | |
2619 | |
2620 static volatile jint sigint_count = 0; | |
2621 | |
2622 static void | |
2623 UserHandler(int sig, void *siginfo, void *context) { | |
2624 // 4511530 - sem_post is serialized and handled by the manager thread. When | |
2625 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We | |
2626 // don't want to flood the manager thread with sem_post requests. | |
2627 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) | |
2628 return; | |
2629 | |
2630 // Ctrl-C is pressed during error reporting, likely because the error | |
2631 // handler fails to abort. Let VM die immediately. | |
2632 if (sig == SIGINT && is_error_reported()) { | |
2633 os::die(); | |
2634 } | |
2635 | |
2636 os::signal_notify(sig); | |
2637 } | |
2638 | |
2639 void* os::user_handler() { | |
2640 return CAST_FROM_FN_PTR(void*, UserHandler); | |
2641 } | |
2642 | |
2643 extern "C" { | |
2644 typedef void (*sa_handler_t)(int); | |
2645 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); | |
2646 } | |
2647 | |
2648 void* os::signal(int signal_number, void* handler) { | |
2649 struct sigaction sigAct, oldSigAct; | |
2650 | |
2651 sigfillset(&(sigAct.sa_mask)); | |
2652 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; | |
2653 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); | |
2654 | |
2655 if (sigaction(signal_number, &sigAct, &oldSigAct)) { | |
2656 // -1 means registration failed | |
2657 return (void *)-1; | |
2658 } | |
2659 | |
2660 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); | |
2661 } | |
2662 | |
2663 void os::signal_raise(int signal_number) { | |
2664 ::raise(signal_number); | |
2665 } | |
2666 | |
2667 /* | |
2668 * The following code is moved from os.cpp for making this | |
2669 * code platform specific, which it is by its very nature. | |
2670 */ | |
2671 | |
2672 // Will be modified when max signal is changed to be dynamic | |
2673 int os::sigexitnum_pd() { | |
2674 return NSIG; | |
2675 } | |
2676 | |
2677 // a counter for each possible signal value | |
2678 static volatile jint pending_signals[NSIG+1] = { 0 }; | |
2679 | |
2680 // Bsd(POSIX) specific hand shaking semaphore. | |
2681 #ifdef __APPLE__ | |
2682 static semaphore_t sig_sem; | |
2683 #define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value) | |
2684 #define SEM_WAIT(sem) semaphore_wait(sem); | |
2685 #define SEM_POST(sem) semaphore_signal(sem); | |
2686 #else | |
2687 static sem_t sig_sem; | |
2688 #define SEM_INIT(sem, value) sem_init(&sem, 0, value) | |
2689 #define SEM_WAIT(sem) sem_wait(&sem); | |
2690 #define SEM_POST(sem) sem_post(&sem); | |
2691 #endif | |
2692 | |
2693 void os::signal_init_pd() { | |
2694 // Initialize signal structures | |
2695 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); | |
2696 | |
2697 // Initialize signal semaphore | |
2698 ::SEM_INIT(sig_sem, 0); | |
2699 } | |
2700 | |
2701 void os::signal_notify(int sig) { | |
2702 Atomic::inc(&pending_signals[sig]); | |
2703 ::SEM_POST(sig_sem); | |
2704 } | |
2705 | |
2706 static int check_pending_signals(bool wait) { | |
2707 Atomic::store(0, &sigint_count); | |
2708 for (;;) { | |
2709 for (int i = 0; i < NSIG + 1; i++) { | |
2710 jint n = pending_signals[i]; | |
2711 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { | |
2712 return i; | |
2713 } | |
2714 } | |
2715 if (!wait) { | |
2716 return -1; | |
2717 } | |
2718 JavaThread *thread = JavaThread::current(); | |
2719 ThreadBlockInVM tbivm(thread); | |
2720 | |
2721 bool threadIsSuspended; | |
2722 do { | |
2723 thread->set_suspend_equivalent(); | |
2724 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() | |
2725 ::SEM_WAIT(sig_sem); | |
2726 | |
2727 // were we externally suspended while we were waiting? | |
2728 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); | |
2729 if (threadIsSuspended) { | |
2730 // | |
2731 // The semaphore has been incremented, but while we were waiting | |
2732 // another thread suspended us. We don't want to continue running | |
2733 // while suspended because that would surprise the thread that | |
2734 // suspended us. | |
2735 // | |
2736 ::SEM_POST(sig_sem); | |
2737 | |
2738 thread->java_suspend_self(); | |
2739 } | |
2740 } while (threadIsSuspended); | |
2741 } | |
2742 } | |
2743 | |
2744 int os::signal_lookup() { | |
2745 return check_pending_signals(false); | |
2746 } | |
2747 | |
2748 int os::signal_wait() { | |
2749 return check_pending_signals(true); | |
2750 } | |
2751 | |
2752 //////////////////////////////////////////////////////////////////////////////// | |
2753 // Virtual Memory | |
2754 | |
2755 int os::vm_page_size() { | |
2756 // Seems redundant as all get out | |
2757 assert(os::Bsd::page_size() != -1, "must call os::init"); | |
2758 return os::Bsd::page_size(); | |
2759 } | |
2760 | |
2761 // Solaris allocates memory by pages. | |
2762 int os::vm_allocation_granularity() { | |
2763 assert(os::Bsd::page_size() != -1, "must call os::init"); | |
2764 return os::Bsd::page_size(); | |
2765 } | |
2766 | |
2767 // Rationale behind this function: | |
2768 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable | |
2769 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get | |
2770 // samples for JITted code. Here we create private executable mapping over the code cache | |
2771 // and then we can use standard (well, almost, as mapping can change) way to provide | |
2772 // info for the reporting script by storing timestamp and location of symbol | |
2773 void bsd_wrap_code(char* base, size_t size) { | |
2774 static volatile jint cnt = 0; | |
2775 | |
2776 if (!UseOprofile) { | |
2777 return; | |
2778 } | |
2779 | |
2780 char buf[PATH_MAX + 1]; | |
2781 int num = Atomic::add(1, &cnt); | |
2782 | |
2783 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d", | |
2784 os::get_temp_directory(), os::current_process_id(), num); | |
2785 unlink(buf); | |
2786 | |
2787 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU); | |
2788 | |
2789 if (fd != -1) { | |
2790 off_t rv = ::lseek(fd, size-2, SEEK_SET); | |
2791 if (rv != (off_t)-1) { | |
2792 if (::write(fd, "", 1) == 1) { | |
2793 mmap(base, size, | |
2794 PROT_READ|PROT_WRITE|PROT_EXEC, | |
2795 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); | |
2796 } | |
2797 } | |
2798 ::close(fd); | |
2799 unlink(buf); | |
2800 } | |
2801 } | |
2802 | |
2803 // NOTE: Bsd kernel does not really reserve the pages for us. | |
2804 // All it does is to check if there are enough free pages | |
2805 // left at the time of mmap(). This could be a potential | |
2806 // problem. | |
2807 bool os::commit_memory(char* addr, size_t size, bool exec) { | |
2808 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; | |
2809 #ifdef __OpenBSD__ | |
2810 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD | |
2811 return ::mprotect(addr, size, prot) == 0; | |
2812 #else | |
2813 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, | |
2814 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); | |
2815 return res != (uintptr_t) MAP_FAILED; | |
2816 #endif | |
2817 } | |
2818 | |
2819 #ifndef _ALLBSD_SOURCE | |
2820 // Define MAP_HUGETLB here so we can build HotSpot on old systems. | |
2821 #ifndef MAP_HUGETLB | |
2822 #define MAP_HUGETLB 0x40000 | |
2823 #endif | |
2824 | |
2825 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems. | |
2826 #ifndef MADV_HUGEPAGE | |
2827 #define MADV_HUGEPAGE 14 | |
2828 #endif | |
2829 #endif | |
2830 | |
2831 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint, | |
2832 bool exec) { | |
2833 #ifndef _ALLBSD_SOURCE | |
2834 if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) { | |
2835 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; | |
2836 uintptr_t res = | |
2837 (uintptr_t) ::mmap(addr, size, prot, | |
2838 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS|MAP_HUGETLB, | |
2839 -1, 0); | |
2840 return res != (uintptr_t) MAP_FAILED; | |
2841 } | |
2842 #endif | |
2843 | |
2844 return commit_memory(addr, size, exec); | |
2845 } | |
2846 | |
2847 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { | |
2848 #ifndef _ALLBSD_SOURCE | |
2849 if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) { | |
2850 // We don't check the return value: madvise(MADV_HUGEPAGE) may not | |
2851 // be supported or the memory may already be backed by huge pages. | |
2852 ::madvise(addr, bytes, MADV_HUGEPAGE); | |
2853 } | |
2854 #endif | |
2855 } | |
2856 | |
4734
20bfb6d15a94
7124829: NUMA: memory leak on Linux with large pages
iveresov
parents:
4712
diff
changeset
|
2857 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) { |
3960 | 2858 ::madvise(addr, bytes, MADV_DONTNEED); |
2859 } | |
2860 | |
2861 void os::numa_make_global(char *addr, size_t bytes) { | |
2862 } | |
2863 | |
2864 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { | |
2865 } | |
2866 | |
2867 bool os::numa_topology_changed() { return false; } | |
2868 | |
2869 size_t os::numa_get_groups_num() { | |
2870 return 1; | |
2871 } | |
2872 | |
2873 int os::numa_get_group_id() { | |
2874 return 0; | |
2875 } | |
2876 | |
2877 size_t os::numa_get_leaf_groups(int *ids, size_t size) { | |
2878 if (size > 0) { | |
2879 ids[0] = 0; | |
2880 return 1; | |
2881 } | |
2882 return 0; | |
2883 } | |
2884 | |
2885 bool os::get_page_info(char *start, page_info* info) { | |
2886 return false; | |
2887 } | |
2888 | |
2889 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { | |
2890 return end; | |
2891 } | |
2892 | |
2893 #ifndef _ALLBSD_SOURCE | |
2894 // Something to do with the numa-aware allocator needs these symbols | |
2895 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { } | |
2896 extern "C" JNIEXPORT void numa_error(char *where) { } | |
2897 extern "C" JNIEXPORT int fork1() { return fork(); } | |
2898 | |
2899 | |
2900 // If we are running with libnuma version > 2, then we should | |
2901 // be trying to use symbols with versions 1.1 | |
2902 // If we are running with earlier version, which did not have symbol versions, | |
2903 // we should use the base version. | |
2904 void* os::Bsd::libnuma_dlsym(void* handle, const char *name) { | |
2905 void *f = dlvsym(handle, name, "libnuma_1.1"); | |
2906 if (f == NULL) { | |
2907 f = dlsym(handle, name); | |
2908 } | |
2909 return f; | |
2910 } | |
2911 | |
2912 bool os::Bsd::libnuma_init() { | |
2913 // sched_getcpu() should be in libc. | |
2914 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, | |
2915 dlsym(RTLD_DEFAULT, "sched_getcpu"))); | |
2916 | |
2917 if (sched_getcpu() != -1) { // Does it work? | |
2918 void *handle = dlopen("libnuma.so.1", RTLD_LAZY); | |
2919 if (handle != NULL) { | |
2920 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, | |
2921 libnuma_dlsym(handle, "numa_node_to_cpus"))); | |
2922 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t, | |
2923 libnuma_dlsym(handle, "numa_max_node"))); | |
2924 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t, | |
2925 libnuma_dlsym(handle, "numa_available"))); | |
2926 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t, | |
2927 libnuma_dlsym(handle, "numa_tonode_memory"))); | |
2928 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t, | |
2929 libnuma_dlsym(handle, "numa_interleave_memory"))); | |
2930 | |
2931 | |
2932 if (numa_available() != -1) { | |
2933 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes")); | |
2934 // Create a cpu -> node mapping | |
2935 _cpu_to_node = new (ResourceObj::C_HEAP) GrowableArray<int>(0, true); | |
2936 rebuild_cpu_to_node_map(); | |
2937 return true; | |
2938 } | |
2939 } | |
2940 } | |
2941 return false; | |
2942 } | |
2943 | |
2944 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id. | |
2945 // The table is later used in get_node_by_cpu(). | |
2946 void os::Bsd::rebuild_cpu_to_node_map() { | |
2947 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure | |
2948 // in libnuma (possible values are starting from 16, | |
2949 // and continuing up with every other power of 2, but less | |
2950 // than the maximum number of CPUs supported by kernel), and | |
2951 // is a subject to change (in libnuma version 2 the requirements | |
2952 // are more reasonable) we'll just hardcode the number they use | |
2953 // in the library. | |
2954 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT; | |
2955 | |
2956 size_t cpu_num = os::active_processor_count(); | |
2957 size_t cpu_map_size = NCPUS / BitsPerCLong; | |
2958 size_t cpu_map_valid_size = | |
2959 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size); | |
2960 | |
2961 cpu_to_node()->clear(); | |
2962 cpu_to_node()->at_grow(cpu_num - 1); | |
2963 size_t node_num = numa_get_groups_num(); | |
2964 | |
2965 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size); | |
2966 for (size_t i = 0; i < node_num; i++) { | |
2967 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) { | |
2968 for (size_t j = 0; j < cpu_map_valid_size; j++) { | |
2969 if (cpu_map[j] != 0) { | |
2970 for (size_t k = 0; k < BitsPerCLong; k++) { | |
2971 if (cpu_map[j] & (1UL << k)) { | |
2972 cpu_to_node()->at_put(j * BitsPerCLong + k, i); | |
2973 } | |
2974 } | |
2975 } | |
2976 } | |
2977 } | |
2978 } | |
2979 FREE_C_HEAP_ARRAY(unsigned long, cpu_map); | |
2980 } | |
2981 | |
2982 int os::Bsd::get_node_by_cpu(int cpu_id) { | |
2983 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) { | |
2984 return cpu_to_node()->at(cpu_id); | |
2985 } | |
2986 return -1; | |
2987 } | |
2988 | |
2989 GrowableArray<int>* os::Bsd::_cpu_to_node; | |
2990 os::Bsd::sched_getcpu_func_t os::Bsd::_sched_getcpu; | |
2991 os::Bsd::numa_node_to_cpus_func_t os::Bsd::_numa_node_to_cpus; | |
2992 os::Bsd::numa_max_node_func_t os::Bsd::_numa_max_node; | |
2993 os::Bsd::numa_available_func_t os::Bsd::_numa_available; | |
2994 os::Bsd::numa_tonode_memory_func_t os::Bsd::_numa_tonode_memory; | |
2995 os::Bsd::numa_interleave_memory_func_t os::Bsd::_numa_interleave_memory; | |
2996 unsigned long* os::Bsd::_numa_all_nodes; | |
2997 #endif | |
2998 | |
2999 bool os::uncommit_memory(char* addr, size_t size) { | |
3000 #ifdef __OpenBSD__ | |
3001 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD | |
3002 return ::mprotect(addr, size, PROT_NONE) == 0; | |
3003 #else | |
3004 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, | |
3005 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); | |
3006 return res != (uintptr_t) MAP_FAILED; | |
3007 #endif | |
3008 } | |
3009 | |
3010 bool os::create_stack_guard_pages(char* addr, size_t size) { | |
3011 return os::commit_memory(addr, size); | |
3012 } | |
3013 | |
3014 // If this is a growable mapping, remove the guard pages entirely by | |
3015 // munmap()ping them. If not, just call uncommit_memory(). | |
3016 bool os::remove_stack_guard_pages(char* addr, size_t size) { | |
3017 return os::uncommit_memory(addr, size); | |
3018 } | |
3019 | |
3020 static address _highest_vm_reserved_address = NULL; | |
3021 | |
3022 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory | |
3023 // at 'requested_addr'. If there are existing memory mappings at the same | |
3024 // location, however, they will be overwritten. If 'fixed' is false, | |
3025 // 'requested_addr' is only treated as a hint, the return value may or | |
3026 // may not start from the requested address. Unlike Bsd mmap(), this | |
3027 // function returns NULL to indicate failure. | |
3028 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { | |
3029 char * addr; | |
3030 int flags; | |
3031 | |
3032 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; | |
3033 if (fixed) { | |
3034 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address"); | |
3035 flags |= MAP_FIXED; | |
3036 } | |
3037 | |
3038 // Map uncommitted pages PROT_READ and PROT_WRITE, change access | |
3039 // to PROT_EXEC if executable when we commit the page. | |
3040 addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE, | |
3041 flags, -1, 0); | |
3042 | |
3043 if (addr != MAP_FAILED) { | |
3044 // anon_mmap() should only get called during VM initialization, | |
3045 // don't need lock (actually we can skip locking even it can be called | |
3046 // from multiple threads, because _highest_vm_reserved_address is just a | |
3047 // hint about the upper limit of non-stack memory regions.) | |
3048 if ((address)addr + bytes > _highest_vm_reserved_address) { | |
3049 _highest_vm_reserved_address = (address)addr + bytes; | |
3050 } | |
3051 } | |
3052 | |
3053 return addr == MAP_FAILED ? NULL : addr; | |
3054 } | |
3055 | |
3056 // Don't update _highest_vm_reserved_address, because there might be memory | |
3057 // regions above addr + size. If so, releasing a memory region only creates | |
3058 // a hole in the address space, it doesn't help prevent heap-stack collision. | |
3059 // | |
3060 static int anon_munmap(char * addr, size_t size) { | |
3061 return ::munmap(addr, size) == 0; | |
3062 } | |
3063 | |
3064 char* os::reserve_memory(size_t bytes, char* requested_addr, | |
3065 size_t alignment_hint) { | |
3066 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); | |
3067 } | |
3068 | |
3069 bool os::release_memory(char* addr, size_t size) { | |
3070 return anon_munmap(addr, size); | |
3071 } | |
3072 | |
3073 static address highest_vm_reserved_address() { | |
3074 return _highest_vm_reserved_address; | |
3075 } | |
3076 | |
3077 static bool bsd_mprotect(char* addr, size_t size, int prot) { | |
3078 // Bsd wants the mprotect address argument to be page aligned. | |
3079 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size()); | |
3080 | |
3081 // According to SUSv3, mprotect() should only be used with mappings | |
3082 // established by mmap(), and mmap() always maps whole pages. Unaligned | |
3083 // 'addr' likely indicates problem in the VM (e.g. trying to change | |
3084 // protection of malloc'ed or statically allocated memory). Check the | |
3085 // caller if you hit this assert. | |
3086 assert(addr == bottom, "sanity check"); | |
3087 | |
3088 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size()); | |
3089 return ::mprotect(bottom, size, prot) == 0; | |
3090 } | |
3091 | |
3092 // Set protections specified | |
3093 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, | |
3094 bool is_committed) { | |
3095 unsigned int p = 0; | |
3096 switch (prot) { | |
3097 case MEM_PROT_NONE: p = PROT_NONE; break; | |
3098 case MEM_PROT_READ: p = PROT_READ; break; | |
3099 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; | |
3100 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; | |
3101 default: | |
3102 ShouldNotReachHere(); | |
3103 } | |
3104 // is_committed is unused. | |
3105 return bsd_mprotect(addr, bytes, p); | |
3106 } | |
3107 | |
3108 bool os::guard_memory(char* addr, size_t size) { | |
3109 return bsd_mprotect(addr, size, PROT_NONE); | |
3110 } | |
3111 | |
3112 bool os::unguard_memory(char* addr, size_t size) { | |
3113 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE); | |
3114 } | |
3115 | |
3116 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) { | |
3117 bool result = false; | |
3118 #ifndef _ALLBSD_SOURCE | |
3119 void *p = mmap (NULL, page_size, PROT_READ|PROT_WRITE, | |
3120 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB, | |
3121 -1, 0); | |
3122 | |
3123 if (p != (void *) -1) { | |
3124 // We don't know if this really is a huge page or not. | |
3125 FILE *fp = fopen("/proc/self/maps", "r"); | |
3126 if (fp) { | |
3127 while (!feof(fp)) { | |
3128 char chars[257]; | |
3129 long x = 0; | |
3130 if (fgets(chars, sizeof(chars), fp)) { | |
3131 if (sscanf(chars, "%lx-%*x", &x) == 1 | |
3132 && x == (long)p) { | |
3133 if (strstr (chars, "hugepage")) { | |
3134 result = true; | |
3135 break; | |
3136 } | |
3137 } | |
3138 } | |
3139 } | |
3140 fclose(fp); | |
3141 } | |
3142 munmap (p, page_size); | |
3143 if (result) | |
3144 return true; | |
3145 } | |
3146 | |
3147 if (warn) { | |
3148 warning("HugeTLBFS is not supported by the operating system."); | |
3149 } | |
3150 #endif | |
3151 | |
3152 return result; | |
3153 } | |
3154 | |
3155 /* | |
3156 * Set the coredump_filter bits to include largepages in core dump (bit 6) | |
3157 * | |
3158 * From the coredump_filter documentation: | |
3159 * | |
3160 * - (bit 0) anonymous private memory | |
3161 * - (bit 1) anonymous shared memory | |
3162 * - (bit 2) file-backed private memory | |
3163 * - (bit 3) file-backed shared memory | |
3164 * - (bit 4) ELF header pages in file-backed private memory areas (it is | |
3165 * effective only if the bit 2 is cleared) | |
3166 * - (bit 5) hugetlb private memory | |
3167 * - (bit 6) hugetlb shared memory | |
3168 */ | |
3169 static void set_coredump_filter(void) { | |
3170 FILE *f; | |
3171 long cdm; | |
3172 | |
3173 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) { | |
3174 return; | |
3175 } | |
3176 | |
3177 if (fscanf(f, "%lx", &cdm) != 1) { | |
3178 fclose(f); | |
3179 return; | |
3180 } | |
3181 | |
3182 rewind(f); | |
3183 | |
3184 if ((cdm & LARGEPAGES_BIT) == 0) { | |
3185 cdm |= LARGEPAGES_BIT; | |
3186 fprintf(f, "%#lx", cdm); | |
3187 } | |
3188 | |
3189 fclose(f); | |
3190 } | |
3191 | |
3192 // Large page support | |
3193 | |
3194 static size_t _large_page_size = 0; | |
3195 | |
3196 void os::large_page_init() { | |
3197 #ifndef _ALLBSD_SOURCE | |
3198 if (!UseLargePages) { | |
3199 UseHugeTLBFS = false; | |
3200 UseSHM = false; | |
3201 return; | |
3202 } | |
3203 | |
3204 if (FLAG_IS_DEFAULT(UseHugeTLBFS) && FLAG_IS_DEFAULT(UseSHM)) { | |
3205 // If UseLargePages is specified on the command line try both methods, | |
3206 // if it's default, then try only HugeTLBFS. | |
3207 if (FLAG_IS_DEFAULT(UseLargePages)) { | |
3208 UseHugeTLBFS = true; | |
3209 } else { | |
3210 UseHugeTLBFS = UseSHM = true; | |
3211 } | |
3212 } | |
3213 | |
3214 if (LargePageSizeInBytes) { | |
3215 _large_page_size = LargePageSizeInBytes; | |
3216 } else { | |
3217 // large_page_size on Bsd is used to round up heap size. x86 uses either | |
3218 // 2M or 4M page, depending on whether PAE (Physical Address Extensions) | |
3219 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use | |
3220 // page as large as 256M. | |
3221 // | |
3222 // Here we try to figure out page size by parsing /proc/meminfo and looking | |
3223 // for a line with the following format: | |
3224 // Hugepagesize: 2048 kB | |
3225 // | |
3226 // If we can't determine the value (e.g. /proc is not mounted, or the text | |
3227 // format has been changed), we'll use the largest page size supported by | |
3228 // the processor. | |
3229 | |
3230 #ifndef ZERO | |
3231 _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M) | |
3232 ARM_ONLY(2 * M) PPC_ONLY(4 * M); | |
3233 #endif // ZERO | |
3234 | |
3235 FILE *fp = fopen("/proc/meminfo", "r"); | |
3236 if (fp) { | |
3237 while (!feof(fp)) { | |
3238 int x = 0; | |
3239 char buf[16]; | |
3240 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) { | |
3241 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) { | |
3242 _large_page_size = x * K; | |
3243 break; | |
3244 } | |
3245 } else { | |
3246 // skip to next line | |
3247 for (;;) { | |
3248 int ch = fgetc(fp); | |
3249 if (ch == EOF || ch == (int)'\n') break; | |
3250 } | |
3251 } | |
3252 } | |
3253 fclose(fp); | |
3254 } | |
3255 } | |
3256 | |
3257 // print a warning if any large page related flag is specified on command line | |
3258 bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS); | |
3259 | |
3260 const size_t default_page_size = (size_t)Bsd::page_size(); | |
3261 if (_large_page_size > default_page_size) { | |
3262 _page_sizes[0] = _large_page_size; | |
3263 _page_sizes[1] = default_page_size; | |
3264 _page_sizes[2] = 0; | |
3265 } | |
3266 UseHugeTLBFS = UseHugeTLBFS && | |
3267 Bsd::hugetlbfs_sanity_check(warn_on_failure, _large_page_size); | |
3268 | |
3269 if (UseHugeTLBFS) | |
3270 UseSHM = false; | |
3271 | |
3272 UseLargePages = UseHugeTLBFS || UseSHM; | |
3273 | |
3274 set_coredump_filter(); | |
3275 #endif | |
3276 } | |
3277 | |
3278 #ifndef _ALLBSD_SOURCE | |
3279 #ifndef SHM_HUGETLB | |
3280 #define SHM_HUGETLB 04000 | |
3281 #endif | |
3282 #endif | |
3283 | |
3284 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) { | |
3285 // "exec" is passed in but not used. Creating the shared image for | |
3286 // the code cache doesn't have an SHM_X executable permission to check. | |
3287 assert(UseLargePages && UseSHM, "only for SHM large pages"); | |
3288 | |
3289 key_t key = IPC_PRIVATE; | |
3290 char *addr; | |
3291 | |
3292 bool warn_on_failure = UseLargePages && | |
3293 (!FLAG_IS_DEFAULT(UseLargePages) || | |
3294 !FLAG_IS_DEFAULT(LargePageSizeInBytes) | |
3295 ); | |
3296 char msg[128]; | |
3297 | |
3298 // Create a large shared memory region to attach to based on size. | |
3299 // Currently, size is the total size of the heap | |
3300 #ifndef _ALLBSD_SOURCE | |
3301 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W); | |
3302 #else | |
3303 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W); | |
3304 #endif | |
3305 if (shmid == -1) { | |
3306 // Possible reasons for shmget failure: | |
3307 // 1. shmmax is too small for Java heap. | |
3308 // > check shmmax value: cat /proc/sys/kernel/shmmax | |
3309 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax | |
3310 // 2. not enough large page memory. | |
3311 // > check available large pages: cat /proc/meminfo | |
3312 // > increase amount of large pages: | |
3313 // echo new_value > /proc/sys/vm/nr_hugepages | |
3314 // Note 1: different Bsd may use different name for this property, | |
3315 // e.g. on Redhat AS-3 it is "hugetlb_pool". | |
3316 // Note 2: it's possible there's enough physical memory available but | |
3317 // they are so fragmented after a long run that they can't | |
3318 // coalesce into large pages. Try to reserve large pages when | |
3319 // the system is still "fresh". | |
3320 if (warn_on_failure) { | |
3321 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); | |
3322 warning(msg); | |
3323 } | |
3324 return NULL; | |
3325 } | |
3326 | |
3327 // attach to the region | |
3328 addr = (char*)shmat(shmid, req_addr, 0); | |
3329 int err = errno; | |
3330 | |
3331 // Remove shmid. If shmat() is successful, the actual shared memory segment | |
3332 // will be deleted when it's detached by shmdt() or when the process | |
3333 // terminates. If shmat() is not successful this will remove the shared | |
3334 // segment immediately. | |
3335 shmctl(shmid, IPC_RMID, NULL); | |
3336 | |
3337 if ((intptr_t)addr == -1) { | |
3338 if (warn_on_failure) { | |
3339 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); | |
3340 warning(msg); | |
3341 } | |
3342 return NULL; | |
3343 } | |
3344 | |
3345 return addr; | |
3346 } | |
3347 | |
3348 bool os::release_memory_special(char* base, size_t bytes) { | |
3349 // detaching the SHM segment will also delete it, see reserve_memory_special() | |
3350 int rslt = shmdt(base); | |
3351 return rslt == 0; | |
3352 } | |
3353 | |
3354 size_t os::large_page_size() { | |
3355 return _large_page_size; | |
3356 } | |
3357 | |
3358 // HugeTLBFS allows application to commit large page memory on demand; | |
3359 // with SysV SHM the entire memory region must be allocated as shared | |
3360 // memory. | |
3361 bool os::can_commit_large_page_memory() { | |
3362 return UseHugeTLBFS; | |
3363 } | |
3364 | |
3365 bool os::can_execute_large_page_memory() { | |
3366 return UseHugeTLBFS; | |
3367 } | |
3368 | |
3369 // Reserve memory at an arbitrary address, only if that area is | |
3370 // available (and not reserved for something else). | |
3371 | |
3372 char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) { | |
3373 const int max_tries = 10; | |
3374 char* base[max_tries]; | |
3375 size_t size[max_tries]; | |
3376 const size_t gap = 0x000000; | |
3377 | |
3378 // Assert only that the size is a multiple of the page size, since | |
3379 // that's all that mmap requires, and since that's all we really know | |
3380 // about at this low abstraction level. If we need higher alignment, | |
3381 // we can either pass an alignment to this method or verify alignment | |
3382 // in one of the methods further up the call chain. See bug 5044738. | |
3383 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); | |
3384 | |
3385 // Repeatedly allocate blocks until the block is allocated at the | |
3386 // right spot. Give up after max_tries. Note that reserve_memory() will | |
3387 // automatically update _highest_vm_reserved_address if the call is | |
3388 // successful. The variable tracks the highest memory address every reserved | |
3389 // by JVM. It is used to detect heap-stack collision if running with | |
3390 // fixed-stack BsdThreads. Because here we may attempt to reserve more | |
3391 // space than needed, it could confuse the collision detecting code. To | |
3392 // solve the problem, save current _highest_vm_reserved_address and | |
3393 // calculate the correct value before return. | |
3394 address old_highest = _highest_vm_reserved_address; | |
3395 | |
3396 // Bsd mmap allows caller to pass an address as hint; give it a try first, | |
3397 // if kernel honors the hint then we can return immediately. | |
3398 char * addr = anon_mmap(requested_addr, bytes, false); | |
3399 if (addr == requested_addr) { | |
3400 return requested_addr; | |
3401 } | |
3402 | |
3403 if (addr != NULL) { | |
3404 // mmap() is successful but it fails to reserve at the requested address | |
3405 anon_munmap(addr, bytes); | |
3406 } | |
3407 | |
3408 int i; | |
3409 for (i = 0; i < max_tries; ++i) { | |
3410 base[i] = reserve_memory(bytes); | |
3411 | |
3412 if (base[i] != NULL) { | |
3413 // Is this the block we wanted? | |
3414 if (base[i] == requested_addr) { | |
3415 size[i] = bytes; | |
3416 break; | |
3417 } | |
3418 | |
3419 // Does this overlap the block we wanted? Give back the overlapped | |
3420 // parts and try again. | |
3421 | |
3422 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; | |
3423 if (top_overlap >= 0 && top_overlap < bytes) { | |
3424 unmap_memory(base[i], top_overlap); | |
3425 base[i] += top_overlap; | |
3426 size[i] = bytes - top_overlap; | |
3427 } else { | |
3428 size_t bottom_overlap = base[i] + bytes - requested_addr; | |
3429 if (bottom_overlap >= 0 && bottom_overlap < bytes) { | |
3430 unmap_memory(requested_addr, bottom_overlap); | |
3431 size[i] = bytes - bottom_overlap; | |
3432 } else { | |
3433 size[i] = bytes; | |
3434 } | |
3435 } | |
3436 } | |
3437 } | |
3438 | |
3439 // Give back the unused reserved pieces. | |
3440 | |
3441 for (int j = 0; j < i; ++j) { | |
3442 if (base[j] != NULL) { | |
3443 unmap_memory(base[j], size[j]); | |
3444 } | |
3445 } | |
3446 | |
3447 if (i < max_tries) { | |
3448 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); | |
3449 return requested_addr; | |
3450 } else { | |
3451 _highest_vm_reserved_address = old_highest; | |
3452 return NULL; | |
3453 } | |
3454 } | |
3455 | |
3456 size_t os::read(int fd, void *buf, unsigned int nBytes) { | |
3457 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes)); | |
3458 } | |
3459 | |
3460 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation. | |
3461 // Solaris uses poll(), bsd uses park(). | |
3462 // Poll() is likely a better choice, assuming that Thread.interrupt() | |
3463 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with | |
3464 // SIGSEGV, see 4355769. | |
3465 | |
3466 int os::sleep(Thread* thread, jlong millis, bool interruptible) { | |
3467 assert(thread == Thread::current(), "thread consistency check"); | |
3468 | |
3469 ParkEvent * const slp = thread->_SleepEvent ; | |
3470 slp->reset() ; | |
3471 OrderAccess::fence() ; | |
3472 | |
3473 if (interruptible) { | |
3474 jlong prevtime = javaTimeNanos(); | |
3475 | |
3476 for (;;) { | |
3477 if (os::is_interrupted(thread, true)) { | |
3478 return OS_INTRPT; | |
3479 } | |
3480 | |
3481 jlong newtime = javaTimeNanos(); | |
3482 | |
3483 if (newtime - prevtime < 0) { | |
3484 // time moving backwards, should only happen if no monotonic clock | |
3485 // not a guarantee() because JVM should not abort on kernel/glibc bugs | |
3486 assert(!Bsd::supports_monotonic_clock(), "time moving backwards"); | |
3487 } else { | |
4712
e7dead7e90af
7117303: VM uses non-monotonic time source and complains that it is non-monotonic
johnc
parents:
4082
diff
changeset
|
3488 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; |
3960 | 3489 } |
3490 | |
3491 if(millis <= 0) { | |
3492 return OS_OK; | |
3493 } | |
3494 | |
3495 prevtime = newtime; | |
3496 | |
3497 { | |
3498 assert(thread->is_Java_thread(), "sanity check"); | |
3499 JavaThread *jt = (JavaThread *) thread; | |
3500 ThreadBlockInVM tbivm(jt); | |
3501 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); | |
3502 | |
3503 jt->set_suspend_equivalent(); | |
3504 // cleared by handle_special_suspend_equivalent_condition() or | |
3505 // java_suspend_self() via check_and_wait_while_suspended() | |
3506 | |
3507 slp->park(millis); | |
3508 | |
3509 // were we externally suspended while we were waiting? | |
3510 jt->check_and_wait_while_suspended(); | |
3511 } | |
3512 } | |
3513 } else { | |
3514 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); | |
3515 jlong prevtime = javaTimeNanos(); | |
3516 | |
3517 for (;;) { | |
3518 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on | |
3519 // the 1st iteration ... | |
3520 jlong newtime = javaTimeNanos(); | |
3521 | |
3522 if (newtime - prevtime < 0) { | |
3523 // time moving backwards, should only happen if no monotonic clock | |
3524 // not a guarantee() because JVM should not abort on kernel/glibc bugs | |
3525 assert(!Bsd::supports_monotonic_clock(), "time moving backwards"); | |
3526 } else { | |
4712
e7dead7e90af
7117303: VM uses non-monotonic time source and complains that it is non-monotonic
johnc
parents:
4082
diff
changeset
|
3527 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; |
3960 | 3528 } |
3529 | |
3530 if(millis <= 0) break ; | |
3531 | |
3532 prevtime = newtime; | |
3533 slp->park(millis); | |
3534 } | |
3535 return OS_OK ; | |
3536 } | |
3537 } | |
3538 | |
3539 int os::naked_sleep() { | |
3540 // %% make the sleep time an integer flag. for now use 1 millisec. | |
3541 return os::sleep(Thread::current(), 1, false); | |
3542 } | |
3543 | |
3544 // Sleep forever; naked call to OS-specific sleep; use with CAUTION | |
3545 void os::infinite_sleep() { | |
3546 while (true) { // sleep forever ... | |
3547 ::sleep(100); // ... 100 seconds at a time | |
3548 } | |
3549 } | |
3550 | |
3551 // Used to convert frequent JVM_Yield() to nops | |
3552 bool os::dont_yield() { | |
3553 return DontYieldALot; | |
3554 } | |
3555 | |
3556 void os::yield() { | |
3557 sched_yield(); | |
3558 } | |
3559 | |
3560 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;} | |
3561 | |
3562 void os::yield_all(int attempts) { | |
3563 // Yields to all threads, including threads with lower priorities | |
3564 // Threads on Bsd are all with same priority. The Solaris style | |
3565 // os::yield_all() with nanosleep(1ms) is not necessary. | |
3566 sched_yield(); | |
3567 } | |
3568 | |
3569 // Called from the tight loops to possibly influence time-sharing heuristics | |
3570 void os::loop_breaker(int attempts) { | |
3571 os::yield_all(attempts); | |
3572 } | |
3573 | |
3574 //////////////////////////////////////////////////////////////////////////////// | |
3575 // thread priority support | |
3576 | |
3577 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER | |
3578 // only supports dynamic priority, static priority must be zero. For real-time | |
3579 // applications, Bsd supports SCHED_RR which allows static priority (1-99). | |
3580 // However, for large multi-threaded applications, SCHED_RR is not only slower | |
3581 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out | |
3582 // of 5 runs - Sep 2005). | |
3583 // | |
3584 // The following code actually changes the niceness of kernel-thread/LWP. It | |
3585 // has an assumption that setpriority() only modifies one kernel-thread/LWP, | |
3586 // not the entire user process, and user level threads are 1:1 mapped to kernel | |
3587 // threads. It has always been the case, but could change in the future. For | |
3588 // this reason, the code should not be used as default (ThreadPriorityPolicy=0). | |
3589 // It is only used when ThreadPriorityPolicy=1 and requires root privilege. | |
3590 | |
3591 #if defined(_ALLBSD_SOURCE) && !defined(__APPLE__) | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3592 int os::java_to_os_priority[CriticalPriority + 1] = { |
3960 | 3593 19, // 0 Entry should never be used |
3594 | |
3595 0, // 1 MinPriority | |
3596 3, // 2 | |
3597 6, // 3 | |
3598 | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3599 10, // 4 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3600 15, // 5 NormPriority |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3601 18, // 6 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3602 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3603 21, // 7 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3604 25, // 8 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3605 28, // 9 NearMaxPriority |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3606 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3607 31, // 10 MaxPriority |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3608 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3609 31 // 11 CriticalPriority |
3960 | 3610 }; |
3611 #elif defined(__APPLE__) | |
3612 /* Using Mach high-level priority assignments */ | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3613 int os::java_to_os_priority[CriticalPriority + 1] = { |
3960 | 3614 0, // 0 Entry should never be used (MINPRI_USER) |
3615 | |
3616 27, // 1 MinPriority | |
3617 28, // 2 | |
3618 29, // 3 | |
3619 | |
3620 30, // 4 | |
3621 31, // 5 NormPriority (BASEPRI_DEFAULT) | |
3622 32, // 6 | |
3623 | |
3624 33, // 7 | |
3625 34, // 8 | |
3626 35, // 9 NearMaxPriority | |
3627 | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3628 36, // 10 MaxPriority |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3629 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3630 36 // 11 CriticalPriority |
3960 | 3631 }; |
3632 #else | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3633 int os::java_to_os_priority[CriticalPriority + 1] = { |
3960 | 3634 19, // 0 Entry should never be used |
3635 | |
3636 4, // 1 MinPriority | |
3637 3, // 2 | |
3638 2, // 3 | |
3639 | |
3640 1, // 4 | |
3641 0, // 5 NormPriority | |
3642 -1, // 6 | |
3643 | |
3644 -2, // 7 | |
3645 -3, // 8 | |
3646 -4, // 9 NearMaxPriority | |
3647 | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3648 -5, // 10 MaxPriority |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3649 |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3650 -5 // 11 CriticalPriority |
3960 | 3651 }; |
3652 #endif | |
3653 | |
3654 static int prio_init() { | |
3655 if (ThreadPriorityPolicy == 1) { | |
3656 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 | |
3657 // if effective uid is not root. Perhaps, a more elegant way of doing | |
3658 // this is to test CAP_SYS_NICE capability, but that will require libcap.so | |
3659 if (geteuid() != 0) { | |
3660 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { | |
3661 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd"); | |
3662 } | |
3663 ThreadPriorityPolicy = 0; | |
3664 } | |
3665 } | |
4854
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3666 if (UseCriticalJavaThreadPriority) { |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3667 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; |
de268c8a8075
7082553: Interpret Thread.setPriority(Thread.MAX_PRIORITY) to mean FX60 on Solaris 10 and 11
phh
parents:
4846
diff
changeset
|
3668 } |
3960 | 3669 return 0; |
3670 } | |
3671 | |
3672 OSReturn os::set_native_priority(Thread* thread, int newpri) { | |
3673 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK; | |
3674 | |
3675 #ifdef __OpenBSD__ | |
3676 // OpenBSD pthread_setprio starves low priority threads | |
3677 return OS_OK; | |
3678 #elif defined(__FreeBSD__) | |
3679 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri); | |
3680 #elif defined(__APPLE__) || defined(__NetBSD__) | |
3681 struct sched_param sp; | |
3682 int policy; | |
3683 pthread_t self = pthread_self(); | |
3684 | |
3685 if (pthread_getschedparam(self, &policy, &sp) != 0) | |
3686 return OS_ERR; | |
3687 | |
3688 sp.sched_priority = newpri; | |
3689 if (pthread_setschedparam(self, policy, &sp) != 0) | |
3690 return OS_ERR; | |
3691 | |
3692 return OS_OK; | |
3693 #else | |
3694 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); | |
3695 return (ret == 0) ? OS_OK : OS_ERR; | |
3696 #endif | |
3697 } | |
3698 | |
3699 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { | |
3700 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) { | |
3701 *priority_ptr = java_to_os_priority[NormPriority]; | |
3702 return OS_OK; | |
3703 } | |
3704 | |
3705 errno = 0; | |
3706 #if defined(__OpenBSD__) || defined(__FreeBSD__) | |
3707 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id()); | |
3708 #elif defined(__APPLE__) || defined(__NetBSD__) | |
3709 int policy; | |
3710 struct sched_param sp; | |
3711 | |
3712 pthread_getschedparam(pthread_self(), &policy, &sp); | |
3713 *priority_ptr = sp.sched_priority; | |
3714 #else | |
3715 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); | |
3716 #endif | |
3717 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); | |
3718 } | |
3719 | |
3720 // Hint to the underlying OS that a task switch would not be good. | |
3721 // Void return because it's a hint and can fail. | |
3722 void os::hint_no_preempt() {} | |
3723 | |
3724 //////////////////////////////////////////////////////////////////////////////// | |
3725 // suspend/resume support | |
3726 | |
3727 // the low-level signal-based suspend/resume support is a remnant from the | |
3728 // old VM-suspension that used to be for java-suspension, safepoints etc, | |
3729 // within hotspot. Now there is a single use-case for this: | |
3730 // - calling get_thread_pc() on the VMThread by the flat-profiler task | |
3731 // that runs in the watcher thread. | |
3732 // The remaining code is greatly simplified from the more general suspension | |
3733 // code that used to be used. | |
3734 // | |
3735 // The protocol is quite simple: | |
3736 // - suspend: | |
3737 // - sends a signal to the target thread | |
3738 // - polls the suspend state of the osthread using a yield loop | |
3739 // - target thread signal handler (SR_handler) sets suspend state | |
3740 // and blocks in sigsuspend until continued | |
3741 // - resume: | |
3742 // - sets target osthread state to continue | |
3743 // - sends signal to end the sigsuspend loop in the SR_handler | |
3744 // | |
3745 // Note that the SR_lock plays no role in this suspend/resume protocol. | |
3746 // | |
3747 | |
3748 static void resume_clear_context(OSThread *osthread) { | |
3749 osthread->set_ucontext(NULL); | |
3750 osthread->set_siginfo(NULL); | |
3751 | |
3752 // notify the suspend action is completed, we have now resumed | |
3753 osthread->sr.clear_suspended(); | |
3754 } | |
3755 | |
3756 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { | |
3757 osthread->set_ucontext(context); | |
3758 osthread->set_siginfo(siginfo); | |
3759 } | |
3760 | |
3761 // | |
3762 // Handler function invoked when a thread's execution is suspended or | |
3763 // resumed. We have to be careful that only async-safe functions are | |
3764 // called here (Note: most pthread functions are not async safe and | |
3765 // should be avoided.) | |
3766 // | |
3767 // Note: sigwait() is a more natural fit than sigsuspend() from an | |
3768 // interface point of view, but sigwait() prevents the signal hander | |
3769 // from being run. libpthread would get very confused by not having | |
3770 // its signal handlers run and prevents sigwait()'s use with the | |
3771 // mutex granting granting signal. | |
3772 // | |
3773 // Currently only ever called on the VMThread | |
3774 // | |
3775 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { | |
3776 // Save and restore errno to avoid confusing native code with EINTR | |
3777 // after sigsuspend. | |
3778 int old_errno = errno; | |
3779 | |
3780 Thread* thread = Thread::current(); | |
3781 OSThread* osthread = thread->osthread(); | |
3782 assert(thread->is_VM_thread(), "Must be VMThread"); | |
3783 // read current suspend action | |
3784 int action = osthread->sr.suspend_action(); | |
3785 if (action == SR_SUSPEND) { | |
3786 suspend_save_context(osthread, siginfo, context); | |
3787 | |
3788 // Notify the suspend action is about to be completed. do_suspend() | |
3789 // waits until SR_SUSPENDED is set and then returns. We will wait | |
3790 // here for a resume signal and that completes the suspend-other | |
3791 // action. do_suspend/do_resume is always called as a pair from | |
3792 // the same thread - so there are no races | |
3793 | |
3794 // notify the caller | |
3795 osthread->sr.set_suspended(); | |
3796 | |
3797 sigset_t suspend_set; // signals for sigsuspend() | |
3798 | |
3799 // get current set of blocked signals and unblock resume signal | |
3800 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); | |
3801 sigdelset(&suspend_set, SR_signum); | |
3802 | |
3803 // wait here until we are resumed | |
3804 do { | |
3805 sigsuspend(&suspend_set); | |
3806 // ignore all returns until we get a resume signal | |
3807 } while (osthread->sr.suspend_action() != SR_CONTINUE); | |
3808 | |
3809 resume_clear_context(osthread); | |
3810 | |
3811 } else { | |
3812 assert(action == SR_CONTINUE, "unexpected sr action"); | |
3813 // nothing special to do - just leave the handler | |
3814 } | |
3815 | |
3816 errno = old_errno; | |
3817 } | |
3818 | |
3819 | |
3820 static int SR_initialize() { | |
3821 struct sigaction act; | |
3822 char *s; | |
3823 /* Get signal number to use for suspend/resume */ | |
3824 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { | |
3825 int sig = ::strtol(s, 0, 10); | |
3826 if (sig > 0 || sig < NSIG) { | |
3827 SR_signum = sig; | |
3828 } | |
3829 } | |
3830 | |
3831 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, | |
3832 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); | |
3833 | |
3834 sigemptyset(&SR_sigset); | |
3835 sigaddset(&SR_sigset, SR_signum); | |
3836 | |
3837 /* Set up signal handler for suspend/resume */ | |
3838 act.sa_flags = SA_RESTART|SA_SIGINFO; | |
3839 act.sa_handler = (void (*)(int)) SR_handler; | |
3840 | |
3841 // SR_signum is blocked by default. | |
3842 // 4528190 - We also need to block pthread restart signal (32 on all | |
3843 // supported Bsd platforms). Note that BsdThreads need to block | |
3844 // this signal for all threads to work properly. So we don't have | |
3845 // to use hard-coded signal number when setting up the mask. | |
3846 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); | |
3847 | |
3848 if (sigaction(SR_signum, &act, 0) == -1) { | |
3849 return -1; | |
3850 } | |
3851 | |
3852 // Save signal flag | |
3853 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags); | |
3854 return 0; | |
3855 } | |
3856 | |
3857 static int SR_finalize() { | |
3858 return 0; | |
3859 } | |
3860 | |
3861 | |
3862 // returns true on success and false on error - really an error is fatal | |
3863 // but this seems the normal response to library errors | |
3864 static bool do_suspend(OSThread* osthread) { | |
3865 // mark as suspended and send signal | |
3866 osthread->sr.set_suspend_action(SR_SUSPEND); | |
3867 int status = pthread_kill(osthread->pthread_id(), SR_signum); | |
3868 assert_status(status == 0, status, "pthread_kill"); | |
3869 | |
3870 // check status and wait until notified of suspension | |
3871 if (status == 0) { | |
3872 for (int i = 0; !osthread->sr.is_suspended(); i++) { | |
3873 os::yield_all(i); | |
3874 } | |
3875 osthread->sr.set_suspend_action(SR_NONE); | |
3876 return true; | |
3877 } | |
3878 else { | |
3879 osthread->sr.set_suspend_action(SR_NONE); | |
3880 return false; | |
3881 } | |
3882 } | |
3883 | |
3884 static void do_resume(OSThread* osthread) { | |
3885 assert(osthread->sr.is_suspended(), "thread should be suspended"); | |
3886 osthread->sr.set_suspend_action(SR_CONTINUE); | |
3887 | |
3888 int status = pthread_kill(osthread->pthread_id(), SR_signum); | |
3889 assert_status(status == 0, status, "pthread_kill"); | |
3890 // check status and wait unit notified of resumption | |
3891 if (status == 0) { | |
3892 for (int i = 0; osthread->sr.is_suspended(); i++) { | |
3893 os::yield_all(i); | |
3894 } | |
3895 } | |
3896 osthread->sr.set_suspend_action(SR_NONE); | |
3897 } | |
3898 | |
3899 //////////////////////////////////////////////////////////////////////////////// | |
3900 // interrupt support | |
3901 | |
3902 void os::interrupt(Thread* thread) { | |
3903 assert(Thread::current() == thread || Threads_lock->owned_by_self(), | |
3904 "possibility of dangling Thread pointer"); | |
3905 | |
3906 OSThread* osthread = thread->osthread(); | |
3907 | |
3908 if (!osthread->interrupted()) { | |
3909 osthread->set_interrupted(true); | |
3910 // More than one thread can get here with the same value of osthread, | |
3911 // resulting in multiple notifications. We do, however, want the store | |
3912 // to interrupted() to be visible to other threads before we execute unpark(). | |
3913 OrderAccess::fence(); | |
3914 ParkEvent * const slp = thread->_SleepEvent ; | |
3915 if (slp != NULL) slp->unpark() ; | |
3916 } | |
3917 | |
3918 // For JSR166. Unpark even if interrupt status already was set | |
3919 if (thread->is_Java_thread()) | |
3920 ((JavaThread*)thread)->parker()->unpark(); | |
3921 | |
3922 ParkEvent * ev = thread->_ParkEvent ; | |
3923 if (ev != NULL) ev->unpark() ; | |
3924 | |
3925 } | |
3926 | |
3927 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { | |
3928 assert(Thread::current() == thread || Threads_lock->owned_by_self(), | |
3929 "possibility of dangling Thread pointer"); | |
3930 | |
3931 OSThread* osthread = thread->osthread(); | |
3932 | |
3933 bool interrupted = osthread->interrupted(); | |
3934 | |
3935 if (interrupted && clear_interrupted) { | |
3936 osthread->set_interrupted(false); | |
3937 // consider thread->_SleepEvent->reset() ... optional optimization | |
3938 } | |
3939 | |
3940 return interrupted; | |
3941 } | |
3942 | |
3943 /////////////////////////////////////////////////////////////////////////////////// | |
3944 // signal handling (except suspend/resume) | |
3945 | |
3946 // This routine may be used by user applications as a "hook" to catch signals. | |
3947 // The user-defined signal handler must pass unrecognized signals to this | |
3948 // routine, and if it returns true (non-zero), then the signal handler must | |
3949 // return immediately. If the flag "abort_if_unrecognized" is true, then this | |
3950 // routine will never retun false (zero), but instead will execute a VM panic | |
3951 // routine kill the process. | |
3952 // | |
3953 // If this routine returns false, it is OK to call it again. This allows | |
3954 // the user-defined signal handler to perform checks either before or after | |
3955 // the VM performs its own checks. Naturally, the user code would be making | |
3956 // a serious error if it tried to handle an exception (such as a null check | |
3957 // or breakpoint) that the VM was generating for its own correct operation. | |
3958 // | |
3959 // This routine may recognize any of the following kinds of signals: | |
3960 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. | |
3961 // It should be consulted by handlers for any of those signals. | |
3962 // | |
3963 // The caller of this routine must pass in the three arguments supplied | |
3964 // to the function referred to in the "sa_sigaction" (not the "sa_handler") | |
3965 // field of the structure passed to sigaction(). This routine assumes that | |
3966 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. | |
3967 // | |
3968 // Note that the VM will print warnings if it detects conflicting signal | |
3969 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". | |
3970 // | |
3971 extern "C" JNIEXPORT int | |
3972 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo, | |
3973 void* ucontext, int abort_if_unrecognized); | |
3974 | |
3975 void signalHandler(int sig, siginfo_t* info, void* uc) { | |
3976 assert(info != NULL && uc != NULL, "it must be old kernel"); | |
3977 JVM_handle_bsd_signal(sig, info, uc, true); | |
3978 } | |
3979 | |
3980 | |
3981 // This boolean allows users to forward their own non-matching signals | |
3982 // to JVM_handle_bsd_signal, harmlessly. | |
3983 bool os::Bsd::signal_handlers_are_installed = false; | |
3984 | |
3985 // For signal-chaining | |
3986 struct sigaction os::Bsd::sigact[MAXSIGNUM]; | |
3987 unsigned int os::Bsd::sigs = 0; | |
3988 bool os::Bsd::libjsig_is_loaded = false; | |
3989 typedef struct sigaction *(*get_signal_t)(int); | |
3990 get_signal_t os::Bsd::get_signal_action = NULL; | |
3991 | |
3992 struct sigaction* os::Bsd::get_chained_signal_action(int sig) { | |
3993 struct sigaction *actp = NULL; | |
3994 | |
3995 if (libjsig_is_loaded) { | |
3996 // Retrieve the old signal handler from libjsig | |
3997 actp = (*get_signal_action)(sig); | |
3998 } | |
3999 if (actp == NULL) { | |
4000 // Retrieve the preinstalled signal handler from jvm | |
4001 actp = get_preinstalled_handler(sig); | |
4002 } | |
4003 | |
4004 return actp; | |
4005 } | |
4006 | |
4007 static bool call_chained_handler(struct sigaction *actp, int sig, | |
4008 siginfo_t *siginfo, void *context) { | |
4009 // Call the old signal handler | |
4010 if (actp->sa_handler == SIG_DFL) { | |
4011 // It's more reasonable to let jvm treat it as an unexpected exception | |
4012 // instead of taking the default action. | |
4013 return false; | |
4014 } else if (actp->sa_handler != SIG_IGN) { | |
4015 if ((actp->sa_flags & SA_NODEFER) == 0) { | |
4016 // automaticlly block the signal | |
4017 sigaddset(&(actp->sa_mask), sig); | |
4018 } | |
4019 | |
4020 sa_handler_t hand; | |
4021 sa_sigaction_t sa; | |
4022 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; | |
4023 // retrieve the chained handler | |
4024 if (siginfo_flag_set) { | |
4025 sa = actp->sa_sigaction; | |
4026 } else { | |
4027 hand = actp->sa_handler; | |
4028 } | |
4029 | |
4030 if ((actp->sa_flags & SA_RESETHAND) != 0) { | |
4031 actp->sa_handler = SIG_DFL; | |
4032 } | |
4033 | |
4034 // try to honor the signal mask | |
4035 sigset_t oset; | |
4036 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); | |
4037 | |
4038 // call into the chained handler | |
4039 if (siginfo_flag_set) { | |
4040 (*sa)(sig, siginfo, context); | |
4041 } else { | |
4042 (*hand)(sig); | |
4043 } | |
4044 | |
4045 // restore the signal mask | |
4046 pthread_sigmask(SIG_SETMASK, &oset, 0); | |
4047 } | |
4048 // Tell jvm's signal handler the signal is taken care of. | |
4049 return true; | |
4050 } | |
4051 | |
4052 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) { | |
4053 bool chained = false; | |
4054 // signal-chaining | |
4055 if (UseSignalChaining) { | |
4056 struct sigaction *actp = get_chained_signal_action(sig); | |
4057 if (actp != NULL) { | |
4058 chained = call_chained_handler(actp, sig, siginfo, context); | |
4059 } | |
4060 } | |
4061 return chained; | |
4062 } | |
4063 | |
4064 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) { | |
4065 if ((( (unsigned int)1 << sig ) & sigs) != 0) { | |
4066 return &sigact[sig]; | |
4067 } | |
4068 return NULL; | |
4069 } | |
4070 | |
4071 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) { | |
4072 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
4073 sigact[sig] = oldAct; | |
4074 sigs |= (unsigned int)1 << sig; | |
4075 } | |
4076 | |
4077 // for diagnostic | |
4078 int os::Bsd::sigflags[MAXSIGNUM]; | |
4079 | |
4080 int os::Bsd::get_our_sigflags(int sig) { | |
4081 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
4082 return sigflags[sig]; | |
4083 } | |
4084 | |
4085 void os::Bsd::set_our_sigflags(int sig, int flags) { | |
4086 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
4087 sigflags[sig] = flags; | |
4088 } | |
4089 | |
4090 void os::Bsd::set_signal_handler(int sig, bool set_installed) { | |
4091 // Check for overwrite. | |
4092 struct sigaction oldAct; | |
4093 sigaction(sig, (struct sigaction*)NULL, &oldAct); | |
4094 | |
4095 void* oldhand = oldAct.sa_sigaction | |
4096 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) | |
4097 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); | |
4098 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && | |
4099 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && | |
4100 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { | |
4101 if (AllowUserSignalHandlers || !set_installed) { | |
4102 // Do not overwrite; user takes responsibility to forward to us. | |
4103 return; | |
4104 } else if (UseSignalChaining) { | |
4105 // save the old handler in jvm | |
4106 save_preinstalled_handler(sig, oldAct); | |
4107 // libjsig also interposes the sigaction() call below and saves the | |
4108 // old sigaction on it own. | |
4109 } else { | |
4110 fatal(err_msg("Encountered unexpected pre-existing sigaction handler " | |
4111 "%#lx for signal %d.", (long)oldhand, sig)); | |
4112 } | |
4113 } | |
4114 | |
4115 struct sigaction sigAct; | |
4116 sigfillset(&(sigAct.sa_mask)); | |
4117 sigAct.sa_handler = SIG_DFL; | |
4118 if (!set_installed) { | |
4119 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; | |
4120 } else { | |
4121 sigAct.sa_sigaction = signalHandler; | |
4122 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; | |
4123 } | |
4124 // Save flags, which are set by ours | |
4125 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
4126 sigflags[sig] = sigAct.sa_flags; | |
4127 | |
4128 int ret = sigaction(sig, &sigAct, &oldAct); | |
4129 assert(ret == 0, "check"); | |
4130 | |
4131 void* oldhand2 = oldAct.sa_sigaction | |
4132 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) | |
4133 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); | |
4134 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); | |
4135 } | |
4136 | |
4137 // install signal handlers for signals that HotSpot needs to | |
4138 // handle in order to support Java-level exception handling. | |
4139 | |
4140 void os::Bsd::install_signal_handlers() { | |
4141 if (!signal_handlers_are_installed) { | |
4142 signal_handlers_are_installed = true; | |
4143 | |
4144 // signal-chaining | |
4145 typedef void (*signal_setting_t)(); | |
4146 signal_setting_t begin_signal_setting = NULL; | |
4147 signal_setting_t end_signal_setting = NULL; | |
4148 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, | |
4149 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); | |
4150 if (begin_signal_setting != NULL) { | |
4151 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, | |
4152 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); | |
4153 get_signal_action = CAST_TO_FN_PTR(get_signal_t, | |
4154 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); | |
4155 libjsig_is_loaded = true; | |
4156 assert(UseSignalChaining, "should enable signal-chaining"); | |
4157 } | |
4158 if (libjsig_is_loaded) { | |
4159 // Tell libjsig jvm is setting signal handlers | |
4160 (*begin_signal_setting)(); | |
4161 } | |
4162 | |
4163 set_signal_handler(SIGSEGV, true); | |
4164 set_signal_handler(SIGPIPE, true); | |
4165 set_signal_handler(SIGBUS, true); | |
4166 set_signal_handler(SIGILL, true); | |
4167 set_signal_handler(SIGFPE, true); | |
4168 set_signal_handler(SIGXFSZ, true); | |
4169 | |
4170 #if defined(__APPLE__) | |
4171 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including | |
4172 // signals caught and handled by the JVM. To work around this, we reset the mach task | |
4173 // signal handler that's placed on our process by CrashReporter. This disables | |
4174 // CrashReporter-based reporting. | |
4175 // | |
4176 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes | |
4177 // on caught fatal signals. | |
4178 // | |
4179 // Additionally, gdb installs both standard BSD signal handlers, and mach exception | |
4180 // handlers. By replacing the existing task exception handler, we disable gdb's mach | |
4181 // exception handling, while leaving the standard BSD signal handlers functional. | |
4182 kern_return_t kr; | |
4183 kr = task_set_exception_ports(mach_task_self(), | |
4184 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC, | |
4185 MACH_PORT_NULL, | |
4186 EXCEPTION_STATE_IDENTITY, | |
4187 MACHINE_THREAD_STATE); | |
4188 | |
4189 assert(kr == KERN_SUCCESS, "could not set mach task signal handler"); | |
4190 #endif | |
4191 | |
4192 if (libjsig_is_loaded) { | |
4193 // Tell libjsig jvm finishes setting signal handlers | |
4194 (*end_signal_setting)(); | |
4195 } | |
4196 | |
4197 // We don't activate signal checker if libjsig is in place, we trust ourselves | |
4198 // and if UserSignalHandler is installed all bets are off | |
4199 if (CheckJNICalls) { | |
4200 if (libjsig_is_loaded) { | |
4201 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); | |
4202 check_signals = false; | |
4203 } | |
4204 if (AllowUserSignalHandlers) { | |
4205 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); | |
4206 check_signals = false; | |
4207 } | |
4208 } | |
4209 } | |
4210 } | |
4211 | |
4212 #ifndef _ALLBSD_SOURCE | |
4213 // This is the fastest way to get thread cpu time on Bsd. | |
4214 // Returns cpu time (user+sys) for any thread, not only for current. | |
4215 // POSIX compliant clocks are implemented in the kernels 2.6.16+. | |
4216 // It might work on 2.6.10+ with a special kernel/glibc patch. | |
4217 // For reference, please, see IEEE Std 1003.1-2004: | |
4218 // http://www.unix.org/single_unix_specification | |
4219 | |
4220 jlong os::Bsd::fast_thread_cpu_time(clockid_t clockid) { | |
4221 struct timespec tp; | |
4222 int rc = os::Bsd::clock_gettime(clockid, &tp); | |
4223 assert(rc == 0, "clock_gettime is expected to return 0 code"); | |
4224 | |
4712
e7dead7e90af
7117303: VM uses non-monotonic time source and complains that it is non-monotonic
johnc
parents:
4082
diff
changeset
|
4225 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec; |
3960 | 4226 } |
4227 #endif | |
4228 | |
4229 ///// | |
4230 // glibc on Bsd platform uses non-documented flag | |
4231 // to indicate, that some special sort of signal | |
4232 // trampoline is used. | |
4233 // We will never set this flag, and we should | |
4234 // ignore this flag in our diagnostic | |
4235 #ifdef SIGNIFICANT_SIGNAL_MASK | |
4236 #undef SIGNIFICANT_SIGNAL_MASK | |
4237 #endif | |
4238 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000) | |
4239 | |
4240 static const char* get_signal_handler_name(address handler, | |
4241 char* buf, int buflen) { | |
4242 int offset; | |
4243 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); | |
4244 if (found) { | |
4245 // skip directory names | |
4246 const char *p1, *p2; | |
4247 p1 = buf; | |
4248 size_t len = strlen(os::file_separator()); | |
4249 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; | |
4250 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); | |
4251 } else { | |
4252 jio_snprintf(buf, buflen, PTR_FORMAT, handler); | |
4253 } | |
4254 return buf; | |
4255 } | |
4256 | |
4257 static void print_signal_handler(outputStream* st, int sig, | |
4258 char* buf, size_t buflen) { | |
4259 struct sigaction sa; | |
4260 | |
4261 sigaction(sig, NULL, &sa); | |
4262 | |
4263 // See comment for SIGNIFICANT_SIGNAL_MASK define | |
4264 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; | |
4265 | |
4266 st->print("%s: ", os::exception_name(sig, buf, buflen)); | |
4267 | |
4268 address handler = (sa.sa_flags & SA_SIGINFO) | |
4269 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) | |
4270 : CAST_FROM_FN_PTR(address, sa.sa_handler); | |
4271 | |
4272 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { | |
4273 st->print("SIG_DFL"); | |
4274 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { | |
4275 st->print("SIG_IGN"); | |
4276 } else { | |
4277 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); | |
4278 } | |
4279 | |
4280 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask); | |
4281 | |
4282 address rh = VMError::get_resetted_sighandler(sig); | |
4283 // May be, handler was resetted by VMError? | |
4284 if(rh != NULL) { | |
4285 handler = rh; | |
4286 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; | |
4287 } | |
4288 | |
4289 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags); | |
4290 | |
4291 // Check: is it our handler? | |
4292 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || | |
4293 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { | |
4294 // It is our signal handler | |
4295 // check for flags, reset system-used one! | |
4296 if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) { | |
4297 st->print( | |
4298 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", | |
4299 os::Bsd::get_our_sigflags(sig)); | |
4300 } | |
4301 } | |
4302 st->cr(); | |
4303 } | |
4304 | |
4305 | |
4306 #define DO_SIGNAL_CHECK(sig) \ | |
4307 if (!sigismember(&check_signal_done, sig)) \ | |
4308 os::Bsd::check_signal_handler(sig) | |
4309 | |
4310 // This method is a periodic task to check for misbehaving JNI applications | |
4311 // under CheckJNI, we can add any periodic checks here | |
4312 | |
4313 void os::run_periodic_checks() { | |
4314 | |
4315 if (check_signals == false) return; | |
4316 | |
4317 // SEGV and BUS if overridden could potentially prevent | |
4318 // generation of hs*.log in the event of a crash, debugging | |
4319 // such a case can be very challenging, so we absolutely | |
4320 // check the following for a good measure: | |
4321 DO_SIGNAL_CHECK(SIGSEGV); | |
4322 DO_SIGNAL_CHECK(SIGILL); | |
4323 DO_SIGNAL_CHECK(SIGFPE); | |
4324 DO_SIGNAL_CHECK(SIGBUS); | |
4325 DO_SIGNAL_CHECK(SIGPIPE); | |
4326 DO_SIGNAL_CHECK(SIGXFSZ); | |
4327 | |
4328 | |
4329 // ReduceSignalUsage allows the user to override these handlers | |
4330 // see comments at the very top and jvm_solaris.h | |
4331 if (!ReduceSignalUsage) { | |
4332 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); | |
4333 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); | |
4334 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); | |
4335 DO_SIGNAL_CHECK(BREAK_SIGNAL); | |
4336 } | |
4337 | |
4338 DO_SIGNAL_CHECK(SR_signum); | |
4339 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); | |
4340 } | |
4341 | |
4342 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); | |
4343 | |
4344 static os_sigaction_t os_sigaction = NULL; | |
4345 | |
4346 void os::Bsd::check_signal_handler(int sig) { | |
4347 char buf[O_BUFLEN]; | |
4348 address jvmHandler = NULL; | |
4349 | |
4350 | |
4351 struct sigaction act; | |
4352 if (os_sigaction == NULL) { | |
4353 // only trust the default sigaction, in case it has been interposed | |
4354 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); | |
4355 if (os_sigaction == NULL) return; | |
4356 } | |
4357 | |
4358 os_sigaction(sig, (struct sigaction*)NULL, &act); | |
4359 | |
4360 | |
4361 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; | |
4362 | |
4363 address thisHandler = (act.sa_flags & SA_SIGINFO) | |
4364 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) | |
4365 : CAST_FROM_FN_PTR(address, act.sa_handler) ; | |
4366 | |
4367 | |
4368 switch(sig) { | |
4369 case SIGSEGV: | |
4370 case SIGBUS: | |
4371 case SIGFPE: | |
4372 case SIGPIPE: | |
4373 case SIGILL: | |
4374 case SIGXFSZ: | |
4375 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); | |
4376 break; | |
4377 | |
4378 case SHUTDOWN1_SIGNAL: | |
4379 case SHUTDOWN2_SIGNAL: | |
4380 case SHUTDOWN3_SIGNAL: | |
4381 case BREAK_SIGNAL: | |
4382 jvmHandler = (address)user_handler(); | |
4383 break; | |
4384 | |
4385 case INTERRUPT_SIGNAL: | |
4386 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); | |
4387 break; | |
4388 | |
4389 default: | |
4390 if (sig == SR_signum) { | |
4391 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); | |
4392 } else { | |
4393 return; | |
4394 } | |
4395 break; | |
4396 } | |
4397 | |
4398 if (thisHandler != jvmHandler) { | |
4399 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); | |
4400 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); | |
4401 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); | |
4402 // No need to check this sig any longer | |
4403 sigaddset(&check_signal_done, sig); | |
4404 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) { | |
4405 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); | |
4406 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig)); | |
4407 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); | |
4408 // No need to check this sig any longer | |
4409 sigaddset(&check_signal_done, sig); | |
4410 } | |
4411 | |
4412 // Dump all the signal | |
4413 if (sigismember(&check_signal_done, sig)) { | |
4414 print_signal_handlers(tty, buf, O_BUFLEN); | |
4415 } | |
4416 } | |
4417 | |
4418 extern void report_error(char* file_name, int line_no, char* title, char* format, ...); | |
4419 | |
4420 extern bool signal_name(int signo, char* buf, size_t len); | |
4421 | |
4422 const char* os::exception_name(int exception_code, char* buf, size_t size) { | |
4423 if (0 < exception_code && exception_code <= SIGRTMAX) { | |
4424 // signal | |
4425 if (!signal_name(exception_code, buf, size)) { | |
4426 jio_snprintf(buf, size, "SIG%d", exception_code); | |
4427 } | |
4428 return buf; | |
4429 } else { | |
4430 return NULL; | |
4431 } | |
4432 } | |
4433 | |
4434 // this is called _before_ the most of global arguments have been parsed | |
4435 void os::init(void) { | |
4436 char dummy; /* used to get a guess on initial stack address */ | |
4437 // first_hrtime = gethrtime(); | |
4438 | |
4439 // With BsdThreads the JavaMain thread pid (primordial thread) | |
4440 // is different than the pid of the java launcher thread. | |
4441 // So, on Bsd, the launcher thread pid is passed to the VM | |
4442 // via the sun.java.launcher.pid property. | |
4443 // Use this property instead of getpid() if it was correctly passed. | |
4444 // See bug 6351349. | |
4445 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); | |
4446 | |
4447 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); | |
4448 | |
4449 clock_tics_per_sec = CLK_TCK; | |
4450 | |
4451 init_random(1234567); | |
4452 | |
4453 ThreadCritical::initialize(); | |
4454 | |
4455 Bsd::set_page_size(getpagesize()); | |
4456 if (Bsd::page_size() == -1) { | |
4457 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)", | |
4458 strerror(errno))); | |
4459 } | |
4460 init_page_sizes((size_t) Bsd::page_size()); | |
4461 | |
4462 Bsd::initialize_system_info(); | |
4463 | |
4464 // main_thread points to the aboriginal thread | |
4465 Bsd::_main_thread = pthread_self(); | |
4466 | |
4467 Bsd::clock_init(); | |
4468 initial_time_count = os::elapsed_counter(); | |
4469 | |
4470 #ifdef __APPLE__ | |
4471 // XXXDARWIN | |
4472 // Work around the unaligned VM callbacks in hotspot's | |
4473 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on | |
4474 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces | |
4475 // alignment when doing symbol lookup. To work around this, we force early | |
4476 // binding of all symbols now, thus binding when alignment is known-good. | |
4477 _dyld_bind_fully_image_containing_address((const void *) &os::init); | |
4478 #endif | |
4479 } | |
4480 | |
4481 // To install functions for atexit system call | |
4482 extern "C" { | |
4483 static void perfMemory_exit_helper() { | |
4484 perfMemory_exit(); | |
4485 } | |
4486 } | |
4487 | |
4488 // this is called _after_ the global arguments have been parsed | |
4489 jint os::init_2(void) | |
4490 { | |
4491 #ifndef _ALLBSD_SOURCE | |
4492 Bsd::fast_thread_clock_init(); | |
4493 #endif | |
4494 | |
4495 // Allocate a single page and mark it as readable for safepoint polling | |
4496 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); | |
4497 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" ); | |
4498 | |
4499 os::set_polling_page( polling_page ); | |
4500 | |
4501 #ifndef PRODUCT | |
4502 if(Verbose && PrintMiscellaneous) | |
4503 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); | |
4504 #endif | |
4505 | |
4506 if (!UseMembar) { | |
4507 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); | |
4508 guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page"); | |
4509 os::set_memory_serialize_page( mem_serialize_page ); | |
4510 | |
4511 #ifndef PRODUCT | |
4512 if(Verbose && PrintMiscellaneous) | |
4513 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); | |
4514 #endif | |
4515 } | |
4516 | |
4517 os::large_page_init(); | |
4518 | |
4519 // initialize suspend/resume support - must do this before signal_sets_init() | |
4520 if (SR_initialize() != 0) { | |
4521 perror("SR_initialize failed"); | |
4522 return JNI_ERR; | |
4523 } | |
4524 | |
4525 Bsd::signal_sets_init(); | |
4526 Bsd::install_signal_handlers(); | |
4527 | |
4528 // Check minimum allowable stack size for thread creation and to initialize | |
4529 // the java system classes, including StackOverflowError - depends on page | |
4530 // size. Add a page for compiler2 recursion in main thread. | |
4531 // Add in 2*BytesPerWord times page size to account for VM stack during | |
4532 // class initialization depending on 32 or 64 bit VM. | |
4533 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed, | |
4534 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+ | |
4535 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size()); | |
4536 | |
4537 size_t threadStackSizeInBytes = ThreadStackSize * K; | |
4538 if (threadStackSizeInBytes != 0 && | |
4539 threadStackSizeInBytes < os::Bsd::min_stack_allowed) { | |
4540 tty->print_cr("\nThe stack size specified is too small, " | |
4541 "Specify at least %dk", | |
4542 os::Bsd::min_stack_allowed/ K); | |
4543 return JNI_ERR; | |
4544 } | |
4545 | |
4546 // Make the stack size a multiple of the page size so that | |
4547 // the yellow/red zones can be guarded. | |
4548 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, | |
4549 vm_page_size())); | |
4550 | |
4551 #ifndef _ALLBSD_SOURCE | |
4552 Bsd::capture_initial_stack(JavaThread::stack_size_at_create()); | |
4553 | |
4554 Bsd::libpthread_init(); | |
4555 if (PrintMiscellaneous && (Verbose || WizardMode)) { | |
4556 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n", | |
4557 Bsd::glibc_version(), Bsd::libpthread_version(), | |
4558 Bsd::is_floating_stack() ? "floating stack" : "fixed stack"); | |
4559 } | |
4560 | |
4561 if (UseNUMA) { | |
4562 if (!Bsd::libnuma_init()) { | |
4563 UseNUMA = false; | |
4564 } else { | |
4565 if ((Bsd::numa_max_node() < 1)) { | |
4566 // There's only one node(they start from 0), disable NUMA. | |
4567 UseNUMA = false; | |
4568 } | |
4569 } | |
4570 // With SHM large pages we cannot uncommit a page, so there's not way | |
4571 // we can make the adaptive lgrp chunk resizing work. If the user specified | |
4572 // both UseNUMA and UseLargePages (or UseSHM) on the command line - warn and | |
4573 // disable adaptive resizing. | |
4574 if (UseNUMA && UseLargePages && UseSHM) { | |
4575 if (!FLAG_IS_DEFAULT(UseNUMA)) { | |
4576 if (FLAG_IS_DEFAULT(UseLargePages) && FLAG_IS_DEFAULT(UseSHM)) { | |
4577 UseLargePages = false; | |
4578 } else { | |
4579 warning("UseNUMA is not fully compatible with SHM large pages, disabling adaptive resizing"); | |
4580 UseAdaptiveSizePolicy = false; | |
4581 UseAdaptiveNUMAChunkSizing = false; | |
4582 } | |
4583 } else { | |
4584 UseNUMA = false; | |
4585 } | |
4586 } | |
4587 if (!UseNUMA && ForceNUMA) { | |
4588 UseNUMA = true; | |
4589 } | |
4590 } | |
4591 #endif | |
4592 | |
4593 if (MaxFDLimit) { | |
4594 // set the number of file descriptors to max. print out error | |
4595 // if getrlimit/setrlimit fails but continue regardless. | |
4596 struct rlimit nbr_files; | |
4597 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); | |
4598 if (status != 0) { | |
4599 if (PrintMiscellaneous && (Verbose || WizardMode)) | |
4600 perror("os::init_2 getrlimit failed"); | |
4601 } else { | |
4602 nbr_files.rlim_cur = nbr_files.rlim_max; | |
4603 | |
4604 #ifdef __APPLE__ | |
4605 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if | |
4606 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must | |
4607 // be used instead | |
4608 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur); | |
4609 #endif | |
4610 | |
4611 status = setrlimit(RLIMIT_NOFILE, &nbr_files); | |
4612 if (status != 0) { | |
4613 if (PrintMiscellaneous && (Verbose || WizardMode)) | |
4614 perror("os::init_2 setrlimit failed"); | |
4615 } | |
4616 } | |
4617 } | |
4618 | |
4619 #ifndef _ALLBSD_SOURCE | |
4620 // Initialize lock used to serialize thread creation (see os::create_thread) | |
4621 Bsd::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false)); | |
4622 #endif | |
4623 | |
4624 // at-exit methods are called in the reverse order of their registration. | |
4625 // atexit functions are called on return from main or as a result of a | |
4626 // call to exit(3C). There can be only 32 of these functions registered | |
4627 // and atexit() does not set errno. | |
4628 | |
4629 if (PerfAllowAtExitRegistration) { | |
4630 // only register atexit functions if PerfAllowAtExitRegistration is set. | |
4631 // atexit functions can be delayed until process exit time, which | |
4632 // can be problematic for embedded VM situations. Embedded VMs should | |
4633 // call DestroyJavaVM() to assure that VM resources are released. | |
4634 | |
4635 // note: perfMemory_exit_helper atexit function may be removed in | |
4636 // the future if the appropriate cleanup code can be added to the | |
4637 // VM_Exit VMOperation's doit method. | |
4638 if (atexit(perfMemory_exit_helper) != 0) { | |
4639 warning("os::init2 atexit(perfMemory_exit_helper) failed"); | |
4640 } | |
4641 } | |
4642 | |
4643 // initialize thread priority policy | |
4644 prio_init(); | |
4645 | |
4006 | 4646 #ifdef __APPLE__ |
4647 // dynamically link to objective c gc registration | |
4648 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY); | |
4649 if (handleLibObjc != NULL) { | |
4650 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER); | |
4651 } | |
4652 #endif | |
4653 | |
3960 | 4654 return JNI_OK; |
4655 } | |
4656 | |
4657 // this is called at the end of vm_initialization | |
4658 void os::init_3(void) { } | |
4659 | |
4660 // Mark the polling page as unreadable | |
4661 void os::make_polling_page_unreadable(void) { | |
4662 if( !guard_memory((char*)_polling_page, Bsd::page_size()) ) | |
4663 fatal("Could not disable polling page"); | |
4664 }; | |
4665 | |
4666 // Mark the polling page as readable | |
4667 void os::make_polling_page_readable(void) { | |
4668 if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) { | |
4669 fatal("Could not enable polling page"); | |
4670 } | |
4671 }; | |
4672 | |
4673 int os::active_processor_count() { | |
4674 #ifdef _ALLBSD_SOURCE | |
4675 return _processor_count; | |
4676 #else | |
4677 // Bsd doesn't yet have a (official) notion of processor sets, | |
4678 // so just return the number of online processors. | |
4679 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); | |
4680 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); | |
4681 return online_cpus; | |
4682 #endif | |
4683 } | |
4684 | |
4006 | 4685 void os::set_native_thread_name(const char *name) { |
4686 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 | |
4687 // This is only supported in Snow Leopard and beyond | |
4688 if (name != NULL) { | |
4689 // Add a "Java: " prefix to the name | |
4690 char buf[MAXTHREADNAMESIZE]; | |
4691 snprintf(buf, sizeof(buf), "Java: %s", name); | |
4692 pthread_setname_np(buf); | |
4693 } | |
4694 #endif | |
4695 } | |
4696 | |
3960 | 4697 bool os::distribute_processes(uint length, uint* distribution) { |
4698 // Not yet implemented. | |
4699 return false; | |
4700 } | |
4701 | |
4702 bool os::bind_to_processor(uint processor_id) { | |
4703 // Not yet implemented. | |
4704 return false; | |
4705 } | |
4706 | |
4707 /// | |
4708 | |
4709 // Suspends the target using the signal mechanism and then grabs the PC before | |
4710 // resuming the target. Used by the flat-profiler only | |
4711 ExtendedPC os::get_thread_pc(Thread* thread) { | |
4712 // Make sure that it is called by the watcher for the VMThread | |
4713 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); | |
4714 assert(thread->is_VM_thread(), "Can only be called for VMThread"); | |
4715 | |
4716 ExtendedPC epc; | |
4717 | |
4718 OSThread* osthread = thread->osthread(); | |
4719 if (do_suspend(osthread)) { | |
4720 if (osthread->ucontext() != NULL) { | |
4721 epc = os::Bsd::ucontext_get_pc(osthread->ucontext()); | |
4722 } else { | |
4723 // NULL context is unexpected, double-check this is the VMThread | |
4724 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); | |
4725 } | |
4726 do_resume(osthread); | |
4727 } | |
4728 // failure means pthread_kill failed for some reason - arguably this is | |
4729 // a fatal problem, but such problems are ignored elsewhere | |
4730 | |
4731 return epc; | |
4732 } | |
4733 | |
4734 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) | |
4735 { | |
4736 #ifdef _ALLBSD_SOURCE | |
4737 return pthread_cond_timedwait(_cond, _mutex, _abstime); | |
4738 #else | |
4739 if (is_NPTL()) { | |
4740 return pthread_cond_timedwait(_cond, _mutex, _abstime); | |
4741 } else { | |
4742 #ifndef IA64 | |
4743 // 6292965: BsdThreads pthread_cond_timedwait() resets FPU control | |
4744 // word back to default 64bit precision if condvar is signaled. Java | |
4745 // wants 53bit precision. Save and restore current value. | |
4746 int fpu = get_fpu_control_word(); | |
4747 #endif // IA64 | |
4748 int status = pthread_cond_timedwait(_cond, _mutex, _abstime); | |
4749 #ifndef IA64 | |
4750 set_fpu_control_word(fpu); | |
4751 #endif // IA64 | |
4752 return status; | |
4753 } | |
4754 #endif | |
4755 } | |
4756 | |
4757 //////////////////////////////////////////////////////////////////////////////// | |
4758 // debug support | |
4759 | |
4760 static address same_page(address x, address y) { | |
4761 int page_bits = -os::vm_page_size(); | |
4762 if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) | |
4763 return x; | |
4764 else if (x > y) | |
4765 return (address)(intptr_t(y) | ~page_bits) + 1; | |
4766 else | |
4767 return (address)(intptr_t(y) & page_bits); | |
4768 } | |
4769 | |
4770 bool os::find(address addr, outputStream* st) { | |
4771 Dl_info dlinfo; | |
4772 memset(&dlinfo, 0, sizeof(dlinfo)); | |
4773 if (dladdr(addr, &dlinfo)) { | |
4774 st->print(PTR_FORMAT ": ", addr); | |
4775 if (dlinfo.dli_sname != NULL) { | |
4776 st->print("%s+%#x", dlinfo.dli_sname, | |
4777 addr - (intptr_t)dlinfo.dli_saddr); | |
4778 } else if (dlinfo.dli_fname) { | |
4779 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); | |
4780 } else { | |
4781 st->print("<absolute address>"); | |
4782 } | |
4783 if (dlinfo.dli_fname) { | |
4784 st->print(" in %s", dlinfo.dli_fname); | |
4785 } | |
4786 if (dlinfo.dli_fbase) { | |
4787 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); | |
4788 } | |
4789 st->cr(); | |
4790 | |
4791 if (Verbose) { | |
4792 // decode some bytes around the PC | |
4793 address begin = same_page(addr-40, addr); | |
4794 address end = same_page(addr+40, addr); | |
4795 address lowest = (address) dlinfo.dli_sname; | |
4796 if (!lowest) lowest = (address) dlinfo.dli_fbase; | |
4797 if (begin < lowest) begin = lowest; | |
4798 Dl_info dlinfo2; | |
4799 if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr | |
4800 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) | |
4801 end = (address) dlinfo2.dli_saddr; | |
4802 Disassembler::decode(begin, end, st); | |
4803 } | |
4804 return true; | |
4805 } | |
4806 return false; | |
4807 } | |
4808 | |
4809 //////////////////////////////////////////////////////////////////////////////// | |
4810 // misc | |
4811 | |
4812 // This does not do anything on Bsd. This is basically a hook for being | |
4813 // able to use structured exception handling (thread-local exception filters) | |
4814 // on, e.g., Win32. | |
4815 void | |
4816 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, | |
4817 JavaCallArguments* args, Thread* thread) { | |
4818 f(value, method, args, thread); | |
4819 } | |
4820 | |
4821 void os::print_statistics() { | |
4822 } | |
4823 | |
4824 int os::message_box(const char* title, const char* message) { | |
4825 int i; | |
4826 fdStream err(defaultStream::error_fd()); | |
4827 for (i = 0; i < 78; i++) err.print_raw("="); | |
4828 err.cr(); | |
4829 err.print_raw_cr(title); | |
4830 for (i = 0; i < 78; i++) err.print_raw("-"); | |
4831 err.cr(); | |
4832 err.print_raw_cr(message); | |
4833 for (i = 0; i < 78; i++) err.print_raw("="); | |
4834 err.cr(); | |
4835 | |
4836 char buf[16]; | |
4837 // Prevent process from exiting upon "read error" without consuming all CPU | |
4838 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } | |
4839 | |
4840 return buf[0] == 'y' || buf[0] == 'Y'; | |
4841 } | |
4842 | |
4843 int os::stat(const char *path, struct stat *sbuf) { | |
4844 char pathbuf[MAX_PATH]; | |
4845 if (strlen(path) > MAX_PATH - 1) { | |
4846 errno = ENAMETOOLONG; | |
4847 return -1; | |
4848 } | |
4849 os::native_path(strcpy(pathbuf, path)); | |
4850 return ::stat(pathbuf, sbuf); | |
4851 } | |
4852 | |
4853 bool os::check_heap(bool force) { | |
4854 return true; | |
4855 } | |
4856 | |
4857 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { | |
4858 return ::vsnprintf(buf, count, format, args); | |
4859 } | |
4860 | |
4861 // Is a (classpath) directory empty? | |
4862 bool os::dir_is_empty(const char* path) { | |
4863 DIR *dir = NULL; | |
4864 struct dirent *ptr; | |
4865 | |
4866 dir = opendir(path); | |
4867 if (dir == NULL) return true; | |
4868 | |
4869 /* Scan the directory */ | |
4870 bool result = true; | |
4871 char buf[sizeof(struct dirent) + MAX_PATH]; | |
4872 while (result && (ptr = ::readdir(dir)) != NULL) { | |
4873 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { | |
4874 result = false; | |
4875 } | |
4876 } | |
4877 closedir(dir); | |
4878 return result; | |
4879 } | |
4880 | |
4881 // This code originates from JDK's sysOpen and open64_w | |
4882 // from src/solaris/hpi/src/system_md.c | |
4883 | |
4884 #ifndef O_DELETE | |
4885 #define O_DELETE 0x10000 | |
4886 #endif | |
4887 | |
4888 // Open a file. Unlink the file immediately after open returns | |
4889 // if the specified oflag has the O_DELETE flag set. | |
4890 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c | |
4891 | |
4892 int os::open(const char *path, int oflag, int mode) { | |
4893 | |
4894 if (strlen(path) > MAX_PATH - 1) { | |
4895 errno = ENAMETOOLONG; | |
4896 return -1; | |
4897 } | |
4898 int fd; | |
4899 int o_delete = (oflag & O_DELETE); | |
4900 oflag = oflag & ~O_DELETE; | |
4901 | |
4902 fd = ::open(path, oflag, mode); | |
4903 if (fd == -1) return -1; | |
4904 | |
4905 //If the open succeeded, the file might still be a directory | |
4906 { | |
4907 struct stat buf; | |
4908 int ret = ::fstat(fd, &buf); | |
4909 int st_mode = buf.st_mode; | |
4910 | |
4911 if (ret != -1) { | |
4912 if ((st_mode & S_IFMT) == S_IFDIR) { | |
4913 errno = EISDIR; | |
4914 ::close(fd); | |
4915 return -1; | |
4916 } | |
4917 } else { | |
4918 ::close(fd); | |
4919 return -1; | |
4920 } | |
4921 } | |
4922 | |
4923 /* | |
4924 * All file descriptors that are opened in the JVM and not | |
4925 * specifically destined for a subprocess should have the | |
4926 * close-on-exec flag set. If we don't set it, then careless 3rd | |
4927 * party native code might fork and exec without closing all | |
4928 * appropriate file descriptors (e.g. as we do in closeDescriptors in | |
4929 * UNIXProcess.c), and this in turn might: | |
4930 * | |
4931 * - cause end-of-file to fail to be detected on some file | |
4932 * descriptors, resulting in mysterious hangs, or | |
4933 * | |
4934 * - might cause an fopen in the subprocess to fail on a system | |
4935 * suffering from bug 1085341. | |
4936 * | |
4937 * (Yes, the default setting of the close-on-exec flag is a Unix | |
4938 * design flaw) | |
4939 * | |
4940 * See: | |
4941 * 1085341: 32-bit stdio routines should support file descriptors >255 | |
4942 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed | |
4943 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 | |
4944 */ | |
4945 #ifdef FD_CLOEXEC | |
4946 { | |
4947 int flags = ::fcntl(fd, F_GETFD); | |
4948 if (flags != -1) | |
4949 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); | |
4950 } | |
4951 #endif | |
4952 | |
4953 if (o_delete != 0) { | |
4954 ::unlink(path); | |
4955 } | |
4956 return fd; | |
4957 } | |
4958 | |
4959 | |
4960 // create binary file, rewriting existing file if required | |
4961 int os::create_binary_file(const char* path, bool rewrite_existing) { | |
4962 int oflags = O_WRONLY | O_CREAT; | |
4963 if (!rewrite_existing) { | |
4964 oflags |= O_EXCL; | |
4965 } | |
4966 return ::open(path, oflags, S_IREAD | S_IWRITE); | |
4967 } | |
4968 | |
4969 // return current position of file pointer | |
4970 jlong os::current_file_offset(int fd) { | |
4971 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR); | |
4972 } | |
4973 | |
4974 // move file pointer to the specified offset | |
4975 jlong os::seek_to_file_offset(int fd, jlong offset) { | |
4976 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET); | |
4977 } | |
4978 | |
4979 // This code originates from JDK's sysAvailable | |
4980 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c | |
4981 | |
4982 int os::available(int fd, jlong *bytes) { | |
4983 jlong cur, end; | |
4984 int mode; | |
4985 struct stat buf; | |
4986 | |
4987 if (::fstat(fd, &buf) >= 0) { | |
4988 mode = buf.st_mode; | |
4989 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { | |
4990 /* | |
4991 * XXX: is the following call interruptible? If so, this might | |
4992 * need to go through the INTERRUPT_IO() wrapper as for other | |
4993 * blocking, interruptible calls in this file. | |
4994 */ | |
4995 int n; | |
4996 if (::ioctl(fd, FIONREAD, &n) >= 0) { | |
4997 *bytes = n; | |
4998 return 1; | |
4999 } | |
5000 } | |
5001 } | |
5002 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) { | |
5003 return 0; | |
5004 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) { | |
5005 return 0; | |
5006 } else if (::lseek(fd, cur, SEEK_SET) == -1) { | |
5007 return 0; | |
5008 } | |
5009 *bytes = end - cur; | |
5010 return 1; | |
5011 } | |
5012 | |
5013 int os::socket_available(int fd, jint *pbytes) { | |
5014 if (fd < 0) | |
5015 return OS_OK; | |
5016 | |
5017 int ret; | |
5018 | |
5019 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret); | |
5020 | |
5021 //%% note ioctl can return 0 when successful, JVM_SocketAvailable | |
5022 // is expected to return 0 on failure and 1 on success to the jdk. | |
5023 | |
5024 return (ret == OS_ERR) ? 0 : 1; | |
5025 } | |
5026 | |
5027 // Map a block of memory. | |
5028 char* os::map_memory(int fd, const char* file_name, size_t file_offset, | |
5029 char *addr, size_t bytes, bool read_only, | |
5030 bool allow_exec) { | |
5031 int prot; | |
5032 int flags; | |
5033 | |
5034 if (read_only) { | |
5035 prot = PROT_READ; | |
5036 flags = MAP_SHARED; | |
5037 } else { | |
5038 prot = PROT_READ | PROT_WRITE; | |
5039 flags = MAP_PRIVATE; | |
5040 } | |
5041 | |
5042 if (allow_exec) { | |
5043 prot |= PROT_EXEC; | |
5044 } | |
5045 | |
5046 if (addr != NULL) { | |
5047 flags |= MAP_FIXED; | |
5048 } | |
5049 | |
5050 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, | |
5051 fd, file_offset); | |
5052 if (mapped_address == MAP_FAILED) { | |
5053 return NULL; | |
5054 } | |
5055 return mapped_address; | |
5056 } | |
5057 | |
5058 | |
5059 // Remap a block of memory. | |
5060 char* os::remap_memory(int fd, const char* file_name, size_t file_offset, | |
5061 char *addr, size_t bytes, bool read_only, | |
5062 bool allow_exec) { | |
5063 // same as map_memory() on this OS | |
5064 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, | |
5065 allow_exec); | |
5066 } | |
5067 | |
5068 | |
5069 // Unmap a block of memory. | |
5070 bool os::unmap_memory(char* addr, size_t bytes) { | |
5071 return munmap(addr, bytes) == 0; | |
5072 } | |
5073 | |
5074 #ifndef _ALLBSD_SOURCE | |
5075 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time); | |
5076 | |
5077 static clockid_t thread_cpu_clockid(Thread* thread) { | |
5078 pthread_t tid = thread->osthread()->pthread_id(); | |
5079 clockid_t clockid; | |
5080 | |
5081 // Get thread clockid | |
5082 int rc = os::Bsd::pthread_getcpuclockid(tid, &clockid); | |
5083 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code"); | |
5084 return clockid; | |
5085 } | |
5086 #endif | |
5087 | |
5088 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) | |
5089 // are used by JVM M&M and JVMTI to get user+sys or user CPU time | |
5090 // of a thread. | |
5091 // | |
5092 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns | |
5093 // the fast estimate available on the platform. | |
5094 | |
5095 jlong os::current_thread_cpu_time() { | |
5096 #ifdef __APPLE__ | |
5097 return os::thread_cpu_time(Thread::current(), true /* user + sys */); | |
5098 #elif !defined(_ALLBSD_SOURCE) | |
5099 if (os::Bsd::supports_fast_thread_cpu_time()) { | |
5100 return os::Bsd::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); | |
5101 } else { | |
5102 // return user + sys since the cost is the same | |
5103 return slow_thread_cpu_time(Thread::current(), true /* user + sys */); | |
5104 } | |
5105 #endif | |
5106 } | |
5107 | |
5108 jlong os::thread_cpu_time(Thread* thread) { | |
5109 #ifndef _ALLBSD_SOURCE | |
5110 // consistent with what current_thread_cpu_time() returns | |
5111 if (os::Bsd::supports_fast_thread_cpu_time()) { | |
5112 return os::Bsd::fast_thread_cpu_time(thread_cpu_clockid(thread)); | |
5113 } else { | |
5114 return slow_thread_cpu_time(thread, true /* user + sys */); | |
5115 } | |
5116 #endif | |
5117 } | |
5118 | |
5119 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { | |
5120 #ifdef __APPLE__ | |
5121 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); | |
5122 #elif !defined(_ALLBSD_SOURCE) | |
5123 if (user_sys_cpu_time && os::Bsd::supports_fast_thread_cpu_time()) { | |
5124 return os::Bsd::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); | |
5125 } else { | |
5126 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time); | |
5127 } | |
5128 #endif | |
5129 } | |
5130 | |
5131 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { | |
5132 #ifdef __APPLE__ | |
5133 struct thread_basic_info tinfo; | |
5134 mach_msg_type_number_t tcount = THREAD_INFO_MAX; | |
5135 kern_return_t kr; | |
5136 mach_port_t mach_thread; | |
5137 | |
5138 mach_thread = pthread_mach_thread_np(thread->osthread()->thread_id()); | |
5139 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount); | |
5140 if (kr != KERN_SUCCESS) | |
5141 return -1; | |
5142 | |
5143 if (user_sys_cpu_time) { | |
5144 jlong nanos; | |
5145 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000; | |
5146 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000; | |
5147 return nanos; | |
5148 } else { | |
5149 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000); | |
5150 } | |
5151 #elif !defined(_ALLBSD_SOURCE) | |
5152 if (user_sys_cpu_time && os::Bsd::supports_fast_thread_cpu_time()) { | |
5153 return os::Bsd::fast_thread_cpu_time(thread_cpu_clockid(thread)); | |
5154 } else { | |
5155 return slow_thread_cpu_time(thread, user_sys_cpu_time); | |
5156 } | |
5157 #endif | |
5158 } | |
5159 | |
5160 #ifndef _ALLBSD_SOURCE | |
5161 // | |
5162 // -1 on error. | |
5163 // | |
5164 | |
5165 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { | |
5166 static bool proc_pid_cpu_avail = true; | |
5167 static bool proc_task_unchecked = true; | |
5168 static const char *proc_stat_path = "/proc/%d/stat"; | |
5169 pid_t tid = thread->osthread()->thread_id(); | |
5170 int i; | |
5171 char *s; | |
5172 char stat[2048]; | |
5173 int statlen; | |
5174 char proc_name[64]; | |
5175 int count; | |
5176 long sys_time, user_time; | |
5177 char string[64]; | |
5178 char cdummy; | |
5179 int idummy; | |
5180 long ldummy; | |
5181 FILE *fp; | |
5182 | |
5183 // We first try accessing /proc/<pid>/cpu since this is faster to | |
5184 // process. If this file is not present (bsd kernels 2.5 and above) | |
5185 // then we open /proc/<pid>/stat. | |
5186 if ( proc_pid_cpu_avail ) { | |
5187 sprintf(proc_name, "/proc/%d/cpu", tid); | |
5188 fp = fopen(proc_name, "r"); | |
5189 if ( fp != NULL ) { | |
5190 count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time); | |
5191 fclose(fp); | |
5192 if ( count != 3 ) return -1; | |
5193 | |
5194 if (user_sys_cpu_time) { | |
5195 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); | |
5196 } else { | |
5197 return (jlong)user_time * (1000000000 / clock_tics_per_sec); | |
5198 } | |
5199 } | |
5200 else proc_pid_cpu_avail = false; | |
5201 } | |
5202 | |
5203 // The /proc/<tid>/stat aggregates per-process usage on | |
5204 // new Bsd kernels 2.6+ where NPTL is supported. | |
5205 // The /proc/self/task/<tid>/stat still has the per-thread usage. | |
5206 // See bug 6328462. | |
5207 // There can be no directory /proc/self/task on kernels 2.4 with NPTL | |
5208 // and possibly in some other cases, so we check its availability. | |
5209 if (proc_task_unchecked && os::Bsd::is_NPTL()) { | |
5210 // This is executed only once | |
5211 proc_task_unchecked = false; | |
5212 fp = fopen("/proc/self/task", "r"); | |
5213 if (fp != NULL) { | |
5214 proc_stat_path = "/proc/self/task/%d/stat"; | |
5215 fclose(fp); | |
5216 } | |
5217 } | |
5218 | |
5219 sprintf(proc_name, proc_stat_path, tid); | |
5220 fp = fopen(proc_name, "r"); | |
5221 if ( fp == NULL ) return -1; | |
5222 statlen = fread(stat, 1, 2047, fp); | |
5223 stat[statlen] = '\0'; | |
5224 fclose(fp); | |
5225 | |
5226 // Skip pid and the command string. Note that we could be dealing with | |
5227 // weird command names, e.g. user could decide to rename java launcher | |
5228 // to "java 1.4.2 :)", then the stat file would look like | |
5229 // 1234 (java 1.4.2 :)) R ... ... | |
5230 // We don't really need to know the command string, just find the last | |
5231 // occurrence of ")" and then start parsing from there. See bug 4726580. | |
5232 s = strrchr(stat, ')'); | |
5233 i = 0; | |
5234 if (s == NULL ) return -1; | |
5235 | |
5236 // Skip blank chars | |
5237 do s++; while (isspace(*s)); | |
5238 | |
5239 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", | |
5240 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy, | |
5241 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, | |
5242 &user_time, &sys_time); | |
5243 if ( count != 13 ) return -1; | |
5244 if (user_sys_cpu_time) { | |
5245 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); | |
5246 } else { | |
5247 return (jlong)user_time * (1000000000 / clock_tics_per_sec); | |
5248 } | |
5249 } | |
5250 #endif | |
5251 | |
5252 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { | |
5253 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits | |
5254 info_ptr->may_skip_backward = false; // elapsed time not wall time | |
5255 info_ptr->may_skip_forward = false; // elapsed time not wall time | |
5256 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned | |
5257 } | |
5258 | |
5259 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { | |
5260 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits | |
5261 info_ptr->may_skip_backward = false; // elapsed time not wall time | |
5262 info_ptr->may_skip_forward = false; // elapsed time not wall time | |
5263 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned | |
5264 } | |
5265 | |
5266 bool os::is_thread_cpu_time_supported() { | |
5267 #ifdef __APPLE__ | |
5268 return true; | |
5269 #elif defined(_ALLBSD_SOURCE) | |
5270 return false; | |
5271 #else | |
5272 return true; | |
5273 #endif | |
5274 } | |
5275 | |
5276 // System loadavg support. Returns -1 if load average cannot be obtained. | |
5277 // Bsd doesn't yet have a (official) notion of processor sets, | |
5278 // so just return the system wide load average. | |
5279 int os::loadavg(double loadavg[], int nelem) { | |
5280 return ::getloadavg(loadavg, nelem); | |
5281 } | |
5282 | |
5283 void os::pause() { | |
5284 char filename[MAX_PATH]; | |
5285 if (PauseAtStartupFile && PauseAtStartupFile[0]) { | |
5286 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); | |
5287 } else { | |
5288 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); | |
5289 } | |
5290 | |
5291 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); | |
5292 if (fd != -1) { | |
5293 struct stat buf; | |
5294 ::close(fd); | |
5295 while (::stat(filename, &buf) == 0) { | |
5296 (void)::poll(NULL, 0, 100); | |
5297 } | |
5298 } else { | |
5299 jio_fprintf(stderr, | |
5300 "Could not open pause file '%s', continuing immediately.\n", filename); | |
5301 } | |
5302 } | |
5303 | |
5304 | |
5305 // Refer to the comments in os_solaris.cpp park-unpark. | |
5306 // | |
5307 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can | |
5308 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. | |
5309 // For specifics regarding the bug see GLIBC BUGID 261237 : | |
5310 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. | |
5311 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future | |
5312 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar | |
5313 // is used. (The simple C test-case provided in the GLIBC bug report manifests the | |
5314 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() | |
5315 // and monitorenter when we're using 1-0 locking. All those operations may result in | |
5316 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version | |
5317 // of libpthread avoids the problem, but isn't practical. | |
5318 // | |
5319 // Possible remedies: | |
5320 // | |
5321 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. | |
5322 // This is palliative and probabilistic, however. If the thread is preempted | |
5323 // between the call to compute_abstime() and pthread_cond_timedwait(), more | |
5324 // than the minimum period may have passed, and the abstime may be stale (in the | |
5325 // past) resultin in a hang. Using this technique reduces the odds of a hang | |
5326 // but the JVM is still vulnerable, particularly on heavily loaded systems. | |
5327 // | |
5328 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead | |
5329 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set | |
5330 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) | |
5331 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant | |
5332 // thread. | |
5333 // | |
5334 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread | |
5335 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing | |
5336 // a timeout request to the chron thread and then blocking via pthread_cond_wait(). | |
5337 // This also works well. In fact it avoids kernel-level scalability impediments | |
5338 // on certain platforms that don't handle lots of active pthread_cond_timedwait() | |
5339 // timers in a graceful fashion. | |
5340 // | |
5341 // 4. When the abstime value is in the past it appears that control returns | |
5342 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. | |
5343 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we | |
5344 // can avoid the problem by reinitializing the condvar -- by cond_destroy() | |
5345 // followed by cond_init() -- after all calls to pthread_cond_timedwait(). | |
5346 // It may be possible to avoid reinitialization by checking the return | |
5347 // value from pthread_cond_timedwait(). In addition to reinitializing the | |
5348 // condvar we must establish the invariant that cond_signal() is only called | |
5349 // within critical sections protected by the adjunct mutex. This prevents | |
5350 // cond_signal() from "seeing" a condvar that's in the midst of being | |
5351 // reinitialized or that is corrupt. Sadly, this invariant obviates the | |
5352 // desirable signal-after-unlock optimization that avoids futile context switching. | |
5353 // | |
5354 // I'm also concerned that some versions of NTPL might allocate an auxilliary | |
5355 // structure when a condvar is used or initialized. cond_destroy() would | |
5356 // release the helper structure. Our reinitialize-after-timedwait fix | |
5357 // put excessive stress on malloc/free and locks protecting the c-heap. | |
5358 // | |
5359 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. | |
5360 // It may be possible to refine (4) by checking the kernel and NTPL verisons | |
5361 // and only enabling the work-around for vulnerable environments. | |
5362 | |
5363 // utility to compute the abstime argument to timedwait: | |
5364 // millis is the relative timeout time | |
5365 // abstime will be the absolute timeout time | |
5366 // TODO: replace compute_abstime() with unpackTime() | |
5367 | |
5368 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) { | |
5369 if (millis < 0) millis = 0; | |
5370 struct timeval now; | |
5371 int status = gettimeofday(&now, NULL); | |
5372 assert(status == 0, "gettimeofday"); | |
5373 jlong seconds = millis / 1000; | |
5374 millis %= 1000; | |
5375 if (seconds > 50000000) { // see man cond_timedwait(3T) | |
5376 seconds = 50000000; | |
5377 } | |
5378 abstime->tv_sec = now.tv_sec + seconds; | |
5379 long usec = now.tv_usec + millis * 1000; | |
5380 if (usec >= 1000000) { | |
5381 abstime->tv_sec += 1; | |
5382 usec -= 1000000; | |
5383 } | |
5384 abstime->tv_nsec = usec * 1000; | |
5385 return abstime; | |
5386 } | |
5387 | |
5388 | |
5389 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately. | |
5390 // Conceptually TryPark() should be equivalent to park(0). | |
5391 | |
5392 int os::PlatformEvent::TryPark() { | |
5393 for (;;) { | |
5394 const int v = _Event ; | |
5395 guarantee ((v == 0) || (v == 1), "invariant") ; | |
5396 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; | |
5397 } | |
5398 } | |
5399 | |
5400 void os::PlatformEvent::park() { // AKA "down()" | |
5401 // Invariant: Only the thread associated with the Event/PlatformEvent | |
5402 // may call park(). | |
5403 // TODO: assert that _Assoc != NULL or _Assoc == Self | |
5404 int v ; | |
5405 for (;;) { | |
5406 v = _Event ; | |
5407 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; | |
5408 } | |
5409 guarantee (v >= 0, "invariant") ; | |
5410 if (v == 0) { | |
5411 // Do this the hard way by blocking ... | |
5412 int status = pthread_mutex_lock(_mutex); | |
5413 assert_status(status == 0, status, "mutex_lock"); | |
5414 guarantee (_nParked == 0, "invariant") ; | |
5415 ++ _nParked ; | |
5416 while (_Event < 0) { | |
5417 status = pthread_cond_wait(_cond, _mutex); | |
5418 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... | |
5419 // Treat this the same as if the wait was interrupted | |
5420 if (status == ETIMEDOUT) { status = EINTR; } | |
5421 assert_status(status == 0 || status == EINTR, status, "cond_wait"); | |
5422 } | |
5423 -- _nParked ; | |
5424 | |
5425 // In theory we could move the ST of 0 into _Event past the unlock(), | |
5426 // but then we'd need a MEMBAR after the ST. | |
5427 _Event = 0 ; | |
5428 status = pthread_mutex_unlock(_mutex); | |
5429 assert_status(status == 0, status, "mutex_unlock"); | |
5430 } | |
5431 guarantee (_Event >= 0, "invariant") ; | |
5432 } | |
5433 | |
5434 int os::PlatformEvent::park(jlong millis) { | |
5435 guarantee (_nParked == 0, "invariant") ; | |
5436 | |
5437 int v ; | |
5438 for (;;) { | |
5439 v = _Event ; | |
5440 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; | |
5441 } | |
5442 guarantee (v >= 0, "invariant") ; | |
5443 if (v != 0) return OS_OK ; | |
5444 | |
5445 // We do this the hard way, by blocking the thread. | |
5446 // Consider enforcing a minimum timeout value. | |
5447 struct timespec abst; | |
5448 compute_abstime(&abst, millis); | |
5449 | |
5450 int ret = OS_TIMEOUT; | |
5451 int status = pthread_mutex_lock(_mutex); | |
5452 assert_status(status == 0, status, "mutex_lock"); | |
5453 guarantee (_nParked == 0, "invariant") ; | |
5454 ++_nParked ; | |
5455 | |
5456 // Object.wait(timo) will return because of | |
5457 // (a) notification | |
5458 // (b) timeout | |
5459 // (c) thread.interrupt | |
5460 // | |
5461 // Thread.interrupt and object.notify{All} both call Event::set. | |
5462 // That is, we treat thread.interrupt as a special case of notification. | |
5463 // The underlying Solaris implementation, cond_timedwait, admits | |
5464 // spurious/premature wakeups, but the JLS/JVM spec prevents the | |
5465 // JVM from making those visible to Java code. As such, we must | |
5466 // filter out spurious wakeups. We assume all ETIME returns are valid. | |
5467 // | |
5468 // TODO: properly differentiate simultaneous notify+interrupt. | |
5469 // In that case, we should propagate the notify to another waiter. | |
5470 | |
5471 while (_Event < 0) { | |
5472 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst); | |
5473 if (status != 0 && WorkAroundNPTLTimedWaitHang) { | |
5474 pthread_cond_destroy (_cond); | |
5475 pthread_cond_init (_cond, NULL) ; | |
5476 } | |
5477 assert_status(status == 0 || status == EINTR || | |
5478 status == ETIMEDOUT, | |
5479 status, "cond_timedwait"); | |
5480 if (!FilterSpuriousWakeups) break ; // previous semantics | |
5481 if (status == ETIMEDOUT) break ; | |
5482 // We consume and ignore EINTR and spurious wakeups. | |
5483 } | |
5484 --_nParked ; | |
5485 if (_Event >= 0) { | |
5486 ret = OS_OK; | |
5487 } | |
5488 _Event = 0 ; | |
5489 status = pthread_mutex_unlock(_mutex); | |
5490 assert_status(status == 0, status, "mutex_unlock"); | |
5491 assert (_nParked == 0, "invariant") ; | |
5492 return ret; | |
5493 } | |
5494 | |
5495 void os::PlatformEvent::unpark() { | |
5496 int v, AnyWaiters ; | |
5497 for (;;) { | |
5498 v = _Event ; | |
5499 if (v > 0) { | |
5500 // The LD of _Event could have reordered or be satisfied | |
5501 // by a read-aside from this processor's write buffer. | |
5502 // To avoid problems execute a barrier and then | |
5503 // ratify the value. | |
5504 OrderAccess::fence() ; | |
5505 if (_Event == v) return ; | |
5506 continue ; | |
5507 } | |
5508 if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ; | |
5509 } | |
5510 if (v < 0) { | |
5511 // Wait for the thread associated with the event to vacate | |
5512 int status = pthread_mutex_lock(_mutex); | |
5513 assert_status(status == 0, status, "mutex_lock"); | |
5514 AnyWaiters = _nParked ; | |
5515 assert (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ; | |
5516 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { | |
5517 AnyWaiters = 0 ; | |
5518 pthread_cond_signal (_cond); | |
5519 } | |
5520 status = pthread_mutex_unlock(_mutex); | |
5521 assert_status(status == 0, status, "mutex_unlock"); | |
5522 if (AnyWaiters != 0) { | |
5523 status = pthread_cond_signal(_cond); | |
5524 assert_status(status == 0, status, "cond_signal"); | |
5525 } | |
5526 } | |
5527 | |
5528 // Note that we signal() _after dropping the lock for "immortal" Events. | |
5529 // This is safe and avoids a common class of futile wakeups. In rare | |
5530 // circumstances this can cause a thread to return prematurely from | |
5531 // cond_{timed}wait() but the spurious wakeup is benign and the victim will | |
5532 // simply re-test the condition and re-park itself. | |
5533 } | |
5534 | |
5535 | |
5536 // JSR166 | |
5537 // ------------------------------------------------------- | |
5538 | |
5539 /* | |
5540 * The solaris and bsd implementations of park/unpark are fairly | |
5541 * conservative for now, but can be improved. They currently use a | |
5542 * mutex/condvar pair, plus a a count. | |
5543 * Park decrements count if > 0, else does a condvar wait. Unpark | |
5544 * sets count to 1 and signals condvar. Only one thread ever waits | |
5545 * on the condvar. Contention seen when trying to park implies that someone | |
5546 * is unparking you, so don't wait. And spurious returns are fine, so there | |
5547 * is no need to track notifications. | |
5548 */ | |
5549 | |
5550 #define MAX_SECS 100000000 | |
5551 /* | |
5552 * This code is common to bsd and solaris and will be moved to a | |
5553 * common place in dolphin. | |
5554 * | |
5555 * The passed in time value is either a relative time in nanoseconds | |
5556 * or an absolute time in milliseconds. Either way it has to be unpacked | |
5557 * into suitable seconds and nanoseconds components and stored in the | |
5558 * given timespec structure. | |
5559 * Given time is a 64-bit value and the time_t used in the timespec is only | |
5560 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for | |
5561 * overflow if times way in the future are given. Further on Solaris versions | |
5562 * prior to 10 there is a restriction (see cond_timedwait) that the specified | |
5563 * number of seconds, in abstime, is less than current_time + 100,000,000. | |
5564 * As it will be 28 years before "now + 100000000" will overflow we can | |
5565 * ignore overflow and just impose a hard-limit on seconds using the value | |
5566 * of "now + 100,000,000". This places a limit on the timeout of about 3.17 | |
5567 * years from "now". | |
5568 */ | |
5569 | |
5570 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) { | |
5571 assert (time > 0, "convertTime"); | |
5572 | |
5573 struct timeval now; | |
5574 int status = gettimeofday(&now, NULL); | |
5575 assert(status == 0, "gettimeofday"); | |
5576 | |
5577 time_t max_secs = now.tv_sec + MAX_SECS; | |
5578 | |
5579 if (isAbsolute) { | |
5580 jlong secs = time / 1000; | |
5581 if (secs > max_secs) { | |
5582 absTime->tv_sec = max_secs; | |
5583 } | |
5584 else { | |
5585 absTime->tv_sec = secs; | |
5586 } | |
5587 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; | |
5588 } | |
5589 else { | |
5590 jlong secs = time / NANOSECS_PER_SEC; | |
5591 if (secs >= MAX_SECS) { | |
5592 absTime->tv_sec = max_secs; | |
5593 absTime->tv_nsec = 0; | |
5594 } | |
5595 else { | |
5596 absTime->tv_sec = now.tv_sec + secs; | |
5597 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; | |
5598 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { | |
5599 absTime->tv_nsec -= NANOSECS_PER_SEC; | |
5600 ++absTime->tv_sec; // note: this must be <= max_secs | |
5601 } | |
5602 } | |
5603 } | |
5604 assert(absTime->tv_sec >= 0, "tv_sec < 0"); | |
5605 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); | |
5606 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); | |
5607 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); | |
5608 } | |
5609 | |
5610 void Parker::park(bool isAbsolute, jlong time) { | |
5611 // Optional fast-path check: | |
5612 // Return immediately if a permit is available. | |
5613 if (_counter > 0) { | |
5614 _counter = 0 ; | |
5615 OrderAccess::fence(); | |
5616 return ; | |
5617 } | |
5618 | |
5619 Thread* thread = Thread::current(); | |
5620 assert(thread->is_Java_thread(), "Must be JavaThread"); | |
5621 JavaThread *jt = (JavaThread *)thread; | |
5622 | |
5623 // Optional optimization -- avoid state transitions if there's an interrupt pending. | |
5624 // Check interrupt before trying to wait | |
5625 if (Thread::is_interrupted(thread, false)) { | |
5626 return; | |
5627 } | |
5628 | |
5629 // Next, demultiplex/decode time arguments | |
5630 struct timespec absTime; | |
5631 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all | |
5632 return; | |
5633 } | |
5634 if (time > 0) { | |
5635 unpackTime(&absTime, isAbsolute, time); | |
5636 } | |
5637 | |
5638 | |
5639 // Enter safepoint region | |
5640 // Beware of deadlocks such as 6317397. | |
5641 // The per-thread Parker:: mutex is a classic leaf-lock. | |
5642 // In particular a thread must never block on the Threads_lock while | |
5643 // holding the Parker:: mutex. If safepoints are pending both the | |
5644 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. | |
5645 ThreadBlockInVM tbivm(jt); | |
5646 | |
5647 // Don't wait if cannot get lock since interference arises from | |
5648 // unblocking. Also. check interrupt before trying wait | |
5649 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { | |
5650 return; | |
5651 } | |
5652 | |
5653 int status ; | |
5654 if (_counter > 0) { // no wait needed | |
5655 _counter = 0; | |
5656 status = pthread_mutex_unlock(_mutex); | |
5657 assert (status == 0, "invariant") ; | |
5658 OrderAccess::fence(); | |
5659 return; | |
5660 } | |
5661 | |
5662 #ifdef ASSERT | |
5663 // Don't catch signals while blocked; let the running threads have the signals. | |
5664 // (This allows a debugger to break into the running thread.) | |
5665 sigset_t oldsigs; | |
5666 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals(); | |
5667 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); | |
5668 #endif | |
5669 | |
5670 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); | |
5671 jt->set_suspend_equivalent(); | |
5672 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() | |
5673 | |
5674 if (time == 0) { | |
5675 status = pthread_cond_wait (_cond, _mutex) ; | |
5676 } else { | |
5677 status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ; | |
5678 if (status != 0 && WorkAroundNPTLTimedWaitHang) { | |
5679 pthread_cond_destroy (_cond) ; | |
5680 pthread_cond_init (_cond, NULL); | |
5681 } | |
5682 } | |
5683 assert_status(status == 0 || status == EINTR || | |
5684 status == ETIMEDOUT, | |
5685 status, "cond_timedwait"); | |
5686 | |
5687 #ifdef ASSERT | |
5688 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); | |
5689 #endif | |
5690 | |
5691 _counter = 0 ; | |
5692 status = pthread_mutex_unlock(_mutex) ; | |
5693 assert_status(status == 0, status, "invariant") ; | |
5694 // If externally suspended while waiting, re-suspend | |
5695 if (jt->handle_special_suspend_equivalent_condition()) { | |
5696 jt->java_suspend_self(); | |
5697 } | |
5698 | |
5699 OrderAccess::fence(); | |
5700 } | |
5701 | |
5702 void Parker::unpark() { | |
5703 int s, status ; | |
5704 status = pthread_mutex_lock(_mutex); | |
5705 assert (status == 0, "invariant") ; | |
5706 s = _counter; | |
5707 _counter = 1; | |
5708 if (s < 1) { | |
5709 if (WorkAroundNPTLTimedWaitHang) { | |
5710 status = pthread_cond_signal (_cond) ; | |
5711 assert (status == 0, "invariant") ; | |
5712 status = pthread_mutex_unlock(_mutex); | |
5713 assert (status == 0, "invariant") ; | |
5714 } else { | |
5715 status = pthread_mutex_unlock(_mutex); | |
5716 assert (status == 0, "invariant") ; | |
5717 status = pthread_cond_signal (_cond) ; | |
5718 assert (status == 0, "invariant") ; | |
5719 } | |
5720 } else { | |
5721 pthread_mutex_unlock(_mutex); | |
5722 assert (status == 0, "invariant") ; | |
5723 } | |
5724 } | |
5725 | |
5726 | |
5727 /* Darwin has no "environ" in a dynamic library. */ | |
5728 #ifdef __APPLE__ | |
5729 #include <crt_externs.h> | |
5730 #define environ (*_NSGetEnviron()) | |
5731 #else | |
5732 extern char** environ; | |
5733 #endif | |
5734 | |
5735 // Run the specified command in a separate process. Return its exit value, | |
5736 // or -1 on failure (e.g. can't fork a new process). | |
5737 // Unlike system(), this function can be called from signal handler. It | |
5738 // doesn't block SIGINT et al. | |
5739 int os::fork_and_exec(char* cmd) { | |
5740 const char * argv[4] = {"sh", "-c", cmd, NULL}; | |
5741 | |
5742 // fork() in BsdThreads/NPTL is not async-safe. It needs to run | |
5743 // pthread_atfork handlers and reset pthread library. All we need is a | |
5744 // separate process to execve. Make a direct syscall to fork process. | |
5745 // On IA64 there's no fork syscall, we have to use fork() and hope for | |
5746 // the best... | |
5747 pid_t pid = fork(); | |
5748 | |
5749 if (pid < 0) { | |
5750 // fork failed | |
5751 return -1; | |
5752 | |
5753 } else if (pid == 0) { | |
5754 // child process | |
5755 | |
5756 // execve() in BsdThreads will call pthread_kill_other_threads_np() | |
5757 // first to kill every thread on the thread list. Because this list is | |
5758 // not reset by fork() (see notes above), execve() will instead kill | |
5759 // every thread in the parent process. We know this is the only thread | |
5760 // in the new process, so make a system call directly. | |
5761 // IA64 should use normal execve() from glibc to match the glibc fork() | |
5762 // above. | |
5763 execve("/bin/sh", (char* const*)argv, environ); | |
5764 | |
5765 // execve failed | |
5766 _exit(-1); | |
5767 | |
5768 } else { | |
5769 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't | |
5770 // care about the actual exit code, for now. | |
5771 | |
5772 int status; | |
5773 | |
5774 // Wait for the child process to exit. This returns immediately if | |
5775 // the child has already exited. */ | |
5776 while (waitpid(pid, &status, 0) < 0) { | |
5777 switch (errno) { | |
5778 case ECHILD: return 0; | |
5779 case EINTR: break; | |
5780 default: return -1; | |
5781 } | |
5782 } | |
5783 | |
5784 if (WIFEXITED(status)) { | |
5785 // The child exited normally; get its exit code. | |
5786 return WEXITSTATUS(status); | |
5787 } else if (WIFSIGNALED(status)) { | |
5788 // The child exited because of a signal | |
5789 // The best value to return is 0x80 + signal number, | |
5790 // because that is what all Unix shells do, and because | |
5791 // it allows callers to distinguish between process exit and | |
5792 // process death by signal. | |
5793 return 0x80 + WTERMSIG(status); | |
5794 } else { | |
5795 // Unknown exit code; pass it through | |
5796 return status; | |
5797 } | |
5798 } | |
5799 } | |
5800 | |
5801 // is_headless_jre() | |
5802 // | |
4082
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5803 // Test for the existence of xawt/libmawt.so or libawt_xawt.so |
3960 | 5804 // in order to report if we are running in a headless jre |
5805 // | |
4082
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5806 // Since JDK8 xawt/libmawt.so was moved into the same directory |
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5807 // as libawt.so, and renamed libawt_xawt.so |
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5808 // |
3960 | 5809 bool os::is_headless_jre() { |
5810 struct stat statbuf; | |
5811 char buf[MAXPATHLEN]; | |
5812 char libmawtpath[MAXPATHLEN]; | |
4006 | 5813 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX; |
4082
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5814 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX; |
3960 | 5815 char *p; |
5816 | |
5817 // Get path to libjvm.so | |
5818 os::jvm_path(buf, sizeof(buf)); | |
5819 | |
5820 // Get rid of libjvm.so | |
5821 p = strrchr(buf, '/'); | |
5822 if (p == NULL) return false; | |
5823 else *p = '\0'; | |
5824 | |
5825 // Get rid of client or server | |
5826 p = strrchr(buf, '/'); | |
5827 if (p == NULL) return false; | |
5828 else *p = '\0'; | |
5829 | |
5830 // check xawt/libmawt.so | |
5831 strcpy(libmawtpath, buf); | |
5832 strcat(libmawtpath, xawtstr); | |
5833 if (::stat(libmawtpath, &statbuf) == 0) return false; | |
5834 | |
4082
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5835 // check libawt_xawt.so |
3960 | 5836 strcpy(libmawtpath, buf); |
4082
36b057451829
7110017: is_headless_jre should be updated to reflect the new location of awt toolkit libraries
dholmes
parents:
4006
diff
changeset
|
5837 strcat(libmawtpath, new_xawtstr); |
3960 | 5838 if (::stat(libmawtpath, &statbuf) == 0) return false; |
5839 | |
5840 return true; | |
5841 } |