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