Wed, 07 Nov 2012 17:53:02 -0500
8001185: parsing of sun.boot.library.path in os::dll_build_name somewhat broken
Summary: dll_dir can contain multiple paths, need to parse them correctly when loading agents
Reviewed-by: dholmes, dlong
Contributed-by: bill.pittore@oracle.com
1 /*
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
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
86 // put OS-includes here
87 # include <sys/types.h>
88 # include <sys/mman.h>
89 # include <sys/stat.h>
90 # include <sys/select.h>
91 # include <pthread.h>
92 # include <signal.h>
93 # include <errno.h>
94 # include <dlfcn.h>
95 # include <stdio.h>
96 # include <unistd.h>
97 # include <sys/resource.h>
98 # include <pthread.h>
99 # include <sys/stat.h>
100 # include <sys/time.h>
101 # include <sys/times.h>
102 # include <sys/utsname.h>
103 # include <sys/socket.h>
104 # include <sys/wait.h>
105 # include <time.h>
106 # include <pwd.h>
107 # include <poll.h>
108 # include <semaphore.h>
109 # include <fcntl.h>
110 # include <string.h>
111 # include <sys/param.h>
112 # include <sys/sysctl.h>
113 # include <sys/ipc.h>
114 # include <sys/shm.h>
115 #ifndef __APPLE__
116 # include <link.h>
117 #endif
118 # include <stdint.h>
119 # include <inttypes.h>
120 # include <sys/ioctl.h>
122 #if defined(__FreeBSD__) || defined(__NetBSD__)
123 # include <elf.h>
124 #endif
126 #ifdef __APPLE__
127 # include <mach/mach.h> // semaphore_* API
128 # include <mach-o/dyld.h>
129 # include <sys/proc_info.h>
130 # include <objc/objc-auto.h>
131 #endif
133 #ifndef MAP_ANONYMOUS
134 #define MAP_ANONYMOUS MAP_ANON
135 #endif
137 #define MAX_PATH (2 * K)
139 // for timer info max values which include all bits
140 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
142 #define LARGEPAGES_BIT (1 << 6)
143 ////////////////////////////////////////////////////////////////////////////////
144 // global variables
145 julong os::Bsd::_physical_memory = 0;
148 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
149 pthread_t os::Bsd::_main_thread;
150 int os::Bsd::_page_size = -1;
152 static jlong initial_time_count=0;
154 static int clock_tics_per_sec = 100;
156 // For diagnostics to print a message once. see run_periodic_checks
157 static sigset_t check_signal_done;
158 static bool check_signals = true;
160 static pid_t _initial_pid = 0;
162 /* Signal number used to suspend/resume a thread */
164 /* do not use any signal number less than SIGSEGV, see 4355769 */
165 static int SR_signum = SIGUSR2;
166 sigset_t SR_sigset;
169 ////////////////////////////////////////////////////////////////////////////////
170 // utility functions
172 static int SR_initialize();
173 static int SR_finalize();
175 julong os::available_memory() {
176 return Bsd::available_memory();
177 }
179 julong os::Bsd::available_memory() {
180 // XXXBSD: this is just a stopgap implementation
181 return physical_memory() >> 2;
182 }
184 julong os::physical_memory() {
185 return Bsd::physical_memory();
186 }
188 julong os::allocatable_physical_memory(julong size) {
189 #ifdef _LP64
190 return size;
191 #else
192 julong result = MIN2(size, (julong)3800*M);
193 if (!is_allocatable(result)) {
194 // See comments under solaris for alignment considerations
195 julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
196 result = MIN2(size, reasonable_size);
197 }
198 return result;
199 #endif // _LP64
200 }
202 ////////////////////////////////////////////////////////////////////////////////
203 // environment support
205 bool os::getenv(const char* name, char* buf, int len) {
206 const char* val = ::getenv(name);
207 if (val != NULL && strlen(val) < (size_t)len) {
208 strcpy(buf, val);
209 return true;
210 }
211 if (len > 0) buf[0] = 0; // return a null string
212 return false;
213 }
216 // Return true if user is running as root.
218 bool os::have_special_privileges() {
219 static bool init = false;
220 static bool privileges = false;
221 if (!init) {
222 privileges = (getuid() != geteuid()) || (getgid() != getegid());
223 init = true;
224 }
225 return privileges;
226 }
230 // Cpu architecture string
231 #if defined(ZERO)
232 static char cpu_arch[] = ZERO_LIBARCH;
233 #elif defined(IA64)
234 static char cpu_arch[] = "ia64";
235 #elif defined(IA32)
236 static char cpu_arch[] = "i386";
237 #elif defined(AMD64)
238 static char cpu_arch[] = "amd64";
239 #elif defined(ARM)
240 static char cpu_arch[] = "arm";
241 #elif defined(PPC)
242 static char cpu_arch[] = "ppc";
243 #elif defined(SPARC)
244 # ifdef _LP64
245 static char cpu_arch[] = "sparcv9";
246 # else
247 static char cpu_arch[] = "sparc";
248 # endif
249 #else
250 #error Add appropriate cpu_arch setting
251 #endif
253 // Compiler variant
254 #ifdef COMPILER2
255 #define COMPILER_VARIANT "server"
256 #else
257 #define COMPILER_VARIANT "client"
258 #endif
261 void os::Bsd::initialize_system_info() {
262 int mib[2];
263 size_t len;
264 int cpu_val;
265 u_long mem_val;
267 /* get processors count via hw.ncpus sysctl */
268 mib[0] = CTL_HW;
269 mib[1] = HW_NCPU;
270 len = sizeof(cpu_val);
271 if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
272 set_processor_count(cpu_val);
273 }
274 else {
275 set_processor_count(1); // fallback
276 }
278 /* get physical memory via hw.usermem sysctl (hw.usermem is used
279 * instead of hw.physmem because we need size of allocatable memory
280 */
281 mib[0] = CTL_HW;
282 mib[1] = HW_USERMEM;
283 len = sizeof(mem_val);
284 if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1)
285 _physical_memory = mem_val;
286 else
287 _physical_memory = 256*1024*1024; // fallback (XXXBSD?)
289 #ifdef __OpenBSD__
290 {
291 // limit _physical_memory memory view on OpenBSD since
292 // datasize rlimit restricts us anyway.
293 struct rlimit limits;
294 getrlimit(RLIMIT_DATA, &limits);
295 _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
296 }
297 #endif
298 }
300 #ifdef __APPLE__
301 static const char *get_home() {
302 const char *home_dir = ::getenv("HOME");
303 if ((home_dir == NULL) || (*home_dir == '\0')) {
304 struct passwd *passwd_info = getpwuid(geteuid());
305 if (passwd_info != NULL) {
306 home_dir = passwd_info->pw_dir;
307 }
308 }
310 return home_dir;
311 }
312 #endif
314 void os::init_system_properties_values() {
315 // char arch[12];
316 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
318 // The next steps are taken in the product version:
319 //
320 // Obtain the JAVA_HOME value from the location of libjvm[_g].so.
321 // This library should be located at:
322 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so.
323 //
324 // If "/jre/lib/" appears at the right place in the path, then we
325 // assume libjvm[_g].so is installed in a JDK and we use this path.
326 //
327 // Otherwise exit with message: "Could not create the Java virtual machine."
328 //
329 // The following extra steps are taken in the debugging version:
330 //
331 // If "/jre/lib/" does NOT appear at the right place in the path
332 // instead of exit check for $JAVA_HOME environment variable.
333 //
334 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
335 // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so
336 // it looks like libjvm[_g].so is installed there
337 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so.
338 //
339 // Otherwise exit.
340 //
341 // Important note: if the location of libjvm.so changes this
342 // code needs to be changed accordingly.
344 // The next few definitions allow the code to be verbatim:
345 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
346 #define getenv(n) ::getenv(n)
348 /*
349 * See ld(1):
350 * The linker uses the following search paths to locate required
351 * shared libraries:
352 * 1: ...
353 * ...
354 * 7: The default directories, normally /lib and /usr/lib.
355 */
356 #ifndef DEFAULT_LIBPATH
357 #define DEFAULT_LIBPATH "/lib:/usr/lib"
358 #endif
360 #define EXTENSIONS_DIR "/lib/ext"
361 #define ENDORSED_DIR "/lib/endorsed"
362 #define REG_DIR "/usr/java/packages"
364 #ifdef __APPLE__
365 #define SYS_EXTENSIONS_DIR "/Library/Java/Extensions"
366 #define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
367 const char *user_home_dir = get_home();
368 // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
369 int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
370 sizeof(SYS_EXTENSIONS_DIRS);
371 #endif
373 {
374 /* sysclasspath, java_home, dll_dir */
375 {
376 char *home_path;
377 char *dll_path;
378 char *pslash;
379 char buf[MAXPATHLEN];
380 os::jvm_path(buf, sizeof(buf));
382 // Found the full path to libjvm.so.
383 // Now cut the path to <java_home>/jre if we can.
384 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */
385 pslash = strrchr(buf, '/');
386 if (pslash != NULL)
387 *pslash = '\0'; /* get rid of /{client|server|hotspot} */
388 dll_path = malloc(strlen(buf) + 1);
389 if (dll_path == NULL)
390 return;
391 strcpy(dll_path, buf);
392 Arguments::set_dll_dir(dll_path);
394 if (pslash != NULL) {
395 pslash = strrchr(buf, '/');
396 if (pslash != NULL) {
397 *pslash = '\0'; /* get rid of /<arch> (/lib on macosx) */
398 #ifndef __APPLE__
399 pslash = strrchr(buf, '/');
400 if (pslash != NULL)
401 *pslash = '\0'; /* get rid of /lib */
402 #endif
403 }
404 }
406 home_path = malloc(strlen(buf) + 1);
407 if (home_path == NULL)
408 return;
409 strcpy(home_path, buf);
410 Arguments::set_java_home(home_path);
412 if (!set_boot_path('/', ':'))
413 return;
414 }
416 /*
417 * Where to look for native libraries
418 *
419 * Note: Due to a legacy implementation, most of the library path
420 * is set in the launcher. This was to accomodate linking restrictions
421 * on legacy Bsd implementations (which are no longer supported).
422 * Eventually, all the library path setting will be done here.
423 *
424 * However, to prevent the proliferation of improperly built native
425 * libraries, the new path component /usr/java/packages is added here.
426 * Eventually, all the library path setting will be done here.
427 */
428 {
429 char *ld_library_path;
431 /*
432 * Construct the invariant part of ld_library_path. Note that the
433 * space for the colon and the trailing null are provided by the
434 * nulls included by the sizeof operator (so actually we allocate
435 * a byte more than necessary).
436 */
437 #ifdef __APPLE__
438 ld_library_path = (char *) malloc(system_ext_size);
439 sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir);
440 #else
441 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
442 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
443 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
444 #endif
446 /*
447 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It
448 * should always exist (until the legacy problem cited above is
449 * addressed).
450 */
451 #ifdef __APPLE__
452 // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
453 char *l = getenv("JAVA_LIBRARY_PATH");
454 if (l != NULL) {
455 char *t = ld_library_path;
456 /* That's +1 for the colon and +1 for the trailing '\0' */
457 ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1);
458 sprintf(ld_library_path, "%s:%s", l, t);
459 free(t);
460 }
462 char *v = getenv("DYLD_LIBRARY_PATH");
463 #else
464 char *v = getenv("LD_LIBRARY_PATH");
465 #endif
466 if (v != NULL) {
467 char *t = ld_library_path;
468 /* That's +1 for the colon and +1 for the trailing '\0' */
469 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
470 sprintf(ld_library_path, "%s:%s", v, t);
471 free(t);
472 }
474 #ifdef __APPLE__
475 // Apple's Java6 has "." at the beginning of java.library.path.
476 // OpenJDK on Windows has "." at the end of java.library.path.
477 // OpenJDK on Linux and Solaris don't have "." in java.library.path
478 // at all. To ease the transition from Apple's Java6 to OpenJDK7,
479 // "." is appended to the end of java.library.path. Yes, this
480 // could cause a change in behavior, but Apple's Java6 behavior
481 // can be achieved by putting "." at the beginning of the
482 // JAVA_LIBRARY_PATH environment variable.
483 {
484 char *t = ld_library_path;
485 // that's +3 for appending ":." and the trailing '\0'
486 ld_library_path = (char *) malloc(strlen(t) + 3);
487 sprintf(ld_library_path, "%s:%s", t, ".");
488 free(t);
489 }
490 #endif
492 Arguments::set_library_path(ld_library_path);
493 }
495 /*
496 * Extensions directories.
497 *
498 * Note that the space for the colon and the trailing null are provided
499 * by the nulls included by the sizeof operator (so actually one byte more
500 * than necessary is allocated).
501 */
502 {
503 #ifdef __APPLE__
504 char *buf = malloc(strlen(Arguments::get_java_home()) +
505 sizeof(EXTENSIONS_DIR) + system_ext_size);
506 sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":"
507 SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home());
508 #else
509 char *buf = malloc(strlen(Arguments::get_java_home()) +
510 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
511 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
512 Arguments::get_java_home());
513 #endif
515 Arguments::set_ext_dirs(buf);
516 }
518 /* Endorsed standards default directory. */
519 {
520 char * buf;
521 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
522 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
523 Arguments::set_endorsed_dirs(buf);
524 }
525 }
527 #ifdef __APPLE__
528 #undef SYS_EXTENSIONS_DIR
529 #endif
530 #undef malloc
531 #undef getenv
532 #undef EXTENSIONS_DIR
533 #undef ENDORSED_DIR
535 // Done
536 return;
537 }
539 ////////////////////////////////////////////////////////////////////////////////
540 // breakpoint support
542 void os::breakpoint() {
543 BREAKPOINT;
544 }
546 extern "C" void breakpoint() {
547 // use debugger to set breakpoint here
548 }
550 ////////////////////////////////////////////////////////////////////////////////
551 // signal support
553 debug_only(static bool signal_sets_initialized = false);
554 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
556 bool os::Bsd::is_sig_ignored(int sig) {
557 struct sigaction oact;
558 sigaction(sig, (struct sigaction*)NULL, &oact);
559 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)
560 : CAST_FROM_FN_PTR(void*, oact.sa_handler);
561 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
562 return true;
563 else
564 return false;
565 }
567 void os::Bsd::signal_sets_init() {
568 // Should also have an assertion stating we are still single-threaded.
569 assert(!signal_sets_initialized, "Already initialized");
570 // Fill in signals that are necessarily unblocked for all threads in
571 // the VM. Currently, we unblock the following signals:
572 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
573 // by -Xrs (=ReduceSignalUsage));
574 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
575 // other threads. The "ReduceSignalUsage" boolean tells us not to alter
576 // the dispositions or masks wrt these signals.
577 // Programs embedding the VM that want to use the above signals for their
578 // own purposes must, at this time, use the "-Xrs" option to prevent
579 // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
580 // (See bug 4345157, and other related bugs).
581 // In reality, though, unblocking these signals is really a nop, since
582 // these signals are not blocked by default.
583 sigemptyset(&unblocked_sigs);
584 sigemptyset(&allowdebug_blocked_sigs);
585 sigaddset(&unblocked_sigs, SIGILL);
586 sigaddset(&unblocked_sigs, SIGSEGV);
587 sigaddset(&unblocked_sigs, SIGBUS);
588 sigaddset(&unblocked_sigs, SIGFPE);
589 sigaddset(&unblocked_sigs, SR_signum);
591 if (!ReduceSignalUsage) {
592 if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
593 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
594 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
595 }
596 if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
597 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
598 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
599 }
600 if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
601 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
602 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
603 }
604 }
605 // Fill in signals that are blocked by all but the VM thread.
606 sigemptyset(&vm_sigs);
607 if (!ReduceSignalUsage)
608 sigaddset(&vm_sigs, BREAK_SIGNAL);
609 debug_only(signal_sets_initialized = true);
611 }
613 // These are signals that are unblocked while a thread is running Java.
614 // (For some reason, they get blocked by default.)
615 sigset_t* os::Bsd::unblocked_signals() {
616 assert(signal_sets_initialized, "Not initialized");
617 return &unblocked_sigs;
618 }
620 // These are the signals that are blocked while a (non-VM) thread is
621 // running Java. Only the VM thread handles these signals.
622 sigset_t* os::Bsd::vm_signals() {
623 assert(signal_sets_initialized, "Not initialized");
624 return &vm_sigs;
625 }
627 // These are signals that are blocked during cond_wait to allow debugger in
628 sigset_t* os::Bsd::allowdebug_blocked_signals() {
629 assert(signal_sets_initialized, "Not initialized");
630 return &allowdebug_blocked_sigs;
631 }
633 void os::Bsd::hotspot_sigmask(Thread* thread) {
635 //Save caller's signal mask before setting VM signal mask
636 sigset_t caller_sigmask;
637 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
639 OSThread* osthread = thread->osthread();
640 osthread->set_caller_sigmask(caller_sigmask);
642 pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
644 if (!ReduceSignalUsage) {
645 if (thread->is_VM_thread()) {
646 // Only the VM thread handles BREAK_SIGNAL ...
647 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
648 } else {
649 // ... all other threads block BREAK_SIGNAL
650 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
651 }
652 }
653 }
656 //////////////////////////////////////////////////////////////////////////////
657 // create new thread
659 static address highest_vm_reserved_address();
661 // check if it's safe to start a new thread
662 static bool _thread_safety_check(Thread* thread) {
663 return true;
664 }
666 #ifdef __APPLE__
667 // library handle for calling objc_registerThreadWithCollector()
668 // without static linking to the libobjc library
669 #define OBJC_LIB "/usr/lib/libobjc.dylib"
670 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
671 typedef void (*objc_registerThreadWithCollector_t)();
672 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
673 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
674 #endif
676 // Thread start routine for all newly created threads
677 static void *java_start(Thread *thread) {
678 // Try to randomize the cache line index of hot stack frames.
679 // This helps when threads of the same stack traces evict each other's
680 // cache lines. The threads can be either from the same JVM instance, or
681 // from different JVM instances. The benefit is especially true for
682 // processors with hyperthreading technology.
683 static int counter = 0;
684 int pid = os::current_process_id();
685 alloca(((pid ^ counter++) & 7) * 128);
687 ThreadLocalStorage::set_thread(thread);
689 OSThread* osthread = thread->osthread();
690 Monitor* sync = osthread->startThread_lock();
692 // non floating stack BsdThreads needs extra check, see above
693 if (!_thread_safety_check(thread)) {
694 // notify parent thread
695 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
696 osthread->set_state(ZOMBIE);
697 sync->notify_all();
698 return NULL;
699 }
701 #ifdef __APPLE__
702 // thread_id is mach thread on macos
703 osthread->set_thread_id(::mach_thread_self());
704 #else
705 // thread_id is pthread_id on BSD
706 osthread->set_thread_id(::pthread_self());
707 #endif
708 // initialize signal mask for this thread
709 os::Bsd::hotspot_sigmask(thread);
711 // initialize floating point control register
712 os::Bsd::init_thread_fpu_state();
714 #ifdef __APPLE__
715 // register thread with objc gc
716 if (objc_registerThreadWithCollectorFunction != NULL) {
717 objc_registerThreadWithCollectorFunction();
718 }
719 #endif
721 // handshaking with parent thread
722 {
723 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
725 // notify parent thread
726 osthread->set_state(INITIALIZED);
727 sync->notify_all();
729 // wait until os::start_thread()
730 while (osthread->get_state() == INITIALIZED) {
731 sync->wait(Mutex::_no_safepoint_check_flag);
732 }
733 }
735 // call one more level start routine
736 thread->run();
738 return 0;
739 }
741 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
742 assert(thread->osthread() == NULL, "caller responsible");
744 // Allocate the OSThread object
745 OSThread* osthread = new OSThread(NULL, NULL);
746 if (osthread == NULL) {
747 return false;
748 }
750 // set the correct thread state
751 osthread->set_thread_type(thr_type);
753 // Initial state is ALLOCATED but not INITIALIZED
754 osthread->set_state(ALLOCATED);
756 thread->set_osthread(osthread);
758 // init thread attributes
759 pthread_attr_t attr;
760 pthread_attr_init(&attr);
761 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
763 // stack size
764 if (os::Bsd::supports_variable_stack_size()) {
765 // calculate stack size if it's not specified by caller
766 if (stack_size == 0) {
767 stack_size = os::Bsd::default_stack_size(thr_type);
769 switch (thr_type) {
770 case os::java_thread:
771 // Java threads use ThreadStackSize which default value can be
772 // changed with the flag -Xss
773 assert (JavaThread::stack_size_at_create() > 0, "this should be set");
774 stack_size = JavaThread::stack_size_at_create();
775 break;
776 case os::compiler_thread:
777 if (CompilerThreadStackSize > 0) {
778 stack_size = (size_t)(CompilerThreadStackSize * K);
779 break;
780 } // else fall through:
781 // use VMThreadStackSize if CompilerThreadStackSize is not defined
782 case os::vm_thread:
783 case os::pgc_thread:
784 case os::cgc_thread:
785 case os::watcher_thread:
786 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
787 break;
788 }
789 }
791 stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
792 pthread_attr_setstacksize(&attr, stack_size);
793 } else {
794 // let pthread_create() pick the default value.
795 }
797 ThreadState state;
799 {
800 pthread_t tid;
801 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
803 pthread_attr_destroy(&attr);
805 if (ret != 0) {
806 if (PrintMiscellaneous && (Verbose || WizardMode)) {
807 perror("pthread_create()");
808 }
809 // Need to clean up stuff we've allocated so far
810 thread->set_osthread(NULL);
811 delete osthread;
812 return false;
813 }
815 // Store pthread info into the OSThread
816 osthread->set_pthread_id(tid);
818 // Wait until child thread is either initialized or aborted
819 {
820 Monitor* sync_with_child = osthread->startThread_lock();
821 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
822 while ((state = osthread->get_state()) == ALLOCATED) {
823 sync_with_child->wait(Mutex::_no_safepoint_check_flag);
824 }
825 }
827 }
829 // Aborted due to thread limit being reached
830 if (state == ZOMBIE) {
831 thread->set_osthread(NULL);
832 delete osthread;
833 return false;
834 }
836 // The thread is returned suspended (in state INITIALIZED),
837 // and is started higher up in the call chain
838 assert(state == INITIALIZED, "race condition");
839 return true;
840 }
842 /////////////////////////////////////////////////////////////////////////////
843 // attach existing thread
845 // bootstrap the main thread
846 bool os::create_main_thread(JavaThread* thread) {
847 assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
848 return create_attached_thread(thread);
849 }
851 bool os::create_attached_thread(JavaThread* thread) {
852 #ifdef ASSERT
853 thread->verify_not_published();
854 #endif
856 // Allocate the OSThread object
857 OSThread* osthread = new OSThread(NULL, NULL);
859 if (osthread == NULL) {
860 return false;
861 }
863 // Store pthread info into the OSThread
864 #ifdef __APPLE__
865 osthread->set_thread_id(::mach_thread_self());
866 #else
867 osthread->set_thread_id(::pthread_self());
868 #endif
869 osthread->set_pthread_id(::pthread_self());
871 // initialize floating point control register
872 os::Bsd::init_thread_fpu_state();
874 // Initial thread state is RUNNABLE
875 osthread->set_state(RUNNABLE);
877 thread->set_osthread(osthread);
879 // initialize signal mask for this thread
880 // and save the caller's signal mask
881 os::Bsd::hotspot_sigmask(thread);
883 return true;
884 }
886 void os::pd_start_thread(Thread* thread) {
887 OSThread * osthread = thread->osthread();
888 assert(osthread->get_state() != INITIALIZED, "just checking");
889 Monitor* sync_with_child = osthread->startThread_lock();
890 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
891 sync_with_child->notify();
892 }
894 // Free Bsd resources related to the OSThread
895 void os::free_thread(OSThread* osthread) {
896 assert(osthread != NULL, "osthread not set");
898 if (Thread::current()->osthread() == osthread) {
899 // Restore caller's signal mask
900 sigset_t sigmask = osthread->caller_sigmask();
901 pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
902 }
904 delete osthread;
905 }
907 //////////////////////////////////////////////////////////////////////////////
908 // thread local storage
910 int os::allocate_thread_local_storage() {
911 pthread_key_t key;
912 int rslt = pthread_key_create(&key, NULL);
913 assert(rslt == 0, "cannot allocate thread local storage");
914 return (int)key;
915 }
917 // Note: This is currently not used by VM, as we don't destroy TLS key
918 // on VM exit.
919 void os::free_thread_local_storage(int index) {
920 int rslt = pthread_key_delete((pthread_key_t)index);
921 assert(rslt == 0, "invalid index");
922 }
924 void os::thread_local_storage_at_put(int index, void* value) {
925 int rslt = pthread_setspecific((pthread_key_t)index, value);
926 assert(rslt == 0, "pthread_setspecific failed");
927 }
929 extern "C" Thread* get_thread() {
930 return ThreadLocalStorage::thread();
931 }
934 ////////////////////////////////////////////////////////////////////////////////
935 // time support
937 // Time since start-up in seconds to a fine granularity.
938 // Used by VMSelfDestructTimer and the MemProfiler.
939 double os::elapsedTime() {
941 return (double)(os::elapsed_counter()) * 0.000001;
942 }
944 jlong os::elapsed_counter() {
945 timeval time;
946 int status = gettimeofday(&time, NULL);
947 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
948 }
950 jlong os::elapsed_frequency() {
951 return (1000 * 1000);
952 }
954 // XXX: For now, code this as if BSD does not support vtime.
955 bool os::supports_vtime() { return false; }
956 bool os::enable_vtime() { return false; }
957 bool os::vtime_enabled() { return false; }
958 double os::elapsedVTime() {
959 // better than nothing, but not much
960 return elapsedTime();
961 }
963 jlong os::javaTimeMillis() {
964 timeval time;
965 int status = gettimeofday(&time, NULL);
966 assert(status != -1, "bsd error");
967 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
968 }
970 #ifndef CLOCK_MONOTONIC
971 #define CLOCK_MONOTONIC (1)
972 #endif
974 #ifdef __APPLE__
975 void os::Bsd::clock_init() {
976 // XXXDARWIN: Investigate replacement monotonic clock
977 }
978 #else
979 void os::Bsd::clock_init() {
980 struct timespec res;
981 struct timespec tp;
982 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
983 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
984 // yes, monotonic clock is supported
985 _clock_gettime = ::clock_gettime;
986 }
987 }
988 #endif
991 jlong os::javaTimeNanos() {
992 if (Bsd::supports_monotonic_clock()) {
993 struct timespec tp;
994 int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
995 assert(status == 0, "gettime error");
996 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
997 return result;
998 } else {
999 timeval time;
1000 int status = gettimeofday(&time, NULL);
1001 assert(status != -1, "bsd error");
1002 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1003 return 1000 * usecs;
1004 }
1005 }
1007 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1008 if (Bsd::supports_monotonic_clock()) {
1009 info_ptr->max_value = ALL_64_BITS;
1011 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1012 info_ptr->may_skip_backward = false; // not subject to resetting or drifting
1013 info_ptr->may_skip_forward = false; // not subject to resetting or drifting
1014 } else {
1015 // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1016 info_ptr->max_value = ALL_64_BITS;
1018 // gettimeofday is a real time clock so it skips
1019 info_ptr->may_skip_backward = true;
1020 info_ptr->may_skip_forward = true;
1021 }
1023 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
1024 }
1026 // Return the real, user, and system times in seconds from an
1027 // arbitrary fixed point in the past.
1028 bool os::getTimesSecs(double* process_real_time,
1029 double* process_user_time,
1030 double* process_system_time) {
1031 struct tms ticks;
1032 clock_t real_ticks = times(&ticks);
1034 if (real_ticks == (clock_t) (-1)) {
1035 return false;
1036 } else {
1037 double ticks_per_second = (double) clock_tics_per_sec;
1038 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1039 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1040 *process_real_time = ((double) real_ticks) / ticks_per_second;
1042 return true;
1043 }
1044 }
1047 char * os::local_time_string(char *buf, size_t buflen) {
1048 struct tm t;
1049 time_t long_time;
1050 time(&long_time);
1051 localtime_r(&long_time, &t);
1052 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1053 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1054 t.tm_hour, t.tm_min, t.tm_sec);
1055 return buf;
1056 }
1058 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
1059 return localtime_r(clock, res);
1060 }
1062 ////////////////////////////////////////////////////////////////////////////////
1063 // runtime exit support
1065 // Note: os::shutdown() might be called very early during initialization, or
1066 // called from signal handler. Before adding something to os::shutdown(), make
1067 // sure it is async-safe and can handle partially initialized VM.
1068 void os::shutdown() {
1070 // allow PerfMemory to attempt cleanup of any persistent resources
1071 perfMemory_exit();
1073 // needs to remove object in file system
1074 AttachListener::abort();
1076 // flush buffered output, finish log files
1077 ostream_abort();
1079 // Check for abort hook
1080 abort_hook_t abort_hook = Arguments::abort_hook();
1081 if (abort_hook != NULL) {
1082 abort_hook();
1083 }
1085 }
1087 // Note: os::abort() might be called very early during initialization, or
1088 // called from signal handler. Before adding something to os::abort(), make
1089 // sure it is async-safe and can handle partially initialized VM.
1090 void os::abort(bool dump_core) {
1091 os::shutdown();
1092 if (dump_core) {
1093 #ifndef PRODUCT
1094 fdStream out(defaultStream::output_fd());
1095 out.print_raw("Current thread is ");
1096 char buf[16];
1097 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1098 out.print_raw_cr(buf);
1099 out.print_raw_cr("Dumping core ...");
1100 #endif
1101 ::abort(); // dump core
1102 }
1104 ::exit(1);
1105 }
1107 // Die immediately, no exit hook, no abort hook, no cleanup.
1108 void os::die() {
1109 // _exit() on BsdThreads only kills current thread
1110 ::abort();
1111 }
1113 // unused on bsd for now.
1114 void os::set_error_file(const char *logfile) {}
1117 // This method is a copy of JDK's sysGetLastErrorString
1118 // from src/solaris/hpi/src/system_md.c
1120 size_t os::lasterror(char *buf, size_t len) {
1122 if (errno == 0) return 0;
1124 const char *s = ::strerror(errno);
1125 size_t n = ::strlen(s);
1126 if (n >= len) {
1127 n = len - 1;
1128 }
1129 ::strncpy(buf, s, n);
1130 buf[n] = '\0';
1131 return n;
1132 }
1134 intx os::current_thread_id() {
1135 #ifdef __APPLE__
1136 return (intx)::mach_thread_self();
1137 #else
1138 return (intx)::pthread_self();
1139 #endif
1140 }
1141 int os::current_process_id() {
1143 // Under the old bsd thread library, bsd gives each thread
1144 // its own process id. Because of this each thread will return
1145 // a different pid if this method were to return the result
1146 // of getpid(2). Bsd provides no api that returns the pid
1147 // of the launcher thread for the vm. This implementation
1148 // returns a unique pid, the pid of the launcher thread
1149 // that starts the vm 'process'.
1151 // Under the NPTL, getpid() returns the same pid as the
1152 // launcher thread rather than a unique pid per thread.
1153 // Use gettid() if you want the old pre NPTL behaviour.
1155 // if you are looking for the result of a call to getpid() that
1156 // returns a unique pid for the calling thread, then look at the
1157 // OSThread::thread_id() method in osThread_bsd.hpp file
1159 return (int)(_initial_pid ? _initial_pid : getpid());
1160 }
1162 // DLL functions
1164 #define JNI_LIB_PREFIX "lib"
1165 #ifdef __APPLE__
1166 #define JNI_LIB_SUFFIX ".dylib"
1167 #else
1168 #define JNI_LIB_SUFFIX ".so"
1169 #endif
1171 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1173 // This must be hard coded because it's the system's temporary
1174 // directory not the java application's temp directory, ala java.io.tmpdir.
1175 #ifdef __APPLE__
1176 // macosx has a secure per-user temporary directory
1177 char temp_path_storage[PATH_MAX];
1178 const char* os::get_temp_directory() {
1179 static char *temp_path = NULL;
1180 if (temp_path == NULL) {
1181 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1182 if (pathSize == 0 || pathSize > PATH_MAX) {
1183 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1184 }
1185 temp_path = temp_path_storage;
1186 }
1187 return temp_path;
1188 }
1189 #else /* __APPLE__ */
1190 const char* os::get_temp_directory() { return "/tmp"; }
1191 #endif /* __APPLE__ */
1193 static bool file_exists(const char* filename) {
1194 struct stat statbuf;
1195 if (filename == NULL || strlen(filename) == 0) {
1196 return false;
1197 }
1198 return os::stat(filename, &statbuf) == 0;
1199 }
1201 bool os::dll_build_name(char* buffer, size_t buflen,
1202 const char* pname, const char* fname) {
1203 bool retval = false;
1204 // Copied from libhpi
1205 const size_t pnamelen = pname ? strlen(pname) : 0;
1207 // Return error on buffer overflow.
1208 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
1209 return retval;
1210 }
1212 if (pnamelen == 0) {
1213 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
1214 retval = true;
1215 } else if (strchr(pname, *os::path_separator()) != NULL) {
1216 int n;
1217 char** pelements = split_path(pname, &n);
1218 for (int i = 0 ; i < n ; i++) {
1219 // Really shouldn't be NULL, but check can't hurt
1220 if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1221 continue; // skip the empty path values
1222 }
1223 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
1224 pelements[i], fname);
1225 if (file_exists(buffer)) {
1226 retval = true;
1227 break;
1228 }
1229 }
1230 // release the storage
1231 for (int i = 0 ; i < n ; i++) {
1232 if (pelements[i] != NULL) {
1233 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1234 }
1235 }
1236 if (pelements != NULL) {
1237 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1238 }
1239 } else {
1240 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
1241 retval = true;
1242 }
1243 return retval;
1244 }
1246 const char* os::get_current_directory(char *buf, int buflen) {
1247 return getcwd(buf, buflen);
1248 }
1250 // check if addr is inside libjvm[_g].so
1251 bool os::address_is_in_vm(address addr) {
1252 static address libjvm_base_addr;
1253 Dl_info dlinfo;
1255 if (libjvm_base_addr == NULL) {
1256 dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
1257 libjvm_base_addr = (address)dlinfo.dli_fbase;
1258 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1259 }
1261 if (dladdr((void *)addr, &dlinfo)) {
1262 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1263 }
1265 return false;
1266 }
1269 #define MACH_MAXSYMLEN 256
1271 bool os::dll_address_to_function_name(address addr, char *buf,
1272 int buflen, int *offset) {
1273 Dl_info dlinfo;
1274 char localbuf[MACH_MAXSYMLEN];
1276 // dladdr will find names of dynamic functions only, but does
1277 // it set dli_fbase with mach_header address when it "fails" ?
1278 if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
1279 if (buf != NULL) {
1280 if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1281 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1282 }
1283 }
1284 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1285 return true;
1286 } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
1287 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1288 buf, buflen, offset, dlinfo.dli_fname)) {
1289 return true;
1290 }
1291 }
1293 // Handle non-dymanic manually:
1294 if (dlinfo.dli_fbase != NULL &&
1295 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) {
1296 if(!Decoder::demangle(localbuf, buf, buflen)) {
1297 jio_snprintf(buf, buflen, "%s", localbuf);
1298 }
1299 return true;
1300 }
1301 if (buf != NULL) buf[0] = '\0';
1302 if (offset != NULL) *offset = -1;
1303 return false;
1304 }
1306 // ported from solaris version
1307 bool os::dll_address_to_library_name(address addr, char* buf,
1308 int buflen, int* offset) {
1309 Dl_info dlinfo;
1311 if (dladdr((void*)addr, &dlinfo)){
1312 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1313 if (offset) *offset = addr - (address)dlinfo.dli_fbase;
1314 return true;
1315 } else {
1316 if (buf) buf[0] = '\0';
1317 if (offset) *offset = -1;
1318 return false;
1319 }
1320 }
1322 // Loads .dll/.so and
1323 // in case of error it checks if .dll/.so was built for the
1324 // same architecture as Hotspot is running on
1326 #ifdef __APPLE__
1327 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1328 void * result= ::dlopen(filename, RTLD_LAZY);
1329 if (result != NULL) {
1330 // Successful loading
1331 return result;
1332 }
1334 // Read system error message into ebuf
1335 ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1336 ebuf[ebuflen-1]='\0';
1338 return NULL;
1339 }
1340 #else
1341 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1342 {
1343 void * result= ::dlopen(filename, RTLD_LAZY);
1344 if (result != NULL) {
1345 // Successful loading
1346 return result;
1347 }
1349 Elf32_Ehdr elf_head;
1351 // Read system error message into ebuf
1352 // It may or may not be overwritten below
1353 ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1354 ebuf[ebuflen-1]='\0';
1355 int diag_msg_max_length=ebuflen-strlen(ebuf);
1356 char* diag_msg_buf=ebuf+strlen(ebuf);
1358 if (diag_msg_max_length==0) {
1359 // No more space in ebuf for additional diagnostics message
1360 return NULL;
1361 }
1364 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1366 if (file_descriptor < 0) {
1367 // Can't open library, report dlerror() message
1368 return NULL;
1369 }
1371 bool failed_to_read_elf_head=
1372 (sizeof(elf_head)!=
1373 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1375 ::close(file_descriptor);
1376 if (failed_to_read_elf_head) {
1377 // file i/o error - report dlerror() msg
1378 return NULL;
1379 }
1381 typedef struct {
1382 Elf32_Half code; // Actual value as defined in elf.h
1383 Elf32_Half compat_class; // Compatibility of archs at VM's sense
1384 char elf_class; // 32 or 64 bit
1385 char endianess; // MSB or LSB
1386 char* name; // String representation
1387 } arch_t;
1389 #ifndef EM_486
1390 #define EM_486 6 /* Intel 80486 */
1391 #endif
1393 #ifndef EM_MIPS_RS3_LE
1394 #define EM_MIPS_RS3_LE 10 /* MIPS */
1395 #endif
1397 #ifndef EM_PPC64
1398 #define EM_PPC64 21 /* PowerPC64 */
1399 #endif
1401 #ifndef EM_S390
1402 #define EM_S390 22 /* IBM System/390 */
1403 #endif
1405 #ifndef EM_IA_64
1406 #define EM_IA_64 50 /* HP/Intel IA-64 */
1407 #endif
1409 #ifndef EM_X86_64
1410 #define EM_X86_64 62 /* AMD x86-64 */
1411 #endif
1413 static const arch_t arch_array[]={
1414 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1415 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1416 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1417 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1418 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1419 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1420 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1421 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1422 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1423 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1424 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1425 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1426 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1427 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1428 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1429 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1430 };
1432 #if (defined IA32)
1433 static Elf32_Half running_arch_code=EM_386;
1434 #elif (defined AMD64)
1435 static Elf32_Half running_arch_code=EM_X86_64;
1436 #elif (defined IA64)
1437 static Elf32_Half running_arch_code=EM_IA_64;
1438 #elif (defined __sparc) && (defined _LP64)
1439 static Elf32_Half running_arch_code=EM_SPARCV9;
1440 #elif (defined __sparc) && (!defined _LP64)
1441 static Elf32_Half running_arch_code=EM_SPARC;
1442 #elif (defined __powerpc64__)
1443 static Elf32_Half running_arch_code=EM_PPC64;
1444 #elif (defined __powerpc__)
1445 static Elf32_Half running_arch_code=EM_PPC;
1446 #elif (defined ARM)
1447 static Elf32_Half running_arch_code=EM_ARM;
1448 #elif (defined S390)
1449 static Elf32_Half running_arch_code=EM_S390;
1450 #elif (defined ALPHA)
1451 static Elf32_Half running_arch_code=EM_ALPHA;
1452 #elif (defined MIPSEL)
1453 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1454 #elif (defined PARISC)
1455 static Elf32_Half running_arch_code=EM_PARISC;
1456 #elif (defined MIPS)
1457 static Elf32_Half running_arch_code=EM_MIPS;
1458 #elif (defined M68K)
1459 static Elf32_Half running_arch_code=EM_68K;
1460 #else
1461 #error Method os::dll_load requires that one of following is defined:\
1462 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1463 #endif
1465 // Identify compatability class for VM's architecture and library's architecture
1466 // Obtain string descriptions for architectures
1468 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1469 int running_arch_index=-1;
1471 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
1472 if (running_arch_code == arch_array[i].code) {
1473 running_arch_index = i;
1474 }
1475 if (lib_arch.code == arch_array[i].code) {
1476 lib_arch.compat_class = arch_array[i].compat_class;
1477 lib_arch.name = arch_array[i].name;
1478 }
1479 }
1481 assert(running_arch_index != -1,
1482 "Didn't find running architecture code (running_arch_code) in arch_array");
1483 if (running_arch_index == -1) {
1484 // Even though running architecture detection failed
1485 // we may still continue with reporting dlerror() message
1486 return NULL;
1487 }
1489 if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1490 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1491 return NULL;
1492 }
1494 #ifndef S390
1495 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1496 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1497 return NULL;
1498 }
1499 #endif // !S390
1501 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1502 if ( lib_arch.name!=NULL ) {
1503 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1504 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1505 lib_arch.name, arch_array[running_arch_index].name);
1506 } else {
1507 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1508 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1509 lib_arch.code,
1510 arch_array[running_arch_index].name);
1511 }
1512 }
1514 return NULL;
1515 }
1516 #endif /* !__APPLE__ */
1518 // XXX: Do we need a lock around this as per Linux?
1519 void* os::dll_lookup(void* handle, const char* name) {
1520 return dlsym(handle, name);
1521 }
1524 static bool _print_ascii_file(const char* filename, outputStream* st) {
1525 int fd = ::open(filename, O_RDONLY);
1526 if (fd == -1) {
1527 return false;
1528 }
1530 char buf[32];
1531 int bytes;
1532 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1533 st->print_raw(buf, bytes);
1534 }
1536 ::close(fd);
1538 return true;
1539 }
1541 void os::print_dll_info(outputStream *st) {
1542 st->print_cr("Dynamic libraries:");
1543 #ifdef RTLD_DI_LINKMAP
1544 Dl_info dli;
1545 void *handle;
1546 Link_map *map;
1547 Link_map *p;
1549 if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) {
1550 st->print_cr("Error: Cannot print dynamic libraries.");
1551 return;
1552 }
1553 handle = dlopen(dli.dli_fname, RTLD_LAZY);
1554 if (handle == NULL) {
1555 st->print_cr("Error: Cannot print dynamic libraries.");
1556 return;
1557 }
1558 dlinfo(handle, RTLD_DI_LINKMAP, &map);
1559 if (map == NULL) {
1560 st->print_cr("Error: Cannot print dynamic libraries.");
1561 return;
1562 }
1564 while (map->l_prev != NULL)
1565 map = map->l_prev;
1567 while (map != NULL) {
1568 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
1569 map = map->l_next;
1570 }
1572 dlclose(handle);
1573 #elif defined(__APPLE__)
1574 uint32_t count;
1575 uint32_t i;
1577 count = _dyld_image_count();
1578 for (i = 1; i < count; i++) {
1579 const char *name = _dyld_get_image_name(i);
1580 intptr_t slide = _dyld_get_image_vmaddr_slide(i);
1581 st->print_cr(PTR_FORMAT " \t%s", slide, name);
1582 }
1583 #else
1584 st->print_cr("Error: Cannot print dynamic libraries.");
1585 #endif
1586 }
1588 void os::print_os_info_brief(outputStream* st) {
1589 st->print("Bsd");
1591 os::Posix::print_uname_info(st);
1592 }
1594 void os::print_os_info(outputStream* st) {
1595 st->print("OS:");
1596 st->print("Bsd");
1598 os::Posix::print_uname_info(st);
1600 os::Posix::print_rlimit_info(st);
1602 os::Posix::print_load_average(st);
1603 }
1605 void os::pd_print_cpu_info(outputStream* st) {
1606 // Nothing to do for now.
1607 }
1609 void os::print_memory_info(outputStream* st) {
1611 st->print("Memory:");
1612 st->print(" %dk page", os::vm_page_size()>>10);
1614 st->print(", physical " UINT64_FORMAT "k",
1615 os::physical_memory() >> 10);
1616 st->print("(" UINT64_FORMAT "k free)",
1617 os::available_memory() >> 10);
1618 st->cr();
1620 // meminfo
1621 st->print("\n/proc/meminfo:\n");
1622 _print_ascii_file("/proc/meminfo", st);
1623 st->cr();
1624 }
1626 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific
1627 // but they're the same for all the bsd arch that we support
1628 // and they're the same for solaris but there's no common place to put this.
1629 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
1630 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
1631 "ILL_COPROC", "ILL_BADSTK" };
1633 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
1634 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
1635 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
1637 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
1639 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
1641 void os::print_siginfo(outputStream* st, void* siginfo) {
1642 st->print("siginfo:");
1644 const int buflen = 100;
1645 char buf[buflen];
1646 siginfo_t *si = (siginfo_t*)siginfo;
1647 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
1648 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
1649 st->print("si_errno=%s", buf);
1650 } else {
1651 st->print("si_errno=%d", si->si_errno);
1652 }
1653 const int c = si->si_code;
1654 assert(c > 0, "unexpected si_code");
1655 switch (si->si_signo) {
1656 case SIGILL:
1657 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
1658 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1659 break;
1660 case SIGFPE:
1661 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
1662 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1663 break;
1664 case SIGSEGV:
1665 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
1666 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1667 break;
1668 case SIGBUS:
1669 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
1670 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1671 break;
1672 default:
1673 st->print(", si_code=%d", si->si_code);
1674 // no si_addr
1675 }
1677 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
1678 UseSharedSpaces) {
1679 FileMapInfo* mapinfo = FileMapInfo::current_info();
1680 if (mapinfo->is_in_shared_space(si->si_addr)) {
1681 st->print("\n\nError accessing class data sharing archive." \
1682 " Mapped file inaccessible during execution, " \
1683 " possible disk/network problem.");
1684 }
1685 }
1686 st->cr();
1687 }
1690 static void print_signal_handler(outputStream* st, int sig,
1691 char* buf, size_t buflen);
1693 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1694 st->print_cr("Signal Handlers:");
1695 print_signal_handler(st, SIGSEGV, buf, buflen);
1696 print_signal_handler(st, SIGBUS , buf, buflen);
1697 print_signal_handler(st, SIGFPE , buf, buflen);
1698 print_signal_handler(st, SIGPIPE, buf, buflen);
1699 print_signal_handler(st, SIGXFSZ, buf, buflen);
1700 print_signal_handler(st, SIGILL , buf, buflen);
1701 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
1702 print_signal_handler(st, SR_signum, buf, buflen);
1703 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1704 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1705 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1706 print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1707 }
1709 static char saved_jvm_path[MAXPATHLEN] = {0};
1711 // Find the full path to the current module, libjvm or libjvm_g
1712 void os::jvm_path(char *buf, jint buflen) {
1713 // Error checking.
1714 if (buflen < MAXPATHLEN) {
1715 assert(false, "must use a large-enough buffer");
1716 buf[0] = '\0';
1717 return;
1718 }
1719 // Lazy resolve the path to current module.
1720 if (saved_jvm_path[0] != 0) {
1721 strcpy(buf, saved_jvm_path);
1722 return;
1723 }
1725 char dli_fname[MAXPATHLEN];
1726 bool ret = dll_address_to_library_name(
1727 CAST_FROM_FN_PTR(address, os::jvm_path),
1728 dli_fname, sizeof(dli_fname), NULL);
1729 assert(ret != 0, "cannot locate libjvm");
1730 char *rp = realpath(dli_fname, buf);
1731 if (rp == NULL)
1732 return;
1734 if (Arguments::created_by_gamma_launcher()) {
1735 // Support for the gamma launcher. Typical value for buf is
1736 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at
1737 // the right place in the string, then assume we are installed in a JDK and
1738 // we're done. Otherwise, check for a JAVA_HOME environment variable and
1739 // construct a path to the JVM being overridden.
1741 const char *p = buf + strlen(buf) - 1;
1742 for (int count = 0; p > buf && count < 5; ++count) {
1743 for (--p; p > buf && *p != '/'; --p)
1744 /* empty */ ;
1745 }
1747 if (strncmp(p, "/jre/lib/", 9) != 0) {
1748 // Look for JAVA_HOME in the environment.
1749 char* java_home_var = ::getenv("JAVA_HOME");
1750 if (java_home_var != NULL && java_home_var[0] != 0) {
1751 char* jrelib_p;
1752 int len;
1754 // Check the current module name "libjvm" or "libjvm_g".
1755 p = strrchr(buf, '/');
1756 assert(strstr(p, "/libjvm") == p, "invalid library name");
1757 p = strstr(p, "_g") ? "_g" : "";
1759 rp = realpath(java_home_var, buf);
1760 if (rp == NULL)
1761 return;
1763 // determine if this is a legacy image or modules image
1764 // modules image doesn't have "jre" subdirectory
1765 len = strlen(buf);
1766 jrelib_p = buf + len;
1768 // Add the appropriate library subdir
1769 snprintf(jrelib_p, buflen-len, "/jre/lib");
1770 if (0 != access(buf, F_OK)) {
1771 snprintf(jrelib_p, buflen-len, "/lib");
1772 }
1774 // Add the appropriate client or server subdir
1775 len = strlen(buf);
1776 jrelib_p = buf + len;
1777 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1778 if (0 != access(buf, F_OK)) {
1779 snprintf(jrelib_p, buflen-len, "");
1780 }
1782 // If the path exists within JAVA_HOME, add the JVM library name
1783 // to complete the path to JVM being overridden. Otherwise fallback
1784 // to the path to the current library.
1785 if (0 == access(buf, F_OK)) {
1786 // Use current module name "libjvm[_g]" instead of
1787 // "libjvm"debug_only("_g")"" since for fastdebug version
1788 // we should have "libjvm" but debug_only("_g") adds "_g"!
1789 len = strlen(buf);
1790 snprintf(buf + len, buflen-len, "/libjvm%s%s", p, JNI_LIB_SUFFIX);
1791 } else {
1792 // Fall back to path of current library
1793 rp = realpath(dli_fname, buf);
1794 if (rp == NULL)
1795 return;
1796 }
1797 }
1798 }
1799 }
1801 strcpy(saved_jvm_path, buf);
1802 }
1804 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1805 // no prefix required, not even "_"
1806 }
1808 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1809 // no suffix required
1810 }
1812 ////////////////////////////////////////////////////////////////////////////////
1813 // sun.misc.Signal support
1815 static volatile jint sigint_count = 0;
1817 static void
1818 UserHandler(int sig, void *siginfo, void *context) {
1819 // 4511530 - sem_post is serialized and handled by the manager thread. When
1820 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
1821 // don't want to flood the manager thread with sem_post requests.
1822 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
1823 return;
1825 // Ctrl-C is pressed during error reporting, likely because the error
1826 // handler fails to abort. Let VM die immediately.
1827 if (sig == SIGINT && is_error_reported()) {
1828 os::die();
1829 }
1831 os::signal_notify(sig);
1832 }
1834 void* os::user_handler() {
1835 return CAST_FROM_FN_PTR(void*, UserHandler);
1836 }
1838 extern "C" {
1839 typedef void (*sa_handler_t)(int);
1840 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1841 }
1843 void* os::signal(int signal_number, void* handler) {
1844 struct sigaction sigAct, oldSigAct;
1846 sigfillset(&(sigAct.sa_mask));
1847 sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
1848 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1850 if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1851 // -1 means registration failed
1852 return (void *)-1;
1853 }
1855 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1856 }
1858 void os::signal_raise(int signal_number) {
1859 ::raise(signal_number);
1860 }
1862 /*
1863 * The following code is moved from os.cpp for making this
1864 * code platform specific, which it is by its very nature.
1865 */
1867 // Will be modified when max signal is changed to be dynamic
1868 int os::sigexitnum_pd() {
1869 return NSIG;
1870 }
1872 // a counter for each possible signal value
1873 static volatile jint pending_signals[NSIG+1] = { 0 };
1875 // Bsd(POSIX) specific hand shaking semaphore.
1876 #ifdef __APPLE__
1877 static semaphore_t sig_sem;
1878 #define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
1879 #define SEM_WAIT(sem) semaphore_wait(sem);
1880 #define SEM_POST(sem) semaphore_signal(sem);
1881 #else
1882 static sem_t sig_sem;
1883 #define SEM_INIT(sem, value) sem_init(&sem, 0, value)
1884 #define SEM_WAIT(sem) sem_wait(&sem);
1885 #define SEM_POST(sem) sem_post(&sem);
1886 #endif
1888 void os::signal_init_pd() {
1889 // Initialize signal structures
1890 ::memset((void*)pending_signals, 0, sizeof(pending_signals));
1892 // Initialize signal semaphore
1893 ::SEM_INIT(sig_sem, 0);
1894 }
1896 void os::signal_notify(int sig) {
1897 Atomic::inc(&pending_signals[sig]);
1898 ::SEM_POST(sig_sem);
1899 }
1901 static int check_pending_signals(bool wait) {
1902 Atomic::store(0, &sigint_count);
1903 for (;;) {
1904 for (int i = 0; i < NSIG + 1; i++) {
1905 jint n = pending_signals[i];
1906 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
1907 return i;
1908 }
1909 }
1910 if (!wait) {
1911 return -1;
1912 }
1913 JavaThread *thread = JavaThread::current();
1914 ThreadBlockInVM tbivm(thread);
1916 bool threadIsSuspended;
1917 do {
1918 thread->set_suspend_equivalent();
1919 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
1920 ::SEM_WAIT(sig_sem);
1922 // were we externally suspended while we were waiting?
1923 threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
1924 if (threadIsSuspended) {
1925 //
1926 // The semaphore has been incremented, but while we were waiting
1927 // another thread suspended us. We don't want to continue running
1928 // while suspended because that would surprise the thread that
1929 // suspended us.
1930 //
1931 ::SEM_POST(sig_sem);
1933 thread->java_suspend_self();
1934 }
1935 } while (threadIsSuspended);
1936 }
1937 }
1939 int os::signal_lookup() {
1940 return check_pending_signals(false);
1941 }
1943 int os::signal_wait() {
1944 return check_pending_signals(true);
1945 }
1947 ////////////////////////////////////////////////////////////////////////////////
1948 // Virtual Memory
1950 int os::vm_page_size() {
1951 // Seems redundant as all get out
1952 assert(os::Bsd::page_size() != -1, "must call os::init");
1953 return os::Bsd::page_size();
1954 }
1956 // Solaris allocates memory by pages.
1957 int os::vm_allocation_granularity() {
1958 assert(os::Bsd::page_size() != -1, "must call os::init");
1959 return os::Bsd::page_size();
1960 }
1962 // Rationale behind this function:
1963 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
1964 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
1965 // samples for JITted code. Here we create private executable mapping over the code cache
1966 // and then we can use standard (well, almost, as mapping can change) way to provide
1967 // info for the reporting script by storing timestamp and location of symbol
1968 void bsd_wrap_code(char* base, size_t size) {
1969 static volatile jint cnt = 0;
1971 if (!UseOprofile) {
1972 return;
1973 }
1975 char buf[PATH_MAX + 1];
1976 int num = Atomic::add(1, &cnt);
1978 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
1979 os::get_temp_directory(), os::current_process_id(), num);
1980 unlink(buf);
1982 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
1984 if (fd != -1) {
1985 off_t rv = ::lseek(fd, size-2, SEEK_SET);
1986 if (rv != (off_t)-1) {
1987 if (::write(fd, "", 1) == 1) {
1988 mmap(base, size,
1989 PROT_READ|PROT_WRITE|PROT_EXEC,
1990 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
1991 }
1992 }
1993 ::close(fd);
1994 unlink(buf);
1995 }
1996 }
1998 // NOTE: Bsd kernel does not really reserve the pages for us.
1999 // All it does is to check if there are enough free pages
2000 // left at the time of mmap(). This could be a potential
2001 // problem.
2002 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2003 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2004 #ifdef __OpenBSD__
2005 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2006 return ::mprotect(addr, size, prot) == 0;
2007 #else
2008 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2009 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2010 return res != (uintptr_t) MAP_FAILED;
2011 #endif
2012 }
2015 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2016 bool exec) {
2017 return commit_memory(addr, size, exec);
2018 }
2020 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2021 }
2023 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2024 ::madvise(addr, bytes, MADV_DONTNEED);
2025 }
2027 void os::numa_make_global(char *addr, size_t bytes) {
2028 }
2030 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2031 }
2033 bool os::numa_topology_changed() { return false; }
2035 size_t os::numa_get_groups_num() {
2036 return 1;
2037 }
2039 int os::numa_get_group_id() {
2040 return 0;
2041 }
2043 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2044 if (size > 0) {
2045 ids[0] = 0;
2046 return 1;
2047 }
2048 return 0;
2049 }
2051 bool os::get_page_info(char *start, page_info* info) {
2052 return false;
2053 }
2055 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2056 return end;
2057 }
2060 bool os::pd_uncommit_memory(char* addr, size_t size) {
2061 #ifdef __OpenBSD__
2062 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2063 return ::mprotect(addr, size, PROT_NONE) == 0;
2064 #else
2065 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2066 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2067 return res != (uintptr_t) MAP_FAILED;
2068 #endif
2069 }
2071 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2072 return os::commit_memory(addr, size);
2073 }
2075 // If this is a growable mapping, remove the guard pages entirely by
2076 // munmap()ping them. If not, just call uncommit_memory().
2077 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2078 return os::uncommit_memory(addr, size);
2079 }
2081 static address _highest_vm_reserved_address = NULL;
2083 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2084 // at 'requested_addr'. If there are existing memory mappings at the same
2085 // location, however, they will be overwritten. If 'fixed' is false,
2086 // 'requested_addr' is only treated as a hint, the return value may or
2087 // may not start from the requested address. Unlike Bsd mmap(), this
2088 // function returns NULL to indicate failure.
2089 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2090 char * addr;
2091 int flags;
2093 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2094 if (fixed) {
2095 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2096 flags |= MAP_FIXED;
2097 }
2099 // Map uncommitted pages PROT_READ and PROT_WRITE, change access
2100 // to PROT_EXEC if executable when we commit the page.
2101 addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
2102 flags, -1, 0);
2104 if (addr != MAP_FAILED) {
2105 // anon_mmap() should only get called during VM initialization,
2106 // don't need lock (actually we can skip locking even it can be called
2107 // from multiple threads, because _highest_vm_reserved_address is just a
2108 // hint about the upper limit of non-stack memory regions.)
2109 if ((address)addr + bytes > _highest_vm_reserved_address) {
2110 _highest_vm_reserved_address = (address)addr + bytes;
2111 }
2112 }
2114 return addr == MAP_FAILED ? NULL : addr;
2115 }
2117 // Don't update _highest_vm_reserved_address, because there might be memory
2118 // regions above addr + size. If so, releasing a memory region only creates
2119 // a hole in the address space, it doesn't help prevent heap-stack collision.
2120 //
2121 static int anon_munmap(char * addr, size_t size) {
2122 return ::munmap(addr, size) == 0;
2123 }
2125 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2126 size_t alignment_hint) {
2127 return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2128 }
2130 bool os::pd_release_memory(char* addr, size_t size) {
2131 return anon_munmap(addr, size);
2132 }
2134 static address highest_vm_reserved_address() {
2135 return _highest_vm_reserved_address;
2136 }
2138 static bool bsd_mprotect(char* addr, size_t size, int prot) {
2139 // Bsd wants the mprotect address argument to be page aligned.
2140 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
2142 // According to SUSv3, mprotect() should only be used with mappings
2143 // established by mmap(), and mmap() always maps whole pages. Unaligned
2144 // 'addr' likely indicates problem in the VM (e.g. trying to change
2145 // protection of malloc'ed or statically allocated memory). Check the
2146 // caller if you hit this assert.
2147 assert(addr == bottom, "sanity check");
2149 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2150 return ::mprotect(bottom, size, prot) == 0;
2151 }
2153 // Set protections specified
2154 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2155 bool is_committed) {
2156 unsigned int p = 0;
2157 switch (prot) {
2158 case MEM_PROT_NONE: p = PROT_NONE; break;
2159 case MEM_PROT_READ: p = PROT_READ; break;
2160 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
2161 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2162 default:
2163 ShouldNotReachHere();
2164 }
2165 // is_committed is unused.
2166 return bsd_mprotect(addr, bytes, p);
2167 }
2169 bool os::guard_memory(char* addr, size_t size) {
2170 return bsd_mprotect(addr, size, PROT_NONE);
2171 }
2173 bool os::unguard_memory(char* addr, size_t size) {
2174 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2175 }
2177 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2178 return false;
2179 }
2181 /*
2182 * Set the coredump_filter bits to include largepages in core dump (bit 6)
2183 *
2184 * From the coredump_filter documentation:
2185 *
2186 * - (bit 0) anonymous private memory
2187 * - (bit 1) anonymous shared memory
2188 * - (bit 2) file-backed private memory
2189 * - (bit 3) file-backed shared memory
2190 * - (bit 4) ELF header pages in file-backed private memory areas (it is
2191 * effective only if the bit 2 is cleared)
2192 * - (bit 5) hugetlb private memory
2193 * - (bit 6) hugetlb shared memory
2194 */
2195 static void set_coredump_filter(void) {
2196 FILE *f;
2197 long cdm;
2199 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
2200 return;
2201 }
2203 if (fscanf(f, "%lx", &cdm) != 1) {
2204 fclose(f);
2205 return;
2206 }
2208 rewind(f);
2210 if ((cdm & LARGEPAGES_BIT) == 0) {
2211 cdm |= LARGEPAGES_BIT;
2212 fprintf(f, "%#lx", cdm);
2213 }
2215 fclose(f);
2216 }
2218 // Large page support
2220 static size_t _large_page_size = 0;
2222 void os::large_page_init() {
2223 }
2226 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
2227 // "exec" is passed in but not used. Creating the shared image for
2228 // the code cache doesn't have an SHM_X executable permission to check.
2229 assert(UseLargePages && UseSHM, "only for SHM large pages");
2231 key_t key = IPC_PRIVATE;
2232 char *addr;
2234 bool warn_on_failure = UseLargePages &&
2235 (!FLAG_IS_DEFAULT(UseLargePages) ||
2236 !FLAG_IS_DEFAULT(LargePageSizeInBytes)
2237 );
2238 char msg[128];
2240 // Create a large shared memory region to attach to based on size.
2241 // Currently, size is the total size of the heap
2242 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
2243 if (shmid == -1) {
2244 // Possible reasons for shmget failure:
2245 // 1. shmmax is too small for Java heap.
2246 // > check shmmax value: cat /proc/sys/kernel/shmmax
2247 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
2248 // 2. not enough large page memory.
2249 // > check available large pages: cat /proc/meminfo
2250 // > increase amount of large pages:
2251 // echo new_value > /proc/sys/vm/nr_hugepages
2252 // Note 1: different Bsd may use different name for this property,
2253 // e.g. on Redhat AS-3 it is "hugetlb_pool".
2254 // Note 2: it's possible there's enough physical memory available but
2255 // they are so fragmented after a long run that they can't
2256 // coalesce into large pages. Try to reserve large pages when
2257 // the system is still "fresh".
2258 if (warn_on_failure) {
2259 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
2260 warning(msg);
2261 }
2262 return NULL;
2263 }
2265 // attach to the region
2266 addr = (char*)shmat(shmid, req_addr, 0);
2267 int err = errno;
2269 // Remove shmid. If shmat() is successful, the actual shared memory segment
2270 // will be deleted when it's detached by shmdt() or when the process
2271 // terminates. If shmat() is not successful this will remove the shared
2272 // segment immediately.
2273 shmctl(shmid, IPC_RMID, NULL);
2275 if ((intptr_t)addr == -1) {
2276 if (warn_on_failure) {
2277 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
2278 warning(msg);
2279 }
2280 return NULL;
2281 }
2283 return addr;
2284 }
2286 bool os::release_memory_special(char* base, size_t bytes) {
2287 // detaching the SHM segment will also delete it, see reserve_memory_special()
2288 int rslt = shmdt(base);
2289 return rslt == 0;
2290 }
2292 size_t os::large_page_size() {
2293 return _large_page_size;
2294 }
2296 // HugeTLBFS allows application to commit large page memory on demand;
2297 // with SysV SHM the entire memory region must be allocated as shared
2298 // memory.
2299 bool os::can_commit_large_page_memory() {
2300 return UseHugeTLBFS;
2301 }
2303 bool os::can_execute_large_page_memory() {
2304 return UseHugeTLBFS;
2305 }
2307 // Reserve memory at an arbitrary address, only if that area is
2308 // available (and not reserved for something else).
2310 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2311 const int max_tries = 10;
2312 char* base[max_tries];
2313 size_t size[max_tries];
2314 const size_t gap = 0x000000;
2316 // Assert only that the size is a multiple of the page size, since
2317 // that's all that mmap requires, and since that's all we really know
2318 // about at this low abstraction level. If we need higher alignment,
2319 // we can either pass an alignment to this method or verify alignment
2320 // in one of the methods further up the call chain. See bug 5044738.
2321 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2323 // Repeatedly allocate blocks until the block is allocated at the
2324 // right spot. Give up after max_tries. Note that reserve_memory() will
2325 // automatically update _highest_vm_reserved_address if the call is
2326 // successful. The variable tracks the highest memory address every reserved
2327 // by JVM. It is used to detect heap-stack collision if running with
2328 // fixed-stack BsdThreads. Because here we may attempt to reserve more
2329 // space than needed, it could confuse the collision detecting code. To
2330 // solve the problem, save current _highest_vm_reserved_address and
2331 // calculate the correct value before return.
2332 address old_highest = _highest_vm_reserved_address;
2334 // Bsd mmap allows caller to pass an address as hint; give it a try first,
2335 // if kernel honors the hint then we can return immediately.
2336 char * addr = anon_mmap(requested_addr, bytes, false);
2337 if (addr == requested_addr) {
2338 return requested_addr;
2339 }
2341 if (addr != NULL) {
2342 // mmap() is successful but it fails to reserve at the requested address
2343 anon_munmap(addr, bytes);
2344 }
2346 int i;
2347 for (i = 0; i < max_tries; ++i) {
2348 base[i] = reserve_memory(bytes);
2350 if (base[i] != NULL) {
2351 // Is this the block we wanted?
2352 if (base[i] == requested_addr) {
2353 size[i] = bytes;
2354 break;
2355 }
2357 // Does this overlap the block we wanted? Give back the overlapped
2358 // parts and try again.
2360 size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2361 if (top_overlap >= 0 && top_overlap < bytes) {
2362 unmap_memory(base[i], top_overlap);
2363 base[i] += top_overlap;
2364 size[i] = bytes - top_overlap;
2365 } else {
2366 size_t bottom_overlap = base[i] + bytes - requested_addr;
2367 if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2368 unmap_memory(requested_addr, bottom_overlap);
2369 size[i] = bytes - bottom_overlap;
2370 } else {
2371 size[i] = bytes;
2372 }
2373 }
2374 }
2375 }
2377 // Give back the unused reserved pieces.
2379 for (int j = 0; j < i; ++j) {
2380 if (base[j] != NULL) {
2381 unmap_memory(base[j], size[j]);
2382 }
2383 }
2385 if (i < max_tries) {
2386 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
2387 return requested_addr;
2388 } else {
2389 _highest_vm_reserved_address = old_highest;
2390 return NULL;
2391 }
2392 }
2394 size_t os::read(int fd, void *buf, unsigned int nBytes) {
2395 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
2396 }
2398 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
2399 // Solaris uses poll(), bsd uses park().
2400 // Poll() is likely a better choice, assuming that Thread.interrupt()
2401 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
2402 // SIGSEGV, see 4355769.
2404 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
2405 assert(thread == Thread::current(), "thread consistency check");
2407 ParkEvent * const slp = thread->_SleepEvent ;
2408 slp->reset() ;
2409 OrderAccess::fence() ;
2411 if (interruptible) {
2412 jlong prevtime = javaTimeNanos();
2414 for (;;) {
2415 if (os::is_interrupted(thread, true)) {
2416 return OS_INTRPT;
2417 }
2419 jlong newtime = javaTimeNanos();
2421 if (newtime - prevtime < 0) {
2422 // time moving backwards, should only happen if no monotonic clock
2423 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2424 assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2425 } else {
2426 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2427 }
2429 if(millis <= 0) {
2430 return OS_OK;
2431 }
2433 prevtime = newtime;
2435 {
2436 assert(thread->is_Java_thread(), "sanity check");
2437 JavaThread *jt = (JavaThread *) thread;
2438 ThreadBlockInVM tbivm(jt);
2439 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
2441 jt->set_suspend_equivalent();
2442 // cleared by handle_special_suspend_equivalent_condition() or
2443 // java_suspend_self() via check_and_wait_while_suspended()
2445 slp->park(millis);
2447 // were we externally suspended while we were waiting?
2448 jt->check_and_wait_while_suspended();
2449 }
2450 }
2451 } else {
2452 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
2453 jlong prevtime = javaTimeNanos();
2455 for (;;) {
2456 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
2457 // the 1st iteration ...
2458 jlong newtime = javaTimeNanos();
2460 if (newtime - prevtime < 0) {
2461 // time moving backwards, should only happen if no monotonic clock
2462 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2463 assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2464 } else {
2465 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2466 }
2468 if(millis <= 0) break ;
2470 prevtime = newtime;
2471 slp->park(millis);
2472 }
2473 return OS_OK ;
2474 }
2475 }
2477 int os::naked_sleep() {
2478 // %% make the sleep time an integer flag. for now use 1 millisec.
2479 return os::sleep(Thread::current(), 1, false);
2480 }
2482 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2483 void os::infinite_sleep() {
2484 while (true) { // sleep forever ...
2485 ::sleep(100); // ... 100 seconds at a time
2486 }
2487 }
2489 // Used to convert frequent JVM_Yield() to nops
2490 bool os::dont_yield() {
2491 return DontYieldALot;
2492 }
2494 void os::yield() {
2495 sched_yield();
2496 }
2498 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
2500 void os::yield_all(int attempts) {
2501 // Yields to all threads, including threads with lower priorities
2502 // Threads on Bsd are all with same priority. The Solaris style
2503 // os::yield_all() with nanosleep(1ms) is not necessary.
2504 sched_yield();
2505 }
2507 // Called from the tight loops to possibly influence time-sharing heuristics
2508 void os::loop_breaker(int attempts) {
2509 os::yield_all(attempts);
2510 }
2512 ////////////////////////////////////////////////////////////////////////////////
2513 // thread priority support
2515 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2516 // only supports dynamic priority, static priority must be zero. For real-time
2517 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2518 // However, for large multi-threaded applications, SCHED_RR is not only slower
2519 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2520 // of 5 runs - Sep 2005).
2521 //
2522 // The following code actually changes the niceness of kernel-thread/LWP. It
2523 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2524 // not the entire user process, and user level threads are 1:1 mapped to kernel
2525 // threads. It has always been the case, but could change in the future. For
2526 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2527 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
2529 #if !defined(__APPLE__)
2530 int os::java_to_os_priority[CriticalPriority + 1] = {
2531 19, // 0 Entry should never be used
2533 0, // 1 MinPriority
2534 3, // 2
2535 6, // 3
2537 10, // 4
2538 15, // 5 NormPriority
2539 18, // 6
2541 21, // 7
2542 25, // 8
2543 28, // 9 NearMaxPriority
2545 31, // 10 MaxPriority
2547 31 // 11 CriticalPriority
2548 };
2549 #else
2550 /* Using Mach high-level priority assignments */
2551 int os::java_to_os_priority[CriticalPriority + 1] = {
2552 0, // 0 Entry should never be used (MINPRI_USER)
2554 27, // 1 MinPriority
2555 28, // 2
2556 29, // 3
2558 30, // 4
2559 31, // 5 NormPriority (BASEPRI_DEFAULT)
2560 32, // 6
2562 33, // 7
2563 34, // 8
2564 35, // 9 NearMaxPriority
2566 36, // 10 MaxPriority
2568 36 // 11 CriticalPriority
2569 };
2570 #endif
2572 static int prio_init() {
2573 if (ThreadPriorityPolicy == 1) {
2574 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
2575 // if effective uid is not root. Perhaps, a more elegant way of doing
2576 // this is to test CAP_SYS_NICE capability, but that will require libcap.so
2577 if (geteuid() != 0) {
2578 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
2579 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
2580 }
2581 ThreadPriorityPolicy = 0;
2582 }
2583 }
2584 if (UseCriticalJavaThreadPriority) {
2585 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2586 }
2587 return 0;
2588 }
2590 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2591 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
2593 #ifdef __OpenBSD__
2594 // OpenBSD pthread_setprio starves low priority threads
2595 return OS_OK;
2596 #elif defined(__FreeBSD__)
2597 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2598 #elif defined(__APPLE__) || defined(__NetBSD__)
2599 struct sched_param sp;
2600 int policy;
2601 pthread_t self = pthread_self();
2603 if (pthread_getschedparam(self, &policy, &sp) != 0)
2604 return OS_ERR;
2606 sp.sched_priority = newpri;
2607 if (pthread_setschedparam(self, policy, &sp) != 0)
2608 return OS_ERR;
2610 return OS_OK;
2611 #else
2612 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2613 return (ret == 0) ? OS_OK : OS_ERR;
2614 #endif
2615 }
2617 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2618 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
2619 *priority_ptr = java_to_os_priority[NormPriority];
2620 return OS_OK;
2621 }
2623 errno = 0;
2624 #if defined(__OpenBSD__) || defined(__FreeBSD__)
2625 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2626 #elif defined(__APPLE__) || defined(__NetBSD__)
2627 int policy;
2628 struct sched_param sp;
2630 pthread_getschedparam(pthread_self(), &policy, &sp);
2631 *priority_ptr = sp.sched_priority;
2632 #else
2633 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2634 #endif
2635 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2636 }
2638 // Hint to the underlying OS that a task switch would not be good.
2639 // Void return because it's a hint and can fail.
2640 void os::hint_no_preempt() {}
2642 ////////////////////////////////////////////////////////////////////////////////
2643 // suspend/resume support
2645 // the low-level signal-based suspend/resume support is a remnant from the
2646 // old VM-suspension that used to be for java-suspension, safepoints etc,
2647 // within hotspot. Now there is a single use-case for this:
2648 // - calling get_thread_pc() on the VMThread by the flat-profiler task
2649 // that runs in the watcher thread.
2650 // The remaining code is greatly simplified from the more general suspension
2651 // code that used to be used.
2652 //
2653 // The protocol is quite simple:
2654 // - suspend:
2655 // - sends a signal to the target thread
2656 // - polls the suspend state of the osthread using a yield loop
2657 // - target thread signal handler (SR_handler) sets suspend state
2658 // and blocks in sigsuspend until continued
2659 // - resume:
2660 // - sets target osthread state to continue
2661 // - sends signal to end the sigsuspend loop in the SR_handler
2662 //
2663 // Note that the SR_lock plays no role in this suspend/resume protocol.
2664 //
2666 static void resume_clear_context(OSThread *osthread) {
2667 osthread->set_ucontext(NULL);
2668 osthread->set_siginfo(NULL);
2670 // notify the suspend action is completed, we have now resumed
2671 osthread->sr.clear_suspended();
2672 }
2674 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2675 osthread->set_ucontext(context);
2676 osthread->set_siginfo(siginfo);
2677 }
2679 //
2680 // Handler function invoked when a thread's execution is suspended or
2681 // resumed. We have to be careful that only async-safe functions are
2682 // called here (Note: most pthread functions are not async safe and
2683 // should be avoided.)
2684 //
2685 // Note: sigwait() is a more natural fit than sigsuspend() from an
2686 // interface point of view, but sigwait() prevents the signal hander
2687 // from being run. libpthread would get very confused by not having
2688 // its signal handlers run and prevents sigwait()'s use with the
2689 // mutex granting granting signal.
2690 //
2691 // Currently only ever called on the VMThread
2692 //
2693 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2694 // Save and restore errno to avoid confusing native code with EINTR
2695 // after sigsuspend.
2696 int old_errno = errno;
2698 Thread* thread = Thread::current();
2699 OSThread* osthread = thread->osthread();
2700 assert(thread->is_VM_thread(), "Must be VMThread");
2701 // read current suspend action
2702 int action = osthread->sr.suspend_action();
2703 if (action == SR_SUSPEND) {
2704 suspend_save_context(osthread, siginfo, context);
2706 // Notify the suspend action is about to be completed. do_suspend()
2707 // waits until SR_SUSPENDED is set and then returns. We will wait
2708 // here for a resume signal and that completes the suspend-other
2709 // action. do_suspend/do_resume is always called as a pair from
2710 // the same thread - so there are no races
2712 // notify the caller
2713 osthread->sr.set_suspended();
2715 sigset_t suspend_set; // signals for sigsuspend()
2717 // get current set of blocked signals and unblock resume signal
2718 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2719 sigdelset(&suspend_set, SR_signum);
2721 // wait here until we are resumed
2722 do {
2723 sigsuspend(&suspend_set);
2724 // ignore all returns until we get a resume signal
2725 } while (osthread->sr.suspend_action() != SR_CONTINUE);
2727 resume_clear_context(osthread);
2729 } else {
2730 assert(action == SR_CONTINUE, "unexpected sr action");
2731 // nothing special to do - just leave the handler
2732 }
2734 errno = old_errno;
2735 }
2738 static int SR_initialize() {
2739 struct sigaction act;
2740 char *s;
2741 /* Get signal number to use for suspend/resume */
2742 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2743 int sig = ::strtol(s, 0, 10);
2744 if (sig > 0 || sig < NSIG) {
2745 SR_signum = sig;
2746 }
2747 }
2749 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2750 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2752 sigemptyset(&SR_sigset);
2753 sigaddset(&SR_sigset, SR_signum);
2755 /* Set up signal handler for suspend/resume */
2756 act.sa_flags = SA_RESTART|SA_SIGINFO;
2757 act.sa_handler = (void (*)(int)) SR_handler;
2759 // SR_signum is blocked by default.
2760 // 4528190 - We also need to block pthread restart signal (32 on all
2761 // supported Bsd platforms). Note that BsdThreads need to block
2762 // this signal for all threads to work properly. So we don't have
2763 // to use hard-coded signal number when setting up the mask.
2764 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2766 if (sigaction(SR_signum, &act, 0) == -1) {
2767 return -1;
2768 }
2770 // Save signal flag
2771 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2772 return 0;
2773 }
2775 static int SR_finalize() {
2776 return 0;
2777 }
2780 // returns true on success and false on error - really an error is fatal
2781 // but this seems the normal response to library errors
2782 static bool do_suspend(OSThread* osthread) {
2783 // mark as suspended and send signal
2784 osthread->sr.set_suspend_action(SR_SUSPEND);
2785 int status = pthread_kill(osthread->pthread_id(), SR_signum);
2786 assert_status(status == 0, status, "pthread_kill");
2788 // check status and wait until notified of suspension
2789 if (status == 0) {
2790 for (int i = 0; !osthread->sr.is_suspended(); i++) {
2791 os::yield_all(i);
2792 }
2793 osthread->sr.set_suspend_action(SR_NONE);
2794 return true;
2795 }
2796 else {
2797 osthread->sr.set_suspend_action(SR_NONE);
2798 return false;
2799 }
2800 }
2802 static void do_resume(OSThread* osthread) {
2803 assert(osthread->sr.is_suspended(), "thread should be suspended");
2804 osthread->sr.set_suspend_action(SR_CONTINUE);
2806 int status = pthread_kill(osthread->pthread_id(), SR_signum);
2807 assert_status(status == 0, status, "pthread_kill");
2808 // check status and wait unit notified of resumption
2809 if (status == 0) {
2810 for (int i = 0; osthread->sr.is_suspended(); i++) {
2811 os::yield_all(i);
2812 }
2813 }
2814 osthread->sr.set_suspend_action(SR_NONE);
2815 }
2817 ////////////////////////////////////////////////////////////////////////////////
2818 // interrupt support
2820 void os::interrupt(Thread* thread) {
2821 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
2822 "possibility of dangling Thread pointer");
2824 OSThread* osthread = thread->osthread();
2826 if (!osthread->interrupted()) {
2827 osthread->set_interrupted(true);
2828 // More than one thread can get here with the same value of osthread,
2829 // resulting in multiple notifications. We do, however, want the store
2830 // to interrupted() to be visible to other threads before we execute unpark().
2831 OrderAccess::fence();
2832 ParkEvent * const slp = thread->_SleepEvent ;
2833 if (slp != NULL) slp->unpark() ;
2834 }
2836 // For JSR166. Unpark even if interrupt status already was set
2837 if (thread->is_Java_thread())
2838 ((JavaThread*)thread)->parker()->unpark();
2840 ParkEvent * ev = thread->_ParkEvent ;
2841 if (ev != NULL) ev->unpark() ;
2843 }
2845 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
2846 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
2847 "possibility of dangling Thread pointer");
2849 OSThread* osthread = thread->osthread();
2851 bool interrupted = osthread->interrupted();
2853 if (interrupted && clear_interrupted) {
2854 osthread->set_interrupted(false);
2855 // consider thread->_SleepEvent->reset() ... optional optimization
2856 }
2858 return interrupted;
2859 }
2861 ///////////////////////////////////////////////////////////////////////////////////
2862 // signal handling (except suspend/resume)
2864 // This routine may be used by user applications as a "hook" to catch signals.
2865 // The user-defined signal handler must pass unrecognized signals to this
2866 // routine, and if it returns true (non-zero), then the signal handler must
2867 // return immediately. If the flag "abort_if_unrecognized" is true, then this
2868 // routine will never retun false (zero), but instead will execute a VM panic
2869 // routine kill the process.
2870 //
2871 // If this routine returns false, it is OK to call it again. This allows
2872 // the user-defined signal handler to perform checks either before or after
2873 // the VM performs its own checks. Naturally, the user code would be making
2874 // a serious error if it tried to handle an exception (such as a null check
2875 // or breakpoint) that the VM was generating for its own correct operation.
2876 //
2877 // This routine may recognize any of the following kinds of signals:
2878 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
2879 // It should be consulted by handlers for any of those signals.
2880 //
2881 // The caller of this routine must pass in the three arguments supplied
2882 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
2883 // field of the structure passed to sigaction(). This routine assumes that
2884 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
2885 //
2886 // Note that the VM will print warnings if it detects conflicting signal
2887 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
2888 //
2889 extern "C" JNIEXPORT int
2890 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
2891 void* ucontext, int abort_if_unrecognized);
2893 void signalHandler(int sig, siginfo_t* info, void* uc) {
2894 assert(info != NULL && uc != NULL, "it must be old kernel");
2895 JVM_handle_bsd_signal(sig, info, uc, true);
2896 }
2899 // This boolean allows users to forward their own non-matching signals
2900 // to JVM_handle_bsd_signal, harmlessly.
2901 bool os::Bsd::signal_handlers_are_installed = false;
2903 // For signal-chaining
2904 struct sigaction os::Bsd::sigact[MAXSIGNUM];
2905 unsigned int os::Bsd::sigs = 0;
2906 bool os::Bsd::libjsig_is_loaded = false;
2907 typedef struct sigaction *(*get_signal_t)(int);
2908 get_signal_t os::Bsd::get_signal_action = NULL;
2910 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
2911 struct sigaction *actp = NULL;
2913 if (libjsig_is_loaded) {
2914 // Retrieve the old signal handler from libjsig
2915 actp = (*get_signal_action)(sig);
2916 }
2917 if (actp == NULL) {
2918 // Retrieve the preinstalled signal handler from jvm
2919 actp = get_preinstalled_handler(sig);
2920 }
2922 return actp;
2923 }
2925 static bool call_chained_handler(struct sigaction *actp, int sig,
2926 siginfo_t *siginfo, void *context) {
2927 // Call the old signal handler
2928 if (actp->sa_handler == SIG_DFL) {
2929 // It's more reasonable to let jvm treat it as an unexpected exception
2930 // instead of taking the default action.
2931 return false;
2932 } else if (actp->sa_handler != SIG_IGN) {
2933 if ((actp->sa_flags & SA_NODEFER) == 0) {
2934 // automaticlly block the signal
2935 sigaddset(&(actp->sa_mask), sig);
2936 }
2938 sa_handler_t hand;
2939 sa_sigaction_t sa;
2940 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
2941 // retrieve the chained handler
2942 if (siginfo_flag_set) {
2943 sa = actp->sa_sigaction;
2944 } else {
2945 hand = actp->sa_handler;
2946 }
2948 if ((actp->sa_flags & SA_RESETHAND) != 0) {
2949 actp->sa_handler = SIG_DFL;
2950 }
2952 // try to honor the signal mask
2953 sigset_t oset;
2954 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
2956 // call into the chained handler
2957 if (siginfo_flag_set) {
2958 (*sa)(sig, siginfo, context);
2959 } else {
2960 (*hand)(sig);
2961 }
2963 // restore the signal mask
2964 pthread_sigmask(SIG_SETMASK, &oset, 0);
2965 }
2966 // Tell jvm's signal handler the signal is taken care of.
2967 return true;
2968 }
2970 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
2971 bool chained = false;
2972 // signal-chaining
2973 if (UseSignalChaining) {
2974 struct sigaction *actp = get_chained_signal_action(sig);
2975 if (actp != NULL) {
2976 chained = call_chained_handler(actp, sig, siginfo, context);
2977 }
2978 }
2979 return chained;
2980 }
2982 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
2983 if ((( (unsigned int)1 << sig ) & sigs) != 0) {
2984 return &sigact[sig];
2985 }
2986 return NULL;
2987 }
2989 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
2990 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
2991 sigact[sig] = oldAct;
2992 sigs |= (unsigned int)1 << sig;
2993 }
2995 // for diagnostic
2996 int os::Bsd::sigflags[MAXSIGNUM];
2998 int os::Bsd::get_our_sigflags(int sig) {
2999 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3000 return sigflags[sig];
3001 }
3003 void os::Bsd::set_our_sigflags(int sig, int flags) {
3004 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3005 sigflags[sig] = flags;
3006 }
3008 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
3009 // Check for overwrite.
3010 struct sigaction oldAct;
3011 sigaction(sig, (struct sigaction*)NULL, &oldAct);
3013 void* oldhand = oldAct.sa_sigaction
3014 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3015 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3016 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3017 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3018 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
3019 if (AllowUserSignalHandlers || !set_installed) {
3020 // Do not overwrite; user takes responsibility to forward to us.
3021 return;
3022 } else if (UseSignalChaining) {
3023 // save the old handler in jvm
3024 save_preinstalled_handler(sig, oldAct);
3025 // libjsig also interposes the sigaction() call below and saves the
3026 // old sigaction on it own.
3027 } else {
3028 fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
3029 "%#lx for signal %d.", (long)oldhand, sig));
3030 }
3031 }
3033 struct sigaction sigAct;
3034 sigfillset(&(sigAct.sa_mask));
3035 sigAct.sa_handler = SIG_DFL;
3036 if (!set_installed) {
3037 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3038 } else {
3039 sigAct.sa_sigaction = signalHandler;
3040 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3041 }
3042 // Save flags, which are set by ours
3043 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3044 sigflags[sig] = sigAct.sa_flags;
3046 int ret = sigaction(sig, &sigAct, &oldAct);
3047 assert(ret == 0, "check");
3049 void* oldhand2 = oldAct.sa_sigaction
3050 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3051 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3052 assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3053 }
3055 // install signal handlers for signals that HotSpot needs to
3056 // handle in order to support Java-level exception handling.
3058 void os::Bsd::install_signal_handlers() {
3059 if (!signal_handlers_are_installed) {
3060 signal_handlers_are_installed = true;
3062 // signal-chaining
3063 typedef void (*signal_setting_t)();
3064 signal_setting_t begin_signal_setting = NULL;
3065 signal_setting_t end_signal_setting = NULL;
3066 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3067 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
3068 if (begin_signal_setting != NULL) {
3069 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3070 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
3071 get_signal_action = CAST_TO_FN_PTR(get_signal_t,
3072 dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
3073 libjsig_is_loaded = true;
3074 assert(UseSignalChaining, "should enable signal-chaining");
3075 }
3076 if (libjsig_is_loaded) {
3077 // Tell libjsig jvm is setting signal handlers
3078 (*begin_signal_setting)();
3079 }
3081 set_signal_handler(SIGSEGV, true);
3082 set_signal_handler(SIGPIPE, true);
3083 set_signal_handler(SIGBUS, true);
3084 set_signal_handler(SIGILL, true);
3085 set_signal_handler(SIGFPE, true);
3086 set_signal_handler(SIGXFSZ, true);
3088 #if defined(__APPLE__)
3089 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
3090 // signals caught and handled by the JVM. To work around this, we reset the mach task
3091 // signal handler that's placed on our process by CrashReporter. This disables
3092 // CrashReporter-based reporting.
3093 //
3094 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
3095 // on caught fatal signals.
3096 //
3097 // Additionally, gdb installs both standard BSD signal handlers, and mach exception
3098 // handlers. By replacing the existing task exception handler, we disable gdb's mach
3099 // exception handling, while leaving the standard BSD signal handlers functional.
3100 kern_return_t kr;
3101 kr = task_set_exception_ports(mach_task_self(),
3102 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
3103 MACH_PORT_NULL,
3104 EXCEPTION_STATE_IDENTITY,
3105 MACHINE_THREAD_STATE);
3107 assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
3108 #endif
3110 if (libjsig_is_loaded) {
3111 // Tell libjsig jvm finishes setting signal handlers
3112 (*end_signal_setting)();
3113 }
3115 // We don't activate signal checker if libjsig is in place, we trust ourselves
3116 // and if UserSignalHandler is installed all bets are off
3117 if (CheckJNICalls) {
3118 if (libjsig_is_loaded) {
3119 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
3120 check_signals = false;
3121 }
3122 if (AllowUserSignalHandlers) {
3123 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
3124 check_signals = false;
3125 }
3126 }
3127 }
3128 }
3131 /////
3132 // glibc on Bsd platform uses non-documented flag
3133 // to indicate, that some special sort of signal
3134 // trampoline is used.
3135 // We will never set this flag, and we should
3136 // ignore this flag in our diagnostic
3137 #ifdef SIGNIFICANT_SIGNAL_MASK
3138 #undef SIGNIFICANT_SIGNAL_MASK
3139 #endif
3140 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
3142 static const char* get_signal_handler_name(address handler,
3143 char* buf, int buflen) {
3144 int offset;
3145 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
3146 if (found) {
3147 // skip directory names
3148 const char *p1, *p2;
3149 p1 = buf;
3150 size_t len = strlen(os::file_separator());
3151 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
3152 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
3153 } else {
3154 jio_snprintf(buf, buflen, PTR_FORMAT, handler);
3155 }
3156 return buf;
3157 }
3159 static void print_signal_handler(outputStream* st, int sig,
3160 char* buf, size_t buflen) {
3161 struct sigaction sa;
3163 sigaction(sig, NULL, &sa);
3165 // See comment for SIGNIFICANT_SIGNAL_MASK define
3166 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3168 st->print("%s: ", os::exception_name(sig, buf, buflen));
3170 address handler = (sa.sa_flags & SA_SIGINFO)
3171 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
3172 : CAST_FROM_FN_PTR(address, sa.sa_handler);
3174 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
3175 st->print("SIG_DFL");
3176 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
3177 st->print("SIG_IGN");
3178 } else {
3179 st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
3180 }
3182 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
3184 address rh = VMError::get_resetted_sighandler(sig);
3185 // May be, handler was resetted by VMError?
3186 if(rh != NULL) {
3187 handler = rh;
3188 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
3189 }
3191 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags);
3193 // Check: is it our handler?
3194 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
3195 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
3196 // It is our signal handler
3197 // check for flags, reset system-used one!
3198 if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3199 st->print(
3200 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
3201 os::Bsd::get_our_sigflags(sig));
3202 }
3203 }
3204 st->cr();
3205 }
3208 #define DO_SIGNAL_CHECK(sig) \
3209 if (!sigismember(&check_signal_done, sig)) \
3210 os::Bsd::check_signal_handler(sig)
3212 // This method is a periodic task to check for misbehaving JNI applications
3213 // under CheckJNI, we can add any periodic checks here
3215 void os::run_periodic_checks() {
3217 if (check_signals == false) return;
3219 // SEGV and BUS if overridden could potentially prevent
3220 // generation of hs*.log in the event of a crash, debugging
3221 // such a case can be very challenging, so we absolutely
3222 // check the following for a good measure:
3223 DO_SIGNAL_CHECK(SIGSEGV);
3224 DO_SIGNAL_CHECK(SIGILL);
3225 DO_SIGNAL_CHECK(SIGFPE);
3226 DO_SIGNAL_CHECK(SIGBUS);
3227 DO_SIGNAL_CHECK(SIGPIPE);
3228 DO_SIGNAL_CHECK(SIGXFSZ);
3231 // ReduceSignalUsage allows the user to override these handlers
3232 // see comments at the very top and jvm_solaris.h
3233 if (!ReduceSignalUsage) {
3234 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3235 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3236 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3237 DO_SIGNAL_CHECK(BREAK_SIGNAL);
3238 }
3240 DO_SIGNAL_CHECK(SR_signum);
3241 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
3242 }
3244 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3246 static os_sigaction_t os_sigaction = NULL;
3248 void os::Bsd::check_signal_handler(int sig) {
3249 char buf[O_BUFLEN];
3250 address jvmHandler = NULL;
3253 struct sigaction act;
3254 if (os_sigaction == NULL) {
3255 // only trust the default sigaction, in case it has been interposed
3256 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3257 if (os_sigaction == NULL) return;
3258 }
3260 os_sigaction(sig, (struct sigaction*)NULL, &act);
3263 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3265 address thisHandler = (act.sa_flags & SA_SIGINFO)
3266 ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3267 : CAST_FROM_FN_PTR(address, act.sa_handler) ;
3270 switch(sig) {
3271 case SIGSEGV:
3272 case SIGBUS:
3273 case SIGFPE:
3274 case SIGPIPE:
3275 case SIGILL:
3276 case SIGXFSZ:
3277 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3278 break;
3280 case SHUTDOWN1_SIGNAL:
3281 case SHUTDOWN2_SIGNAL:
3282 case SHUTDOWN3_SIGNAL:
3283 case BREAK_SIGNAL:
3284 jvmHandler = (address)user_handler();
3285 break;
3287 case INTERRUPT_SIGNAL:
3288 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
3289 break;
3291 default:
3292 if (sig == SR_signum) {
3293 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3294 } else {
3295 return;
3296 }
3297 break;
3298 }
3300 if (thisHandler != jvmHandler) {
3301 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3302 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3303 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3304 // No need to check this sig any longer
3305 sigaddset(&check_signal_done, sig);
3306 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3307 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3308 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
3309 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);
3310 // No need to check this sig any longer
3311 sigaddset(&check_signal_done, sig);
3312 }
3314 // Dump all the signal
3315 if (sigismember(&check_signal_done, sig)) {
3316 print_signal_handlers(tty, buf, O_BUFLEN);
3317 }
3318 }
3320 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
3322 extern bool signal_name(int signo, char* buf, size_t len);
3324 const char* os::exception_name(int exception_code, char* buf, size_t size) {
3325 if (0 < exception_code && exception_code <= SIGRTMAX) {
3326 // signal
3327 if (!signal_name(exception_code, buf, size)) {
3328 jio_snprintf(buf, size, "SIG%d", exception_code);
3329 }
3330 return buf;
3331 } else {
3332 return NULL;
3333 }
3334 }
3336 // this is called _before_ the most of global arguments have been parsed
3337 void os::init(void) {
3338 char dummy; /* used to get a guess on initial stack address */
3339 // first_hrtime = gethrtime();
3341 // With BsdThreads the JavaMain thread pid (primordial thread)
3342 // is different than the pid of the java launcher thread.
3343 // So, on Bsd, the launcher thread pid is passed to the VM
3344 // via the sun.java.launcher.pid property.
3345 // Use this property instead of getpid() if it was correctly passed.
3346 // See bug 6351349.
3347 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
3349 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
3351 clock_tics_per_sec = CLK_TCK;
3353 init_random(1234567);
3355 ThreadCritical::initialize();
3357 Bsd::set_page_size(getpagesize());
3358 if (Bsd::page_size() == -1) {
3359 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
3360 strerror(errno)));
3361 }
3362 init_page_sizes((size_t) Bsd::page_size());
3364 Bsd::initialize_system_info();
3366 // main_thread points to the aboriginal thread
3367 Bsd::_main_thread = pthread_self();
3369 Bsd::clock_init();
3370 initial_time_count = os::elapsed_counter();
3372 #ifdef __APPLE__
3373 // XXXDARWIN
3374 // Work around the unaligned VM callbacks in hotspot's
3375 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
3376 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
3377 // alignment when doing symbol lookup. To work around this, we force early
3378 // binding of all symbols now, thus binding when alignment is known-good.
3379 _dyld_bind_fully_image_containing_address((const void *) &os::init);
3380 #endif
3381 }
3383 // To install functions for atexit system call
3384 extern "C" {
3385 static void perfMemory_exit_helper() {
3386 perfMemory_exit();
3387 }
3388 }
3390 // this is called _after_ the global arguments have been parsed
3391 jint os::init_2(void)
3392 {
3393 // Allocate a single page and mark it as readable for safepoint polling
3394 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3395 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
3397 os::set_polling_page( polling_page );
3399 #ifndef PRODUCT
3400 if(Verbose && PrintMiscellaneous)
3401 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
3402 #endif
3404 if (!UseMembar) {
3405 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3406 guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
3407 os::set_memory_serialize_page( mem_serialize_page );
3409 #ifndef PRODUCT
3410 if(Verbose && PrintMiscellaneous)
3411 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
3412 #endif
3413 }
3415 os::large_page_init();
3417 // initialize suspend/resume support - must do this before signal_sets_init()
3418 if (SR_initialize() != 0) {
3419 perror("SR_initialize failed");
3420 return JNI_ERR;
3421 }
3423 Bsd::signal_sets_init();
3424 Bsd::install_signal_handlers();
3426 // Check minimum allowable stack size for thread creation and to initialize
3427 // the java system classes, including StackOverflowError - depends on page
3428 // size. Add a page for compiler2 recursion in main thread.
3429 // Add in 2*BytesPerWord times page size to account for VM stack during
3430 // class initialization depending on 32 or 64 bit VM.
3431 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
3432 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
3433 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
3435 size_t threadStackSizeInBytes = ThreadStackSize * K;
3436 if (threadStackSizeInBytes != 0 &&
3437 threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
3438 tty->print_cr("\nThe stack size specified is too small, "
3439 "Specify at least %dk",
3440 os::Bsd::min_stack_allowed/ K);
3441 return JNI_ERR;
3442 }
3444 // Make the stack size a multiple of the page size so that
3445 // the yellow/red zones can be guarded.
3446 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
3447 vm_page_size()));
3449 if (MaxFDLimit) {
3450 // set the number of file descriptors to max. print out error
3451 // if getrlimit/setrlimit fails but continue regardless.
3452 struct rlimit nbr_files;
3453 int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3454 if (status != 0) {
3455 if (PrintMiscellaneous && (Verbose || WizardMode))
3456 perror("os::init_2 getrlimit failed");
3457 } else {
3458 nbr_files.rlim_cur = nbr_files.rlim_max;
3460 #ifdef __APPLE__
3461 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3462 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3463 // be used instead
3464 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3465 #endif
3467 status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3468 if (status != 0) {
3469 if (PrintMiscellaneous && (Verbose || WizardMode))
3470 perror("os::init_2 setrlimit failed");
3471 }
3472 }
3473 }
3475 // at-exit methods are called in the reverse order of their registration.
3476 // atexit functions are called on return from main or as a result of a
3477 // call to exit(3C). There can be only 32 of these functions registered
3478 // and atexit() does not set errno.
3480 if (PerfAllowAtExitRegistration) {
3481 // only register atexit functions if PerfAllowAtExitRegistration is set.
3482 // atexit functions can be delayed until process exit time, which
3483 // can be problematic for embedded VM situations. Embedded VMs should
3484 // call DestroyJavaVM() to assure that VM resources are released.
3486 // note: perfMemory_exit_helper atexit function may be removed in
3487 // the future if the appropriate cleanup code can be added to the
3488 // VM_Exit VMOperation's doit method.
3489 if (atexit(perfMemory_exit_helper) != 0) {
3490 warning("os::init2 atexit(perfMemory_exit_helper) failed");
3491 }
3492 }
3494 // initialize thread priority policy
3495 prio_init();
3497 #ifdef __APPLE__
3498 // dynamically link to objective c gc registration
3499 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3500 if (handleLibObjc != NULL) {
3501 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3502 }
3503 #endif
3505 return JNI_OK;
3506 }
3508 // this is called at the end of vm_initialization
3509 void os::init_3(void) { }
3511 // Mark the polling page as unreadable
3512 void os::make_polling_page_unreadable(void) {
3513 if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
3514 fatal("Could not disable polling page");
3515 };
3517 // Mark the polling page as readable
3518 void os::make_polling_page_readable(void) {
3519 if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
3520 fatal("Could not enable polling page");
3521 }
3522 };
3524 int os::active_processor_count() {
3525 return _processor_count;
3526 }
3528 void os::set_native_thread_name(const char *name) {
3529 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3530 // This is only supported in Snow Leopard and beyond
3531 if (name != NULL) {
3532 // Add a "Java: " prefix to the name
3533 char buf[MAXTHREADNAMESIZE];
3534 snprintf(buf, sizeof(buf), "Java: %s", name);
3535 pthread_setname_np(buf);
3536 }
3537 #endif
3538 }
3540 bool os::distribute_processes(uint length, uint* distribution) {
3541 // Not yet implemented.
3542 return false;
3543 }
3545 bool os::bind_to_processor(uint processor_id) {
3546 // Not yet implemented.
3547 return false;
3548 }
3550 ///
3552 // Suspends the target using the signal mechanism and then grabs the PC before
3553 // resuming the target. Used by the flat-profiler only
3554 ExtendedPC os::get_thread_pc(Thread* thread) {
3555 // Make sure that it is called by the watcher for the VMThread
3556 assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
3557 assert(thread->is_VM_thread(), "Can only be called for VMThread");
3559 ExtendedPC epc;
3561 OSThread* osthread = thread->osthread();
3562 if (do_suspend(osthread)) {
3563 if (osthread->ucontext() != NULL) {
3564 epc = os::Bsd::ucontext_get_pc(osthread->ucontext());
3565 } else {
3566 // NULL context is unexpected, double-check this is the VMThread
3567 guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3568 }
3569 do_resume(osthread);
3570 }
3571 // failure means pthread_kill failed for some reason - arguably this is
3572 // a fatal problem, but such problems are ignored elsewhere
3574 return epc;
3575 }
3577 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
3578 {
3579 return pthread_cond_timedwait(_cond, _mutex, _abstime);
3580 }
3582 ////////////////////////////////////////////////////////////////////////////////
3583 // debug support
3585 static address same_page(address x, address y) {
3586 int page_bits = -os::vm_page_size();
3587 if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
3588 return x;
3589 else if (x > y)
3590 return (address)(intptr_t(y) | ~page_bits) + 1;
3591 else
3592 return (address)(intptr_t(y) & page_bits);
3593 }
3595 bool os::find(address addr, outputStream* st) {
3596 Dl_info dlinfo;
3597 memset(&dlinfo, 0, sizeof(dlinfo));
3598 if (dladdr(addr, &dlinfo)) {
3599 st->print(PTR_FORMAT ": ", addr);
3600 if (dlinfo.dli_sname != NULL) {
3601 st->print("%s+%#x", dlinfo.dli_sname,
3602 addr - (intptr_t)dlinfo.dli_saddr);
3603 } else if (dlinfo.dli_fname) {
3604 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
3605 } else {
3606 st->print("<absolute address>");
3607 }
3608 if (dlinfo.dli_fname) {
3609 st->print(" in %s", dlinfo.dli_fname);
3610 }
3611 if (dlinfo.dli_fbase) {
3612 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
3613 }
3614 st->cr();
3616 if (Verbose) {
3617 // decode some bytes around the PC
3618 address begin = same_page(addr-40, addr);
3619 address end = same_page(addr+40, addr);
3620 address lowest = (address) dlinfo.dli_sname;
3621 if (!lowest) lowest = (address) dlinfo.dli_fbase;
3622 if (begin < lowest) begin = lowest;
3623 Dl_info dlinfo2;
3624 if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
3625 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
3626 end = (address) dlinfo2.dli_saddr;
3627 Disassembler::decode(begin, end, st);
3628 }
3629 return true;
3630 }
3631 return false;
3632 }
3634 ////////////////////////////////////////////////////////////////////////////////
3635 // misc
3637 // This does not do anything on Bsd. This is basically a hook for being
3638 // able to use structured exception handling (thread-local exception filters)
3639 // on, e.g., Win32.
3640 void
3641 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
3642 JavaCallArguments* args, Thread* thread) {
3643 f(value, method, args, thread);
3644 }
3646 void os::print_statistics() {
3647 }
3649 int os::message_box(const char* title, const char* message) {
3650 int i;
3651 fdStream err(defaultStream::error_fd());
3652 for (i = 0; i < 78; i++) err.print_raw("=");
3653 err.cr();
3654 err.print_raw_cr(title);
3655 for (i = 0; i < 78; i++) err.print_raw("-");
3656 err.cr();
3657 err.print_raw_cr(message);
3658 for (i = 0; i < 78; i++) err.print_raw("=");
3659 err.cr();
3661 char buf[16];
3662 // Prevent process from exiting upon "read error" without consuming all CPU
3663 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3665 return buf[0] == 'y' || buf[0] == 'Y';
3666 }
3668 int os::stat(const char *path, struct stat *sbuf) {
3669 char pathbuf[MAX_PATH];
3670 if (strlen(path) > MAX_PATH - 1) {
3671 errno = ENAMETOOLONG;
3672 return -1;
3673 }
3674 os::native_path(strcpy(pathbuf, path));
3675 return ::stat(pathbuf, sbuf);
3676 }
3678 bool os::check_heap(bool force) {
3679 return true;
3680 }
3682 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
3683 return ::vsnprintf(buf, count, format, args);
3684 }
3686 // Is a (classpath) directory empty?
3687 bool os::dir_is_empty(const char* path) {
3688 DIR *dir = NULL;
3689 struct dirent *ptr;
3691 dir = opendir(path);
3692 if (dir == NULL) return true;
3694 /* Scan the directory */
3695 bool result = true;
3696 char buf[sizeof(struct dirent) + MAX_PATH];
3697 while (result && (ptr = ::readdir(dir)) != NULL) {
3698 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3699 result = false;
3700 }
3701 }
3702 closedir(dir);
3703 return result;
3704 }
3706 // This code originates from JDK's sysOpen and open64_w
3707 // from src/solaris/hpi/src/system_md.c
3709 #ifndef O_DELETE
3710 #define O_DELETE 0x10000
3711 #endif
3713 // Open a file. Unlink the file immediately after open returns
3714 // if the specified oflag has the O_DELETE flag set.
3715 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
3717 int os::open(const char *path, int oflag, int mode) {
3719 if (strlen(path) > MAX_PATH - 1) {
3720 errno = ENAMETOOLONG;
3721 return -1;
3722 }
3723 int fd;
3724 int o_delete = (oflag & O_DELETE);
3725 oflag = oflag & ~O_DELETE;
3727 fd = ::open(path, oflag, mode);
3728 if (fd == -1) return -1;
3730 //If the open succeeded, the file might still be a directory
3731 {
3732 struct stat buf;
3733 int ret = ::fstat(fd, &buf);
3734 int st_mode = buf.st_mode;
3736 if (ret != -1) {
3737 if ((st_mode & S_IFMT) == S_IFDIR) {
3738 errno = EISDIR;
3739 ::close(fd);
3740 return -1;
3741 }
3742 } else {
3743 ::close(fd);
3744 return -1;
3745 }
3746 }
3748 /*
3749 * All file descriptors that are opened in the JVM and not
3750 * specifically destined for a subprocess should have the
3751 * close-on-exec flag set. If we don't set it, then careless 3rd
3752 * party native code might fork and exec without closing all
3753 * appropriate file descriptors (e.g. as we do in closeDescriptors in
3754 * UNIXProcess.c), and this in turn might:
3755 *
3756 * - cause end-of-file to fail to be detected on some file
3757 * descriptors, resulting in mysterious hangs, or
3758 *
3759 * - might cause an fopen in the subprocess to fail on a system
3760 * suffering from bug 1085341.
3761 *
3762 * (Yes, the default setting of the close-on-exec flag is a Unix
3763 * design flaw)
3764 *
3765 * See:
3766 * 1085341: 32-bit stdio routines should support file descriptors >255
3767 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3768 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3769 */
3770 #ifdef FD_CLOEXEC
3771 {
3772 int flags = ::fcntl(fd, F_GETFD);
3773 if (flags != -1)
3774 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3775 }
3776 #endif
3778 if (o_delete != 0) {
3779 ::unlink(path);
3780 }
3781 return fd;
3782 }
3785 // create binary file, rewriting existing file if required
3786 int os::create_binary_file(const char* path, bool rewrite_existing) {
3787 int oflags = O_WRONLY | O_CREAT;
3788 if (!rewrite_existing) {
3789 oflags |= O_EXCL;
3790 }
3791 return ::open(path, oflags, S_IREAD | S_IWRITE);
3792 }
3794 // return current position of file pointer
3795 jlong os::current_file_offset(int fd) {
3796 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
3797 }
3799 // move file pointer to the specified offset
3800 jlong os::seek_to_file_offset(int fd, jlong offset) {
3801 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
3802 }
3804 // This code originates from JDK's sysAvailable
3805 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
3807 int os::available(int fd, jlong *bytes) {
3808 jlong cur, end;
3809 int mode;
3810 struct stat buf;
3812 if (::fstat(fd, &buf) >= 0) {
3813 mode = buf.st_mode;
3814 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
3815 /*
3816 * XXX: is the following call interruptible? If so, this might
3817 * need to go through the INTERRUPT_IO() wrapper as for other
3818 * blocking, interruptible calls in this file.
3819 */
3820 int n;
3821 if (::ioctl(fd, FIONREAD, &n) >= 0) {
3822 *bytes = n;
3823 return 1;
3824 }
3825 }
3826 }
3827 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
3828 return 0;
3829 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
3830 return 0;
3831 } else if (::lseek(fd, cur, SEEK_SET) == -1) {
3832 return 0;
3833 }
3834 *bytes = end - cur;
3835 return 1;
3836 }
3838 int os::socket_available(int fd, jint *pbytes) {
3839 if (fd < 0)
3840 return OS_OK;
3842 int ret;
3844 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
3846 //%% note ioctl can return 0 when successful, JVM_SocketAvailable
3847 // is expected to return 0 on failure and 1 on success to the jdk.
3849 return (ret == OS_ERR) ? 0 : 1;
3850 }
3852 // Map a block of memory.
3853 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
3854 char *addr, size_t bytes, bool read_only,
3855 bool allow_exec) {
3856 int prot;
3857 int flags;
3859 if (read_only) {
3860 prot = PROT_READ;
3861 flags = MAP_SHARED;
3862 } else {
3863 prot = PROT_READ | PROT_WRITE;
3864 flags = MAP_PRIVATE;
3865 }
3867 if (allow_exec) {
3868 prot |= PROT_EXEC;
3869 }
3871 if (addr != NULL) {
3872 flags |= MAP_FIXED;
3873 }
3875 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
3876 fd, file_offset);
3877 if (mapped_address == MAP_FAILED) {
3878 return NULL;
3879 }
3880 return mapped_address;
3881 }
3884 // Remap a block of memory.
3885 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
3886 char *addr, size_t bytes, bool read_only,
3887 bool allow_exec) {
3888 // same as map_memory() on this OS
3889 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
3890 allow_exec);
3891 }
3894 // Unmap a block of memory.
3895 bool os::pd_unmap_memory(char* addr, size_t bytes) {
3896 return munmap(addr, bytes) == 0;
3897 }
3899 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
3900 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
3901 // of a thread.
3902 //
3903 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
3904 // the fast estimate available on the platform.
3906 jlong os::current_thread_cpu_time() {
3907 #ifdef __APPLE__
3908 return os::thread_cpu_time(Thread::current(), true /* user + sys */);
3909 #endif
3910 }
3912 jlong os::thread_cpu_time(Thread* thread) {
3913 }
3915 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
3916 #ifdef __APPLE__
3917 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
3918 #endif
3919 }
3921 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
3922 #ifdef __APPLE__
3923 struct thread_basic_info tinfo;
3924 mach_msg_type_number_t tcount = THREAD_INFO_MAX;
3925 kern_return_t kr;
3926 thread_t mach_thread;
3928 mach_thread = thread->osthread()->thread_id();
3929 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
3930 if (kr != KERN_SUCCESS)
3931 return -1;
3933 if (user_sys_cpu_time) {
3934 jlong nanos;
3935 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
3936 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
3937 return nanos;
3938 } else {
3939 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
3940 }
3941 #endif
3942 }
3945 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
3946 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
3947 info_ptr->may_skip_backward = false; // elapsed time not wall time
3948 info_ptr->may_skip_forward = false; // elapsed time not wall time
3949 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
3950 }
3952 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
3953 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
3954 info_ptr->may_skip_backward = false; // elapsed time not wall time
3955 info_ptr->may_skip_forward = false; // elapsed time not wall time
3956 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
3957 }
3959 bool os::is_thread_cpu_time_supported() {
3960 #ifdef __APPLE__
3961 return true;
3962 #else
3963 return false;
3964 #endif
3965 }
3967 // System loadavg support. Returns -1 if load average cannot be obtained.
3968 // Bsd doesn't yet have a (official) notion of processor sets,
3969 // so just return the system wide load average.
3970 int os::loadavg(double loadavg[], int nelem) {
3971 return ::getloadavg(loadavg, nelem);
3972 }
3974 void os::pause() {
3975 char filename[MAX_PATH];
3976 if (PauseAtStartupFile && PauseAtStartupFile[0]) {
3977 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
3978 } else {
3979 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
3980 }
3982 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3983 if (fd != -1) {
3984 struct stat buf;
3985 ::close(fd);
3986 while (::stat(filename, &buf) == 0) {
3987 (void)::poll(NULL, 0, 100);
3988 }
3989 } else {
3990 jio_fprintf(stderr,
3991 "Could not open pause file '%s', continuing immediately.\n", filename);
3992 }
3993 }
3996 // Refer to the comments in os_solaris.cpp park-unpark.
3997 //
3998 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
3999 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
4000 // For specifics regarding the bug see GLIBC BUGID 261237 :
4001 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
4002 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
4003 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
4004 // is used. (The simple C test-case provided in the GLIBC bug report manifests the
4005 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
4006 // and monitorenter when we're using 1-0 locking. All those operations may result in
4007 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
4008 // of libpthread avoids the problem, but isn't practical.
4009 //
4010 // Possible remedies:
4011 //
4012 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
4013 // This is palliative and probabilistic, however. If the thread is preempted
4014 // between the call to compute_abstime() and pthread_cond_timedwait(), more
4015 // than the minimum period may have passed, and the abstime may be stale (in the
4016 // past) resultin in a hang. Using this technique reduces the odds of a hang
4017 // but the JVM is still vulnerable, particularly on heavily loaded systems.
4018 //
4019 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
4020 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set
4021 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
4022 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant
4023 // thread.
4024 //
4025 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
4026 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
4027 // a timeout request to the chron thread and then blocking via pthread_cond_wait().
4028 // This also works well. In fact it avoids kernel-level scalability impediments
4029 // on certain platforms that don't handle lots of active pthread_cond_timedwait()
4030 // timers in a graceful fashion.
4031 //
4032 // 4. When the abstime value is in the past it appears that control returns
4033 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
4034 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we
4035 // can avoid the problem by reinitializing the condvar -- by cond_destroy()
4036 // followed by cond_init() -- after all calls to pthread_cond_timedwait().
4037 // It may be possible to avoid reinitialization by checking the return
4038 // value from pthread_cond_timedwait(). In addition to reinitializing the
4039 // condvar we must establish the invariant that cond_signal() is only called
4040 // within critical sections protected by the adjunct mutex. This prevents
4041 // cond_signal() from "seeing" a condvar that's in the midst of being
4042 // reinitialized or that is corrupt. Sadly, this invariant obviates the
4043 // desirable signal-after-unlock optimization that avoids futile context switching.
4044 //
4045 // I'm also concerned that some versions of NTPL might allocate an auxilliary
4046 // structure when a condvar is used or initialized. cond_destroy() would
4047 // release the helper structure. Our reinitialize-after-timedwait fix
4048 // put excessive stress on malloc/free and locks protecting the c-heap.
4049 //
4050 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
4051 // It may be possible to refine (4) by checking the kernel and NTPL verisons
4052 // and only enabling the work-around for vulnerable environments.
4054 // utility to compute the abstime argument to timedwait:
4055 // millis is the relative timeout time
4056 // abstime will be the absolute timeout time
4057 // TODO: replace compute_abstime() with unpackTime()
4059 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
4060 if (millis < 0) millis = 0;
4061 struct timeval now;
4062 int status = gettimeofday(&now, NULL);
4063 assert(status == 0, "gettimeofday");
4064 jlong seconds = millis / 1000;
4065 millis %= 1000;
4066 if (seconds > 50000000) { // see man cond_timedwait(3T)
4067 seconds = 50000000;
4068 }
4069 abstime->tv_sec = now.tv_sec + seconds;
4070 long usec = now.tv_usec + millis * 1000;
4071 if (usec >= 1000000) {
4072 abstime->tv_sec += 1;
4073 usec -= 1000000;
4074 }
4075 abstime->tv_nsec = usec * 1000;
4076 return abstime;
4077 }
4080 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
4081 // Conceptually TryPark() should be equivalent to park(0).
4083 int os::PlatformEvent::TryPark() {
4084 for (;;) {
4085 const int v = _Event ;
4086 guarantee ((v == 0) || (v == 1), "invariant") ;
4087 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;
4088 }
4089 }
4091 void os::PlatformEvent::park() { // AKA "down()"
4092 // Invariant: Only the thread associated with the Event/PlatformEvent
4093 // may call park().
4094 // TODO: assert that _Assoc != NULL or _Assoc == Self
4095 int v ;
4096 for (;;) {
4097 v = _Event ;
4098 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4099 }
4100 guarantee (v >= 0, "invariant") ;
4101 if (v == 0) {
4102 // Do this the hard way by blocking ...
4103 int status = pthread_mutex_lock(_mutex);
4104 assert_status(status == 0, status, "mutex_lock");
4105 guarantee (_nParked == 0, "invariant") ;
4106 ++ _nParked ;
4107 while (_Event < 0) {
4108 status = pthread_cond_wait(_cond, _mutex);
4109 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
4110 // Treat this the same as if the wait was interrupted
4111 if (status == ETIMEDOUT) { status = EINTR; }
4112 assert_status(status == 0 || status == EINTR, status, "cond_wait");
4113 }
4114 -- _nParked ;
4116 // In theory we could move the ST of 0 into _Event past the unlock(),
4117 // but then we'd need a MEMBAR after the ST.
4118 _Event = 0 ;
4119 status = pthread_mutex_unlock(_mutex);
4120 assert_status(status == 0, status, "mutex_unlock");
4121 }
4122 guarantee (_Event >= 0, "invariant") ;
4123 }
4125 int os::PlatformEvent::park(jlong millis) {
4126 guarantee (_nParked == 0, "invariant") ;
4128 int v ;
4129 for (;;) {
4130 v = _Event ;
4131 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4132 }
4133 guarantee (v >= 0, "invariant") ;
4134 if (v != 0) return OS_OK ;
4136 // We do this the hard way, by blocking the thread.
4137 // Consider enforcing a minimum timeout value.
4138 struct timespec abst;
4139 compute_abstime(&abst, millis);
4141 int ret = OS_TIMEOUT;
4142 int status = pthread_mutex_lock(_mutex);
4143 assert_status(status == 0, status, "mutex_lock");
4144 guarantee (_nParked == 0, "invariant") ;
4145 ++_nParked ;
4147 // Object.wait(timo) will return because of
4148 // (a) notification
4149 // (b) timeout
4150 // (c) thread.interrupt
4151 //
4152 // Thread.interrupt and object.notify{All} both call Event::set.
4153 // That is, we treat thread.interrupt as a special case of notification.
4154 // The underlying Solaris implementation, cond_timedwait, admits
4155 // spurious/premature wakeups, but the JLS/JVM spec prevents the
4156 // JVM from making those visible to Java code. As such, we must
4157 // filter out spurious wakeups. We assume all ETIME returns are valid.
4158 //
4159 // TODO: properly differentiate simultaneous notify+interrupt.
4160 // In that case, we should propagate the notify to another waiter.
4162 while (_Event < 0) {
4163 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
4164 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4165 pthread_cond_destroy (_cond);
4166 pthread_cond_init (_cond, NULL) ;
4167 }
4168 assert_status(status == 0 || status == EINTR ||
4169 status == ETIMEDOUT,
4170 status, "cond_timedwait");
4171 if (!FilterSpuriousWakeups) break ; // previous semantics
4172 if (status == ETIMEDOUT) break ;
4173 // We consume and ignore EINTR and spurious wakeups.
4174 }
4175 --_nParked ;
4176 if (_Event >= 0) {
4177 ret = OS_OK;
4178 }
4179 _Event = 0 ;
4180 status = pthread_mutex_unlock(_mutex);
4181 assert_status(status == 0, status, "mutex_unlock");
4182 assert (_nParked == 0, "invariant") ;
4183 return ret;
4184 }
4186 void os::PlatformEvent::unpark() {
4187 int v, AnyWaiters ;
4188 for (;;) {
4189 v = _Event ;
4190 if (v > 0) {
4191 // The LD of _Event could have reordered or be satisfied
4192 // by a read-aside from this processor's write buffer.
4193 // To avoid problems execute a barrier and then
4194 // ratify the value.
4195 OrderAccess::fence() ;
4196 if (_Event == v) return ;
4197 continue ;
4198 }
4199 if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
4200 }
4201 if (v < 0) {
4202 // Wait for the thread associated with the event to vacate
4203 int status = pthread_mutex_lock(_mutex);
4204 assert_status(status == 0, status, "mutex_lock");
4205 AnyWaiters = _nParked ;
4206 assert (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ;
4207 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
4208 AnyWaiters = 0 ;
4209 pthread_cond_signal (_cond);
4210 }
4211 status = pthread_mutex_unlock(_mutex);
4212 assert_status(status == 0, status, "mutex_unlock");
4213 if (AnyWaiters != 0) {
4214 status = pthread_cond_signal(_cond);
4215 assert_status(status == 0, status, "cond_signal");
4216 }
4217 }
4219 // Note that we signal() _after dropping the lock for "immortal" Events.
4220 // This is safe and avoids a common class of futile wakeups. In rare
4221 // circumstances this can cause a thread to return prematurely from
4222 // cond_{timed}wait() but the spurious wakeup is benign and the victim will
4223 // simply re-test the condition and re-park itself.
4224 }
4227 // JSR166
4228 // -------------------------------------------------------
4230 /*
4231 * The solaris and bsd implementations of park/unpark are fairly
4232 * conservative for now, but can be improved. They currently use a
4233 * mutex/condvar pair, plus a a count.
4234 * Park decrements count if > 0, else does a condvar wait. Unpark
4235 * sets count to 1 and signals condvar. Only one thread ever waits
4236 * on the condvar. Contention seen when trying to park implies that someone
4237 * is unparking you, so don't wait. And spurious returns are fine, so there
4238 * is no need to track notifications.
4239 */
4241 #define MAX_SECS 100000000
4242 /*
4243 * This code is common to bsd and solaris and will be moved to a
4244 * common place in dolphin.
4245 *
4246 * The passed in time value is either a relative time in nanoseconds
4247 * or an absolute time in milliseconds. Either way it has to be unpacked
4248 * into suitable seconds and nanoseconds components and stored in the
4249 * given timespec structure.
4250 * Given time is a 64-bit value and the time_t used in the timespec is only
4251 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
4252 * overflow if times way in the future are given. Further on Solaris versions
4253 * prior to 10 there is a restriction (see cond_timedwait) that the specified
4254 * number of seconds, in abstime, is less than current_time + 100,000,000.
4255 * As it will be 28 years before "now + 100000000" will overflow we can
4256 * ignore overflow and just impose a hard-limit on seconds using the value
4257 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
4258 * years from "now".
4259 */
4261 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
4262 assert (time > 0, "convertTime");
4264 struct timeval now;
4265 int status = gettimeofday(&now, NULL);
4266 assert(status == 0, "gettimeofday");
4268 time_t max_secs = now.tv_sec + MAX_SECS;
4270 if (isAbsolute) {
4271 jlong secs = time / 1000;
4272 if (secs > max_secs) {
4273 absTime->tv_sec = max_secs;
4274 }
4275 else {
4276 absTime->tv_sec = secs;
4277 }
4278 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
4279 }
4280 else {
4281 jlong secs = time / NANOSECS_PER_SEC;
4282 if (secs >= MAX_SECS) {
4283 absTime->tv_sec = max_secs;
4284 absTime->tv_nsec = 0;
4285 }
4286 else {
4287 absTime->tv_sec = now.tv_sec + secs;
4288 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
4289 if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
4290 absTime->tv_nsec -= NANOSECS_PER_SEC;
4291 ++absTime->tv_sec; // note: this must be <= max_secs
4292 }
4293 }
4294 }
4295 assert(absTime->tv_sec >= 0, "tv_sec < 0");
4296 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
4297 assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
4298 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
4299 }
4301 void Parker::park(bool isAbsolute, jlong time) {
4302 // Optional fast-path check:
4303 // Return immediately if a permit is available.
4304 if (_counter > 0) {
4305 _counter = 0 ;
4306 OrderAccess::fence();
4307 return ;
4308 }
4310 Thread* thread = Thread::current();
4311 assert(thread->is_Java_thread(), "Must be JavaThread");
4312 JavaThread *jt = (JavaThread *)thread;
4314 // Optional optimization -- avoid state transitions if there's an interrupt pending.
4315 // Check interrupt before trying to wait
4316 if (Thread::is_interrupted(thread, false)) {
4317 return;
4318 }
4320 // Next, demultiplex/decode time arguments
4321 struct timespec absTime;
4322 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
4323 return;
4324 }
4325 if (time > 0) {
4326 unpackTime(&absTime, isAbsolute, time);
4327 }
4330 // Enter safepoint region
4331 // Beware of deadlocks such as 6317397.
4332 // The per-thread Parker:: mutex is a classic leaf-lock.
4333 // In particular a thread must never block on the Threads_lock while
4334 // holding the Parker:: mutex. If safepoints are pending both the
4335 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
4336 ThreadBlockInVM tbivm(jt);
4338 // Don't wait if cannot get lock since interference arises from
4339 // unblocking. Also. check interrupt before trying wait
4340 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
4341 return;
4342 }
4344 int status ;
4345 if (_counter > 0) { // no wait needed
4346 _counter = 0;
4347 status = pthread_mutex_unlock(_mutex);
4348 assert (status == 0, "invariant") ;
4349 OrderAccess::fence();
4350 return;
4351 }
4353 #ifdef ASSERT
4354 // Don't catch signals while blocked; let the running threads have the signals.
4355 // (This allows a debugger to break into the running thread.)
4356 sigset_t oldsigs;
4357 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
4358 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
4359 #endif
4361 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
4362 jt->set_suspend_equivalent();
4363 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
4365 if (time == 0) {
4366 status = pthread_cond_wait (_cond, _mutex) ;
4367 } else {
4368 status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
4369 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4370 pthread_cond_destroy (_cond) ;
4371 pthread_cond_init (_cond, NULL);
4372 }
4373 }
4374 assert_status(status == 0 || status == EINTR ||
4375 status == ETIMEDOUT,
4376 status, "cond_timedwait");
4378 #ifdef ASSERT
4379 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
4380 #endif
4382 _counter = 0 ;
4383 status = pthread_mutex_unlock(_mutex) ;
4384 assert_status(status == 0, status, "invariant") ;
4385 // If externally suspended while waiting, re-suspend
4386 if (jt->handle_special_suspend_equivalent_condition()) {
4387 jt->java_suspend_self();
4388 }
4390 OrderAccess::fence();
4391 }
4393 void Parker::unpark() {
4394 int s, status ;
4395 status = pthread_mutex_lock(_mutex);
4396 assert (status == 0, "invariant") ;
4397 s = _counter;
4398 _counter = 1;
4399 if (s < 1) {
4400 if (WorkAroundNPTLTimedWaitHang) {
4401 status = pthread_cond_signal (_cond) ;
4402 assert (status == 0, "invariant") ;
4403 status = pthread_mutex_unlock(_mutex);
4404 assert (status == 0, "invariant") ;
4405 } else {
4406 status = pthread_mutex_unlock(_mutex);
4407 assert (status == 0, "invariant") ;
4408 status = pthread_cond_signal (_cond) ;
4409 assert (status == 0, "invariant") ;
4410 }
4411 } else {
4412 pthread_mutex_unlock(_mutex);
4413 assert (status == 0, "invariant") ;
4414 }
4415 }
4418 /* Darwin has no "environ" in a dynamic library. */
4419 #ifdef __APPLE__
4420 #include <crt_externs.h>
4421 #define environ (*_NSGetEnviron())
4422 #else
4423 extern char** environ;
4424 #endif
4426 // Run the specified command in a separate process. Return its exit value,
4427 // or -1 on failure (e.g. can't fork a new process).
4428 // Unlike system(), this function can be called from signal handler. It
4429 // doesn't block SIGINT et al.
4430 int os::fork_and_exec(char* cmd) {
4431 const char * argv[4] = {"sh", "-c", cmd, NULL};
4433 // fork() in BsdThreads/NPTL is not async-safe. It needs to run
4434 // pthread_atfork handlers and reset pthread library. All we need is a
4435 // separate process to execve. Make a direct syscall to fork process.
4436 // On IA64 there's no fork syscall, we have to use fork() and hope for
4437 // the best...
4438 pid_t pid = fork();
4440 if (pid < 0) {
4441 // fork failed
4442 return -1;
4444 } else if (pid == 0) {
4445 // child process
4447 // execve() in BsdThreads will call pthread_kill_other_threads_np()
4448 // first to kill every thread on the thread list. Because this list is
4449 // not reset by fork() (see notes above), execve() will instead kill
4450 // every thread in the parent process. We know this is the only thread
4451 // in the new process, so make a system call directly.
4452 // IA64 should use normal execve() from glibc to match the glibc fork()
4453 // above.
4454 execve("/bin/sh", (char* const*)argv, environ);
4456 // execve failed
4457 _exit(-1);
4459 } else {
4460 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
4461 // care about the actual exit code, for now.
4463 int status;
4465 // Wait for the child process to exit. This returns immediately if
4466 // the child has already exited. */
4467 while (waitpid(pid, &status, 0) < 0) {
4468 switch (errno) {
4469 case ECHILD: return 0;
4470 case EINTR: break;
4471 default: return -1;
4472 }
4473 }
4475 if (WIFEXITED(status)) {
4476 // The child exited normally; get its exit code.
4477 return WEXITSTATUS(status);
4478 } else if (WIFSIGNALED(status)) {
4479 // The child exited because of a signal
4480 // The best value to return is 0x80 + signal number,
4481 // because that is what all Unix shells do, and because
4482 // it allows callers to distinguish between process exit and
4483 // process death by signal.
4484 return 0x80 + WTERMSIG(status);
4485 } else {
4486 // Unknown exit code; pass it through
4487 return status;
4488 }
4489 }
4490 }
4492 // is_headless_jre()
4493 //
4494 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
4495 // in order to report if we are running in a headless jre
4496 //
4497 // Since JDK8 xawt/libmawt.so was moved into the same directory
4498 // as libawt.so, and renamed libawt_xawt.so
4499 //
4500 bool os::is_headless_jre() {
4501 struct stat statbuf;
4502 char buf[MAXPATHLEN];
4503 char libmawtpath[MAXPATHLEN];
4504 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX;
4505 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
4506 char *p;
4508 // Get path to libjvm.so
4509 os::jvm_path(buf, sizeof(buf));
4511 // Get rid of libjvm.so
4512 p = strrchr(buf, '/');
4513 if (p == NULL) return false;
4514 else *p = '\0';
4516 // Get rid of client or server
4517 p = strrchr(buf, '/');
4518 if (p == NULL) return false;
4519 else *p = '\0';
4521 // check xawt/libmawt.so
4522 strcpy(libmawtpath, buf);
4523 strcat(libmawtpath, xawtstr);
4524 if (::stat(libmawtpath, &statbuf) == 0) return false;
4526 // check libawt_xawt.so
4527 strcpy(libmawtpath, buf);
4528 strcat(libmawtpath, new_xawtstr);
4529 if (::stat(libmawtpath, &statbuf) == 0) return false;
4531 return true;
4532 }
4534 // Get the default path to the core file
4535 // Returns the length of the string
4536 int os::get_core_path(char* buffer, size_t bufferSize) {
4537 int n = jio_snprintf(buffer, bufferSize, "/cores");
4539 // Truncate if theoretical string was longer than bufferSize
4540 n = MIN2(n, (int)bufferSize);
4542 return n;
4543 }