Thu, 03 Oct 2013 12:39:58 +0400
8022616: u4 should not be used as a type for thread_id
Summary: Usage of u4 as a type for thread_id cause a compilation error on platform, where thread_id is a pointer
Reviewed-by: sla, sspitsyn, minqi
1 /*
2 * Copyright (c) 1999, 2013, 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 "compiler/disassembler.hpp"
33 #include "interpreter/interpreter.hpp"
34 #include "jvm_bsd.h"
35 #include "memory/allocation.inline.hpp"
36 #include "memory/filemap.hpp"
37 #include "mutex_bsd.inline.hpp"
38 #include "oops/oop.inline.hpp"
39 #include "os_share_bsd.hpp"
40 #include "prims/jniFastGetField.hpp"
41 #include "prims/jvm.h"
42 #include "prims/jvm_misc.hpp"
43 #include "runtime/arguments.hpp"
44 #include "runtime/extendedPC.hpp"
45 #include "runtime/globals.hpp"
46 #include "runtime/interfaceSupport.hpp"
47 #include "runtime/java.hpp"
48 #include "runtime/javaCalls.hpp"
49 #include "runtime/mutexLocker.hpp"
50 #include "runtime/objectMonitor.hpp"
51 #include "runtime/osThread.hpp"
52 #include "runtime/perfMemory.hpp"
53 #include "runtime/sharedRuntime.hpp"
54 #include "runtime/statSampler.hpp"
55 #include "runtime/stubRoutines.hpp"
56 #include "runtime/thread.inline.hpp"
57 #include "runtime/threadCritical.hpp"
58 #include "runtime/timer.hpp"
59 #include "services/attachListener.hpp"
60 #include "services/memTracker.hpp"
61 #include "services/runtimeService.hpp"
62 #include "utilities/decoder.hpp"
63 #include "utilities/defaultStream.hpp"
64 #include "utilities/events.hpp"
65 #include "utilities/growableArray.hpp"
66 #include "utilities/vmError.hpp"
68 // put OS-includes here
69 # include <sys/types.h>
70 # include <sys/mman.h>
71 # include <sys/stat.h>
72 # include <sys/select.h>
73 # include <pthread.h>
74 # include <signal.h>
75 # include <errno.h>
76 # include <dlfcn.h>
77 # include <stdio.h>
78 # include <unistd.h>
79 # include <sys/resource.h>
80 # include <pthread.h>
81 # include <sys/stat.h>
82 # include <sys/time.h>
83 # include <sys/times.h>
84 # include <sys/utsname.h>
85 # include <sys/socket.h>
86 # include <sys/wait.h>
87 # include <time.h>
88 # include <pwd.h>
89 # include <poll.h>
90 # include <semaphore.h>
91 # include <fcntl.h>
92 # include <string.h>
93 # include <sys/param.h>
94 # include <sys/sysctl.h>
95 # include <sys/ipc.h>
96 # include <sys/shm.h>
97 #ifndef __APPLE__
98 # include <link.h>
99 #endif
100 # include <stdint.h>
101 # include <inttypes.h>
102 # include <sys/ioctl.h>
103 # include <sys/syscall.h>
105 #if defined(__FreeBSD__) || defined(__NetBSD__)
106 # include <elf.h>
107 #endif
109 #ifdef __APPLE__
110 # include <mach/mach.h> // semaphore_* API
111 # include <mach-o/dyld.h>
112 # include <sys/proc_info.h>
113 # include <objc/objc-auto.h>
114 #endif
116 #ifndef MAP_ANONYMOUS
117 #define MAP_ANONYMOUS MAP_ANON
118 #endif
120 #define MAX_PATH (2 * K)
122 // for timer info max values which include all bits
123 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
125 #define LARGEPAGES_BIT (1 << 6)
126 ////////////////////////////////////////////////////////////////////////////////
127 // global variables
128 julong os::Bsd::_physical_memory = 0;
131 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
132 pthread_t os::Bsd::_main_thread;
133 int os::Bsd::_page_size = -1;
135 static jlong initial_time_count=0;
137 static int clock_tics_per_sec = 100;
139 // For diagnostics to print a message once. see run_periodic_checks
140 static sigset_t check_signal_done;
141 static bool check_signals = true;
143 static pid_t _initial_pid = 0;
145 /* Signal number used to suspend/resume a thread */
147 /* do not use any signal number less than SIGSEGV, see 4355769 */
148 static int SR_signum = SIGUSR2;
149 sigset_t SR_sigset;
152 ////////////////////////////////////////////////////////////////////////////////
153 // utility functions
155 static int SR_initialize();
156 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
158 julong os::available_memory() {
159 return Bsd::available_memory();
160 }
162 julong os::Bsd::available_memory() {
163 // XXXBSD: this is just a stopgap implementation
164 return physical_memory() >> 2;
165 }
167 julong os::physical_memory() {
168 return Bsd::physical_memory();
169 }
171 ////////////////////////////////////////////////////////////////////////////////
172 // environment support
174 bool os::getenv(const char* name, char* buf, int len) {
175 const char* val = ::getenv(name);
176 if (val != NULL && strlen(val) < (size_t)len) {
177 strcpy(buf, val);
178 return true;
179 }
180 if (len > 0) buf[0] = 0; // return a null string
181 return false;
182 }
185 // Return true if user is running as root.
187 bool os::have_special_privileges() {
188 static bool init = false;
189 static bool privileges = false;
190 if (!init) {
191 privileges = (getuid() != geteuid()) || (getgid() != getegid());
192 init = true;
193 }
194 return privileges;
195 }
199 // Cpu architecture string
200 #if defined(ZERO)
201 static char cpu_arch[] = ZERO_LIBARCH;
202 #elif defined(IA64)
203 static char cpu_arch[] = "ia64";
204 #elif defined(IA32)
205 static char cpu_arch[] = "i386";
206 #elif defined(AMD64)
207 static char cpu_arch[] = "amd64";
208 #elif defined(ARM)
209 static char cpu_arch[] = "arm";
210 #elif defined(PPC)
211 static char cpu_arch[] = "ppc";
212 #elif defined(SPARC)
213 # ifdef _LP64
214 static char cpu_arch[] = "sparcv9";
215 # else
216 static char cpu_arch[] = "sparc";
217 # endif
218 #else
219 #error Add appropriate cpu_arch setting
220 #endif
222 // Compiler variant
223 #ifdef COMPILER2
224 #define COMPILER_VARIANT "server"
225 #else
226 #define COMPILER_VARIANT "client"
227 #endif
230 void os::Bsd::initialize_system_info() {
231 int mib[2];
232 size_t len;
233 int cpu_val;
234 julong mem_val;
236 /* get processors count via hw.ncpus sysctl */
237 mib[0] = CTL_HW;
238 mib[1] = HW_NCPU;
239 len = sizeof(cpu_val);
240 if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
241 assert(len == sizeof(cpu_val), "unexpected data size");
242 set_processor_count(cpu_val);
243 }
244 else {
245 set_processor_count(1); // fallback
246 }
248 /* get physical memory via hw.memsize sysctl (hw.memsize is used
249 * since it returns a 64 bit value)
250 */
251 mib[0] = CTL_HW;
253 #if defined (HW_MEMSIZE) // Apple
254 mib[1] = HW_MEMSIZE;
255 #elif defined(HW_PHYSMEM) // Most of BSD
256 mib[1] = HW_PHYSMEM;
257 #elif defined(HW_REALMEM) // Old FreeBSD
258 mib[1] = HW_REALMEM;
259 #else
260 #error No ways to get physmem
261 #endif
263 len = sizeof(mem_val);
264 if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
265 assert(len == sizeof(mem_val), "unexpected data size");
266 _physical_memory = mem_val;
267 } else {
268 _physical_memory = 256*1024*1024; // fallback (XXXBSD?)
269 }
271 #ifdef __OpenBSD__
272 {
273 // limit _physical_memory memory view on OpenBSD since
274 // datasize rlimit restricts us anyway.
275 struct rlimit limits;
276 getrlimit(RLIMIT_DATA, &limits);
277 _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
278 }
279 #endif
280 }
282 #ifdef __APPLE__
283 static const char *get_home() {
284 const char *home_dir = ::getenv("HOME");
285 if ((home_dir == NULL) || (*home_dir == '\0')) {
286 struct passwd *passwd_info = getpwuid(geteuid());
287 if (passwd_info != NULL) {
288 home_dir = passwd_info->pw_dir;
289 }
290 }
292 return home_dir;
293 }
294 #endif
296 void os::init_system_properties_values() {
297 // char arch[12];
298 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
300 // The next steps are taken in the product version:
301 //
302 // Obtain the JAVA_HOME value from the location of libjvm.so.
303 // This library should be located at:
304 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
305 //
306 // If "/jre/lib/" appears at the right place in the path, then we
307 // assume libjvm.so is installed in a JDK and we use this path.
308 //
309 // Otherwise exit with message: "Could not create the Java virtual machine."
310 //
311 // The following extra steps are taken in the debugging version:
312 //
313 // If "/jre/lib/" does NOT appear at the right place in the path
314 // instead of exit check for $JAVA_HOME environment variable.
315 //
316 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
317 // then we append a fake suffix "hotspot/libjvm.so" to this path so
318 // it looks like libjvm.so is installed there
319 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
320 //
321 // Otherwise exit.
322 //
323 // Important note: if the location of libjvm.so changes this
324 // code needs to be changed accordingly.
326 // The next few definitions allow the code to be verbatim:
327 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
328 #define getenv(n) ::getenv(n)
330 /*
331 * See ld(1):
332 * The linker uses the following search paths to locate required
333 * shared libraries:
334 * 1: ...
335 * ...
336 * 7: The default directories, normally /lib and /usr/lib.
337 */
338 #ifndef DEFAULT_LIBPATH
339 #define DEFAULT_LIBPATH "/lib:/usr/lib"
340 #endif
342 #define EXTENSIONS_DIR "/lib/ext"
343 #define ENDORSED_DIR "/lib/endorsed"
344 #define REG_DIR "/usr/java/packages"
346 #ifdef __APPLE__
347 #define SYS_EXTENSIONS_DIR "/Library/Java/Extensions"
348 #define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
349 const char *user_home_dir = get_home();
350 // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
351 int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
352 sizeof(SYS_EXTENSIONS_DIRS);
353 #endif
355 {
356 /* sysclasspath, java_home, dll_dir */
357 {
358 char *home_path;
359 char *dll_path;
360 char *pslash;
361 char buf[MAXPATHLEN];
362 os::jvm_path(buf, sizeof(buf));
364 // Found the full path to libjvm.so.
365 // Now cut the path to <java_home>/jre if we can.
366 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */
367 pslash = strrchr(buf, '/');
368 if (pslash != NULL)
369 *pslash = '\0'; /* get rid of /{client|server|hotspot} */
370 dll_path = malloc(strlen(buf) + 1);
371 if (dll_path == NULL)
372 return;
373 strcpy(dll_path, buf);
374 Arguments::set_dll_dir(dll_path);
376 if (pslash != NULL) {
377 pslash = strrchr(buf, '/');
378 if (pslash != NULL) {
379 *pslash = '\0'; /* get rid of /<arch> (/lib on macosx) */
380 #ifndef __APPLE__
381 pslash = strrchr(buf, '/');
382 if (pslash != NULL)
383 *pslash = '\0'; /* get rid of /lib */
384 #endif
385 }
386 }
388 home_path = malloc(strlen(buf) + 1);
389 if (home_path == NULL)
390 return;
391 strcpy(home_path, buf);
392 Arguments::set_java_home(home_path);
394 if (!set_boot_path('/', ':'))
395 return;
396 }
398 /*
399 * Where to look for native libraries
400 *
401 * Note: Due to a legacy implementation, most of the library path
402 * is set in the launcher. This was to accomodate linking restrictions
403 * on legacy Bsd implementations (which are no longer supported).
404 * Eventually, all the library path setting will be done here.
405 *
406 * However, to prevent the proliferation of improperly built native
407 * libraries, the new path component /usr/java/packages is added here.
408 * Eventually, all the library path setting will be done here.
409 */
410 {
411 char *ld_library_path;
413 /*
414 * Construct the invariant part of ld_library_path. Note that the
415 * space for the colon and the trailing null are provided by the
416 * nulls included by the sizeof operator (so actually we allocate
417 * a byte more than necessary).
418 */
419 #ifdef __APPLE__
420 ld_library_path = (char *) malloc(system_ext_size);
421 sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir);
422 #else
423 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
424 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
425 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
426 #endif
428 /*
429 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It
430 * should always exist (until the legacy problem cited above is
431 * addressed).
432 */
433 #ifdef __APPLE__
434 // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
435 char *l = getenv("JAVA_LIBRARY_PATH");
436 if (l != NULL) {
437 char *t = ld_library_path;
438 /* That's +1 for the colon and +1 for the trailing '\0' */
439 ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1);
440 sprintf(ld_library_path, "%s:%s", l, t);
441 free(t);
442 }
444 char *v = getenv("DYLD_LIBRARY_PATH");
445 #else
446 char *v = getenv("LD_LIBRARY_PATH");
447 #endif
448 if (v != NULL) {
449 char *t = ld_library_path;
450 /* That's +1 for the colon and +1 for the trailing '\0' */
451 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
452 sprintf(ld_library_path, "%s:%s", v, t);
453 free(t);
454 }
456 #ifdef __APPLE__
457 // Apple's Java6 has "." at the beginning of java.library.path.
458 // OpenJDK on Windows has "." at the end of java.library.path.
459 // OpenJDK on Linux and Solaris don't have "." in java.library.path
460 // at all. To ease the transition from Apple's Java6 to OpenJDK7,
461 // "." is appended to the end of java.library.path. Yes, this
462 // could cause a change in behavior, but Apple's Java6 behavior
463 // can be achieved by putting "." at the beginning of the
464 // JAVA_LIBRARY_PATH environment variable.
465 {
466 char *t = ld_library_path;
467 // that's +3 for appending ":." and the trailing '\0'
468 ld_library_path = (char *) malloc(strlen(t) + 3);
469 sprintf(ld_library_path, "%s:%s", t, ".");
470 free(t);
471 }
472 #endif
474 Arguments::set_library_path(ld_library_path);
475 }
477 /*
478 * Extensions directories.
479 *
480 * Note that the space for the colon and the trailing null are provided
481 * by the nulls included by the sizeof operator (so actually one byte more
482 * than necessary is allocated).
483 */
484 {
485 #ifdef __APPLE__
486 char *buf = malloc(strlen(Arguments::get_java_home()) +
487 sizeof(EXTENSIONS_DIR) + system_ext_size);
488 sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":"
489 SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home());
490 #else
491 char *buf = malloc(strlen(Arguments::get_java_home()) +
492 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
493 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
494 Arguments::get_java_home());
495 #endif
497 Arguments::set_ext_dirs(buf);
498 }
500 /* Endorsed standards default directory. */
501 {
502 char * buf;
503 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
504 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
505 Arguments::set_endorsed_dirs(buf);
506 }
507 }
509 #ifdef __APPLE__
510 #undef SYS_EXTENSIONS_DIR
511 #endif
512 #undef malloc
513 #undef getenv
514 #undef EXTENSIONS_DIR
515 #undef ENDORSED_DIR
517 // Done
518 return;
519 }
521 ////////////////////////////////////////////////////////////////////////////////
522 // breakpoint support
524 void os::breakpoint() {
525 BREAKPOINT;
526 }
528 extern "C" void breakpoint() {
529 // use debugger to set breakpoint here
530 }
532 ////////////////////////////////////////////////////////////////////////////////
533 // signal support
535 debug_only(static bool signal_sets_initialized = false);
536 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
538 bool os::Bsd::is_sig_ignored(int sig) {
539 struct sigaction oact;
540 sigaction(sig, (struct sigaction*)NULL, &oact);
541 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)
542 : CAST_FROM_FN_PTR(void*, oact.sa_handler);
543 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
544 return true;
545 else
546 return false;
547 }
549 void os::Bsd::signal_sets_init() {
550 // Should also have an assertion stating we are still single-threaded.
551 assert(!signal_sets_initialized, "Already initialized");
552 // Fill in signals that are necessarily unblocked for all threads in
553 // the VM. Currently, we unblock the following signals:
554 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
555 // by -Xrs (=ReduceSignalUsage));
556 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
557 // other threads. The "ReduceSignalUsage" boolean tells us not to alter
558 // the dispositions or masks wrt these signals.
559 // Programs embedding the VM that want to use the above signals for their
560 // own purposes must, at this time, use the "-Xrs" option to prevent
561 // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
562 // (See bug 4345157, and other related bugs).
563 // In reality, though, unblocking these signals is really a nop, since
564 // these signals are not blocked by default.
565 sigemptyset(&unblocked_sigs);
566 sigemptyset(&allowdebug_blocked_sigs);
567 sigaddset(&unblocked_sigs, SIGILL);
568 sigaddset(&unblocked_sigs, SIGSEGV);
569 sigaddset(&unblocked_sigs, SIGBUS);
570 sigaddset(&unblocked_sigs, SIGFPE);
571 sigaddset(&unblocked_sigs, SR_signum);
573 if (!ReduceSignalUsage) {
574 if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
575 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
576 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
577 }
578 if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
579 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
580 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
581 }
582 if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
583 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
584 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
585 }
586 }
587 // Fill in signals that are blocked by all but the VM thread.
588 sigemptyset(&vm_sigs);
589 if (!ReduceSignalUsage)
590 sigaddset(&vm_sigs, BREAK_SIGNAL);
591 debug_only(signal_sets_initialized = true);
593 }
595 // These are signals that are unblocked while a thread is running Java.
596 // (For some reason, they get blocked by default.)
597 sigset_t* os::Bsd::unblocked_signals() {
598 assert(signal_sets_initialized, "Not initialized");
599 return &unblocked_sigs;
600 }
602 // These are the signals that are blocked while a (non-VM) thread is
603 // running Java. Only the VM thread handles these signals.
604 sigset_t* os::Bsd::vm_signals() {
605 assert(signal_sets_initialized, "Not initialized");
606 return &vm_sigs;
607 }
609 // These are signals that are blocked during cond_wait to allow debugger in
610 sigset_t* os::Bsd::allowdebug_blocked_signals() {
611 assert(signal_sets_initialized, "Not initialized");
612 return &allowdebug_blocked_sigs;
613 }
615 void os::Bsd::hotspot_sigmask(Thread* thread) {
617 //Save caller's signal mask before setting VM signal mask
618 sigset_t caller_sigmask;
619 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
621 OSThread* osthread = thread->osthread();
622 osthread->set_caller_sigmask(caller_sigmask);
624 pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
626 if (!ReduceSignalUsage) {
627 if (thread->is_VM_thread()) {
628 // Only the VM thread handles BREAK_SIGNAL ...
629 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
630 } else {
631 // ... all other threads block BREAK_SIGNAL
632 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
633 }
634 }
635 }
638 //////////////////////////////////////////////////////////////////////////////
639 // create new thread
641 // check if it's safe to start a new thread
642 static bool _thread_safety_check(Thread* thread) {
643 return true;
644 }
646 #ifdef __APPLE__
647 // library handle for calling objc_registerThreadWithCollector()
648 // without static linking to the libobjc library
649 #define OBJC_LIB "/usr/lib/libobjc.dylib"
650 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
651 typedef void (*objc_registerThreadWithCollector_t)();
652 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
653 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
654 #endif
656 #ifdef __APPLE__
657 static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {
658 // Additional thread_id used to correlate threads in SA
659 thread_identifier_info_data_t m_ident_info;
660 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
662 thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,
663 (thread_info_t) &m_ident_info, &count);
665 return m_ident_info.thread_id;
666 }
667 #endif
669 // Thread start routine for all newly created threads
670 static void *java_start(Thread *thread) {
671 // Try to randomize the cache line index of hot stack frames.
672 // This helps when threads of the same stack traces evict each other's
673 // cache lines. The threads can be either from the same JVM instance, or
674 // from different JVM instances. The benefit is especially true for
675 // processors with hyperthreading technology.
676 static int counter = 0;
677 int pid = os::current_process_id();
678 alloca(((pid ^ counter++) & 7) * 128);
680 ThreadLocalStorage::set_thread(thread);
682 OSThread* osthread = thread->osthread();
683 Monitor* sync = osthread->startThread_lock();
685 // non floating stack BsdThreads needs extra check, see above
686 if (!_thread_safety_check(thread)) {
687 // notify parent thread
688 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
689 osthread->set_state(ZOMBIE);
690 sync->notify_all();
691 return NULL;
692 }
694 osthread->set_thread_id(os::Bsd::gettid());
696 #ifdef __APPLE__
697 uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
698 guarantee(unique_thread_id != 0, "unique thread id was not found");
699 osthread->set_unique_thread_id(unique_thread_id);
700 #endif
701 // initialize signal mask for this thread
702 os::Bsd::hotspot_sigmask(thread);
704 // initialize floating point control register
705 os::Bsd::init_thread_fpu_state();
707 #ifdef __APPLE__
708 // register thread with objc gc
709 if (objc_registerThreadWithCollectorFunction != NULL) {
710 objc_registerThreadWithCollectorFunction();
711 }
712 #endif
714 // handshaking with parent thread
715 {
716 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
718 // notify parent thread
719 osthread->set_state(INITIALIZED);
720 sync->notify_all();
722 // wait until os::start_thread()
723 while (osthread->get_state() == INITIALIZED) {
724 sync->wait(Mutex::_no_safepoint_check_flag);
725 }
726 }
728 // call one more level start routine
729 thread->run();
731 return 0;
732 }
734 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
735 assert(thread->osthread() == NULL, "caller responsible");
737 // Allocate the OSThread object
738 OSThread* osthread = new OSThread(NULL, NULL);
739 if (osthread == NULL) {
740 return false;
741 }
743 // set the correct thread state
744 osthread->set_thread_type(thr_type);
746 // Initial state is ALLOCATED but not INITIALIZED
747 osthread->set_state(ALLOCATED);
749 thread->set_osthread(osthread);
751 // init thread attributes
752 pthread_attr_t attr;
753 pthread_attr_init(&attr);
754 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
756 // stack size
757 if (os::Bsd::supports_variable_stack_size()) {
758 // calculate stack size if it's not specified by caller
759 if (stack_size == 0) {
760 stack_size = os::Bsd::default_stack_size(thr_type);
762 switch (thr_type) {
763 case os::java_thread:
764 // Java threads use ThreadStackSize which default value can be
765 // changed with the flag -Xss
766 assert (JavaThread::stack_size_at_create() > 0, "this should be set");
767 stack_size = JavaThread::stack_size_at_create();
768 break;
769 case os::compiler_thread:
770 if (CompilerThreadStackSize > 0) {
771 stack_size = (size_t)(CompilerThreadStackSize * K);
772 break;
773 } // else fall through:
774 // use VMThreadStackSize if CompilerThreadStackSize is not defined
775 case os::vm_thread:
776 case os::pgc_thread:
777 case os::cgc_thread:
778 case os::watcher_thread:
779 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
780 break;
781 }
782 }
784 stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
785 pthread_attr_setstacksize(&attr, stack_size);
786 } else {
787 // let pthread_create() pick the default value.
788 }
790 ThreadState state;
792 {
793 pthread_t tid;
794 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
796 pthread_attr_destroy(&attr);
798 if (ret != 0) {
799 if (PrintMiscellaneous && (Verbose || WizardMode)) {
800 perror("pthread_create()");
801 }
802 // Need to clean up stuff we've allocated so far
803 thread->set_osthread(NULL);
804 delete osthread;
805 return false;
806 }
808 // Store pthread info into the OSThread
809 osthread->set_pthread_id(tid);
811 // Wait until child thread is either initialized or aborted
812 {
813 Monitor* sync_with_child = osthread->startThread_lock();
814 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
815 while ((state = osthread->get_state()) == ALLOCATED) {
816 sync_with_child->wait(Mutex::_no_safepoint_check_flag);
817 }
818 }
820 }
822 // Aborted due to thread limit being reached
823 if (state == ZOMBIE) {
824 thread->set_osthread(NULL);
825 delete osthread;
826 return false;
827 }
829 // The thread is returned suspended (in state INITIALIZED),
830 // and is started higher up in the call chain
831 assert(state == INITIALIZED, "race condition");
832 return true;
833 }
835 /////////////////////////////////////////////////////////////////////////////
836 // attach existing thread
838 // bootstrap the main thread
839 bool os::create_main_thread(JavaThread* thread) {
840 assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
841 return create_attached_thread(thread);
842 }
844 bool os::create_attached_thread(JavaThread* thread) {
845 #ifdef ASSERT
846 thread->verify_not_published();
847 #endif
849 // Allocate the OSThread object
850 OSThread* osthread = new OSThread(NULL, NULL);
852 if (osthread == NULL) {
853 return false;
854 }
856 osthread->set_thread_id(os::Bsd::gettid());
858 // Store pthread info into the OSThread
859 #ifdef __APPLE__
860 uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
861 guarantee(unique_thread_id != 0, "just checking");
862 osthread->set_unique_thread_id(unique_thread_id);
863 #endif
864 osthread->set_pthread_id(::pthread_self());
866 // initialize floating point control register
867 os::Bsd::init_thread_fpu_state();
869 // Initial thread state is RUNNABLE
870 osthread->set_state(RUNNABLE);
872 thread->set_osthread(osthread);
874 // initialize signal mask for this thread
875 // and save the caller's signal mask
876 os::Bsd::hotspot_sigmask(thread);
878 return true;
879 }
881 void os::pd_start_thread(Thread* thread) {
882 OSThread * osthread = thread->osthread();
883 assert(osthread->get_state() != INITIALIZED, "just checking");
884 Monitor* sync_with_child = osthread->startThread_lock();
885 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
886 sync_with_child->notify();
887 }
889 // Free Bsd resources related to the OSThread
890 void os::free_thread(OSThread* osthread) {
891 assert(osthread != NULL, "osthread not set");
893 if (Thread::current()->osthread() == osthread) {
894 // Restore caller's signal mask
895 sigset_t sigmask = osthread->caller_sigmask();
896 pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
897 }
899 delete osthread;
900 }
902 //////////////////////////////////////////////////////////////////////////////
903 // thread local storage
905 int os::allocate_thread_local_storage() {
906 pthread_key_t key;
907 int rslt = pthread_key_create(&key, NULL);
908 assert(rslt == 0, "cannot allocate thread local storage");
909 return (int)key;
910 }
912 // Note: This is currently not used by VM, as we don't destroy TLS key
913 // on VM exit.
914 void os::free_thread_local_storage(int index) {
915 int rslt = pthread_key_delete((pthread_key_t)index);
916 assert(rslt == 0, "invalid index");
917 }
919 void os::thread_local_storage_at_put(int index, void* value) {
920 int rslt = pthread_setspecific((pthread_key_t)index, value);
921 assert(rslt == 0, "pthread_setspecific failed");
922 }
924 extern "C" Thread* get_thread() {
925 return ThreadLocalStorage::thread();
926 }
929 ////////////////////////////////////////////////////////////////////////////////
930 // time support
932 // Time since start-up in seconds to a fine granularity.
933 // Used by VMSelfDestructTimer and the MemProfiler.
934 double os::elapsedTime() {
936 return (double)(os::elapsed_counter()) * 0.000001;
937 }
939 jlong os::elapsed_counter() {
940 timeval time;
941 int status = gettimeofday(&time, NULL);
942 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
943 }
945 jlong os::elapsed_frequency() {
946 return (1000 * 1000);
947 }
949 bool os::supports_vtime() { return true; }
950 bool os::enable_vtime() { return false; }
951 bool os::vtime_enabled() { return false; }
953 double os::elapsedVTime() {
954 // better than nothing, but not much
955 return elapsedTime();
956 }
958 jlong os::javaTimeMillis() {
959 timeval time;
960 int status = gettimeofday(&time, NULL);
961 assert(status != -1, "bsd error");
962 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
963 }
965 #ifndef CLOCK_MONOTONIC
966 #define CLOCK_MONOTONIC (1)
967 #endif
969 #ifdef __APPLE__
970 void os::Bsd::clock_init() {
971 // XXXDARWIN: Investigate replacement monotonic clock
972 }
973 #else
974 void os::Bsd::clock_init() {
975 struct timespec res;
976 struct timespec tp;
977 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
978 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
979 // yes, monotonic clock is supported
980 _clock_gettime = ::clock_gettime;
981 }
982 }
983 #endif
986 jlong os::javaTimeNanos() {
987 if (Bsd::supports_monotonic_clock()) {
988 struct timespec tp;
989 int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
990 assert(status == 0, "gettime error");
991 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
992 return result;
993 } else {
994 timeval time;
995 int status = gettimeofday(&time, NULL);
996 assert(status != -1, "bsd error");
997 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
998 return 1000 * usecs;
999 }
1000 }
1002 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1003 if (Bsd::supports_monotonic_clock()) {
1004 info_ptr->max_value = ALL_64_BITS;
1006 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1007 info_ptr->may_skip_backward = false; // not subject to resetting or drifting
1008 info_ptr->may_skip_forward = false; // not subject to resetting or drifting
1009 } else {
1010 // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1011 info_ptr->max_value = ALL_64_BITS;
1013 // gettimeofday is a real time clock so it skips
1014 info_ptr->may_skip_backward = true;
1015 info_ptr->may_skip_forward = true;
1016 }
1018 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
1019 }
1021 // Return the real, user, and system times in seconds from an
1022 // arbitrary fixed point in the past.
1023 bool os::getTimesSecs(double* process_real_time,
1024 double* process_user_time,
1025 double* process_system_time) {
1026 struct tms ticks;
1027 clock_t real_ticks = times(&ticks);
1029 if (real_ticks == (clock_t) (-1)) {
1030 return false;
1031 } else {
1032 double ticks_per_second = (double) clock_tics_per_sec;
1033 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1034 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1035 *process_real_time = ((double) real_ticks) / ticks_per_second;
1037 return true;
1038 }
1039 }
1042 char * os::local_time_string(char *buf, size_t buflen) {
1043 struct tm t;
1044 time_t long_time;
1045 time(&long_time);
1046 localtime_r(&long_time, &t);
1047 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1048 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1049 t.tm_hour, t.tm_min, t.tm_sec);
1050 return buf;
1051 }
1053 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
1054 return localtime_r(clock, res);
1055 }
1057 ////////////////////////////////////////////////////////////////////////////////
1058 // runtime exit support
1060 // Note: os::shutdown() might be called very early during initialization, or
1061 // called from signal handler. Before adding something to os::shutdown(), make
1062 // sure it is async-safe and can handle partially initialized VM.
1063 void os::shutdown() {
1065 // allow PerfMemory to attempt cleanup of any persistent resources
1066 perfMemory_exit();
1068 // needs to remove object in file system
1069 AttachListener::abort();
1071 // flush buffered output, finish log files
1072 ostream_abort();
1074 // Check for abort hook
1075 abort_hook_t abort_hook = Arguments::abort_hook();
1076 if (abort_hook != NULL) {
1077 abort_hook();
1078 }
1080 }
1082 // Note: os::abort() might be called very early during initialization, or
1083 // called from signal handler. Before adding something to os::abort(), make
1084 // sure it is async-safe and can handle partially initialized VM.
1085 void os::abort(bool dump_core) {
1086 os::shutdown();
1087 if (dump_core) {
1088 #ifndef PRODUCT
1089 fdStream out(defaultStream::output_fd());
1090 out.print_raw("Current thread is ");
1091 char buf[16];
1092 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1093 out.print_raw_cr(buf);
1094 out.print_raw_cr("Dumping core ...");
1095 #endif
1096 ::abort(); // dump core
1097 }
1099 ::exit(1);
1100 }
1102 // Die immediately, no exit hook, no abort hook, no cleanup.
1103 void os::die() {
1104 // _exit() on BsdThreads only kills current thread
1105 ::abort();
1106 }
1108 // unused on bsd for now.
1109 void os::set_error_file(const char *logfile) {}
1112 // This method is a copy of JDK's sysGetLastErrorString
1113 // from src/solaris/hpi/src/system_md.c
1115 size_t os::lasterror(char *buf, size_t len) {
1117 if (errno == 0) return 0;
1119 const char *s = ::strerror(errno);
1120 size_t n = ::strlen(s);
1121 if (n >= len) {
1122 n = len - 1;
1123 }
1124 ::strncpy(buf, s, n);
1125 buf[n] = '\0';
1126 return n;
1127 }
1129 // Information of current thread in variety of formats
1130 pid_t os::Bsd::gettid() {
1131 int retval = -1;
1133 #ifdef __APPLE__ //XNU kernel
1134 // despite the fact mach port is actually not a thread id use it
1135 // instead of syscall(SYS_thread_selfid) as it certainly fits to u4
1136 retval = ::pthread_mach_thread_np(::pthread_self());
1137 guarantee(retval != 0, "just checking");
1138 return retval;
1140 #elif __FreeBSD__
1141 retval = syscall(SYS_thr_self);
1142 #elif __OpenBSD__
1143 retval = syscall(SYS_getthrid);
1144 #elif __NetBSD__
1145 retval = (pid_t) syscall(SYS__lwp_self);
1146 #endif
1148 if (retval == -1) {
1149 return getpid();
1150 }
1151 }
1153 intx os::current_thread_id() {
1154 #ifdef __APPLE__
1155 return (intx)::pthread_mach_thread_np(::pthread_self());
1156 #else
1157 return (intx)::pthread_self();
1158 #endif
1159 }
1161 int os::current_process_id() {
1163 // Under the old bsd thread library, bsd gives each thread
1164 // its own process id. Because of this each thread will return
1165 // a different pid if this method were to return the result
1166 // of getpid(2). Bsd provides no api that returns the pid
1167 // of the launcher thread for the vm. This implementation
1168 // returns a unique pid, the pid of the launcher thread
1169 // that starts the vm 'process'.
1171 // Under the NPTL, getpid() returns the same pid as the
1172 // launcher thread rather than a unique pid per thread.
1173 // Use gettid() if you want the old pre NPTL behaviour.
1175 // if you are looking for the result of a call to getpid() that
1176 // returns a unique pid for the calling thread, then look at the
1177 // OSThread::thread_id() method in osThread_bsd.hpp file
1179 return (int)(_initial_pid ? _initial_pid : getpid());
1180 }
1182 // DLL functions
1184 #define JNI_LIB_PREFIX "lib"
1185 #ifdef __APPLE__
1186 #define JNI_LIB_SUFFIX ".dylib"
1187 #else
1188 #define JNI_LIB_SUFFIX ".so"
1189 #endif
1191 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1193 // This must be hard coded because it's the system's temporary
1194 // directory not the java application's temp directory, ala java.io.tmpdir.
1195 #ifdef __APPLE__
1196 // macosx has a secure per-user temporary directory
1197 char temp_path_storage[PATH_MAX];
1198 const char* os::get_temp_directory() {
1199 static char *temp_path = NULL;
1200 if (temp_path == NULL) {
1201 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1202 if (pathSize == 0 || pathSize > PATH_MAX) {
1203 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1204 }
1205 temp_path = temp_path_storage;
1206 }
1207 return temp_path;
1208 }
1209 #else /* __APPLE__ */
1210 const char* os::get_temp_directory() { return "/tmp"; }
1211 #endif /* __APPLE__ */
1213 static bool file_exists(const char* filename) {
1214 struct stat statbuf;
1215 if (filename == NULL || strlen(filename) == 0) {
1216 return false;
1217 }
1218 return os::stat(filename, &statbuf) == 0;
1219 }
1221 bool os::dll_build_name(char* buffer, size_t buflen,
1222 const char* pname, const char* fname) {
1223 bool retval = false;
1224 // Copied from libhpi
1225 const size_t pnamelen = pname ? strlen(pname) : 0;
1227 // Return error on buffer overflow.
1228 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
1229 return retval;
1230 }
1232 if (pnamelen == 0) {
1233 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
1234 retval = true;
1235 } else if (strchr(pname, *os::path_separator()) != NULL) {
1236 int n;
1237 char** pelements = split_path(pname, &n);
1238 if (pelements == NULL) {
1239 return false;
1240 }
1241 for (int i = 0 ; i < n ; i++) {
1242 // Really shouldn't be NULL, but check can't hurt
1243 if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1244 continue; // skip the empty path values
1245 }
1246 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
1247 pelements[i], fname);
1248 if (file_exists(buffer)) {
1249 retval = true;
1250 break;
1251 }
1252 }
1253 // release the storage
1254 for (int i = 0 ; i < n ; i++) {
1255 if (pelements[i] != NULL) {
1256 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1257 }
1258 }
1259 if (pelements != NULL) {
1260 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1261 }
1262 } else {
1263 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
1264 retval = true;
1265 }
1266 return retval;
1267 }
1269 // check if addr is inside libjvm.so
1270 bool os::address_is_in_vm(address addr) {
1271 static address libjvm_base_addr;
1272 Dl_info dlinfo;
1274 if (libjvm_base_addr == NULL) {
1275 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1276 libjvm_base_addr = (address)dlinfo.dli_fbase;
1277 }
1278 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1279 }
1281 if (dladdr((void *)addr, &dlinfo) != 0) {
1282 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1283 }
1285 return false;
1286 }
1289 #define MACH_MAXSYMLEN 256
1291 bool os::dll_address_to_function_name(address addr, char *buf,
1292 int buflen, int *offset) {
1293 // buf is not optional, but offset is optional
1294 assert(buf != NULL, "sanity check");
1296 Dl_info dlinfo;
1297 char localbuf[MACH_MAXSYMLEN];
1299 if (dladdr((void*)addr, &dlinfo) != 0) {
1300 // see if we have a matching symbol
1301 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1302 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1303 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1304 }
1305 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1306 return true;
1307 }
1308 // no matching symbol so try for just file info
1309 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1310 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1311 buf, buflen, offset, dlinfo.dli_fname)) {
1312 return true;
1313 }
1314 }
1316 // Handle non-dynamic manually:
1317 if (dlinfo.dli_fbase != NULL &&
1318 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
1319 dlinfo.dli_fbase)) {
1320 if (!Decoder::demangle(localbuf, buf, buflen)) {
1321 jio_snprintf(buf, buflen, "%s", localbuf);
1322 }
1323 return true;
1324 }
1325 }
1326 buf[0] = '\0';
1327 if (offset != NULL) *offset = -1;
1328 return false;
1329 }
1331 // ported from solaris version
1332 bool os::dll_address_to_library_name(address addr, char* buf,
1333 int buflen, int* offset) {
1334 // buf is not optional, but offset is optional
1335 assert(buf != NULL, "sanity check");
1337 Dl_info dlinfo;
1339 if (dladdr((void*)addr, &dlinfo) != 0) {
1340 if (dlinfo.dli_fname != NULL) {
1341 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1342 }
1343 if (dlinfo.dli_fbase != NULL && offset != NULL) {
1344 *offset = addr - (address)dlinfo.dli_fbase;
1345 }
1346 return true;
1347 }
1349 buf[0] = '\0';
1350 if (offset) *offset = -1;
1351 return false;
1352 }
1354 // Loads .dll/.so and
1355 // in case of error it checks if .dll/.so was built for the
1356 // same architecture as Hotspot is running on
1358 #ifdef __APPLE__
1359 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1360 void * result= ::dlopen(filename, RTLD_LAZY);
1361 if (result != NULL) {
1362 // Successful loading
1363 return result;
1364 }
1366 // Read system error message into ebuf
1367 ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1368 ebuf[ebuflen-1]='\0';
1370 return NULL;
1371 }
1372 #else
1373 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1374 {
1375 void * result= ::dlopen(filename, RTLD_LAZY);
1376 if (result != NULL) {
1377 // Successful loading
1378 return result;
1379 }
1381 Elf32_Ehdr elf_head;
1383 // Read system error message into ebuf
1384 // It may or may not be overwritten below
1385 ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1386 ebuf[ebuflen-1]='\0';
1387 int diag_msg_max_length=ebuflen-strlen(ebuf);
1388 char* diag_msg_buf=ebuf+strlen(ebuf);
1390 if (diag_msg_max_length==0) {
1391 // No more space in ebuf for additional diagnostics message
1392 return NULL;
1393 }
1396 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1398 if (file_descriptor < 0) {
1399 // Can't open library, report dlerror() message
1400 return NULL;
1401 }
1403 bool failed_to_read_elf_head=
1404 (sizeof(elf_head)!=
1405 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1407 ::close(file_descriptor);
1408 if (failed_to_read_elf_head) {
1409 // file i/o error - report dlerror() msg
1410 return NULL;
1411 }
1413 typedef struct {
1414 Elf32_Half code; // Actual value as defined in elf.h
1415 Elf32_Half compat_class; // Compatibility of archs at VM's sense
1416 char elf_class; // 32 or 64 bit
1417 char endianess; // MSB or LSB
1418 char* name; // String representation
1419 } arch_t;
1421 #ifndef EM_486
1422 #define EM_486 6 /* Intel 80486 */
1423 #endif
1425 #ifndef EM_MIPS_RS3_LE
1426 #define EM_MIPS_RS3_LE 10 /* MIPS */
1427 #endif
1429 #ifndef EM_PPC64
1430 #define EM_PPC64 21 /* PowerPC64 */
1431 #endif
1433 #ifndef EM_S390
1434 #define EM_S390 22 /* IBM System/390 */
1435 #endif
1437 #ifndef EM_IA_64
1438 #define EM_IA_64 50 /* HP/Intel IA-64 */
1439 #endif
1441 #ifndef EM_X86_64
1442 #define EM_X86_64 62 /* AMD x86-64 */
1443 #endif
1445 static const arch_t arch_array[]={
1446 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1447 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1448 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1449 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1450 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1451 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1452 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1453 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1454 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1455 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1456 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1457 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1458 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1459 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1460 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1461 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1462 };
1464 #if (defined IA32)
1465 static Elf32_Half running_arch_code=EM_386;
1466 #elif (defined AMD64)
1467 static Elf32_Half running_arch_code=EM_X86_64;
1468 #elif (defined IA64)
1469 static Elf32_Half running_arch_code=EM_IA_64;
1470 #elif (defined __sparc) && (defined _LP64)
1471 static Elf32_Half running_arch_code=EM_SPARCV9;
1472 #elif (defined __sparc) && (!defined _LP64)
1473 static Elf32_Half running_arch_code=EM_SPARC;
1474 #elif (defined __powerpc64__)
1475 static Elf32_Half running_arch_code=EM_PPC64;
1476 #elif (defined __powerpc__)
1477 static Elf32_Half running_arch_code=EM_PPC;
1478 #elif (defined ARM)
1479 static Elf32_Half running_arch_code=EM_ARM;
1480 #elif (defined S390)
1481 static Elf32_Half running_arch_code=EM_S390;
1482 #elif (defined ALPHA)
1483 static Elf32_Half running_arch_code=EM_ALPHA;
1484 #elif (defined MIPSEL)
1485 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1486 #elif (defined PARISC)
1487 static Elf32_Half running_arch_code=EM_PARISC;
1488 #elif (defined MIPS)
1489 static Elf32_Half running_arch_code=EM_MIPS;
1490 #elif (defined M68K)
1491 static Elf32_Half running_arch_code=EM_68K;
1492 #else
1493 #error Method os::dll_load requires that one of following is defined:\
1494 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1495 #endif
1497 // Identify compatability class for VM's architecture and library's architecture
1498 // Obtain string descriptions for architectures
1500 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1501 int running_arch_index=-1;
1503 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
1504 if (running_arch_code == arch_array[i].code) {
1505 running_arch_index = i;
1506 }
1507 if (lib_arch.code == arch_array[i].code) {
1508 lib_arch.compat_class = arch_array[i].compat_class;
1509 lib_arch.name = arch_array[i].name;
1510 }
1511 }
1513 assert(running_arch_index != -1,
1514 "Didn't find running architecture code (running_arch_code) in arch_array");
1515 if (running_arch_index == -1) {
1516 // Even though running architecture detection failed
1517 // we may still continue with reporting dlerror() message
1518 return NULL;
1519 }
1521 if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1522 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1523 return NULL;
1524 }
1526 #ifndef S390
1527 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1528 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1529 return NULL;
1530 }
1531 #endif // !S390
1533 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1534 if ( lib_arch.name!=NULL ) {
1535 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1536 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1537 lib_arch.name, arch_array[running_arch_index].name);
1538 } else {
1539 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1540 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1541 lib_arch.code,
1542 arch_array[running_arch_index].name);
1543 }
1544 }
1546 return NULL;
1547 }
1548 #endif /* !__APPLE__ */
1550 // XXX: Do we need a lock around this as per Linux?
1551 void* os::dll_lookup(void* handle, const char* name) {
1552 return dlsym(handle, name);
1553 }
1556 static bool _print_ascii_file(const char* filename, outputStream* st) {
1557 int fd = ::open(filename, O_RDONLY);
1558 if (fd == -1) {
1559 return false;
1560 }
1562 char buf[32];
1563 int bytes;
1564 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1565 st->print_raw(buf, bytes);
1566 }
1568 ::close(fd);
1570 return true;
1571 }
1573 void os::print_dll_info(outputStream *st) {
1574 st->print_cr("Dynamic libraries:");
1575 #ifdef RTLD_DI_LINKMAP
1576 Dl_info dli;
1577 void *handle;
1578 Link_map *map;
1579 Link_map *p;
1581 if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
1582 dli.dli_fname == NULL) {
1583 st->print_cr("Error: Cannot print dynamic libraries.");
1584 return;
1585 }
1586 handle = dlopen(dli.dli_fname, RTLD_LAZY);
1587 if (handle == NULL) {
1588 st->print_cr("Error: Cannot print dynamic libraries.");
1589 return;
1590 }
1591 dlinfo(handle, RTLD_DI_LINKMAP, &map);
1592 if (map == NULL) {
1593 st->print_cr("Error: Cannot print dynamic libraries.");
1594 return;
1595 }
1597 while (map->l_prev != NULL)
1598 map = map->l_prev;
1600 while (map != NULL) {
1601 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
1602 map = map->l_next;
1603 }
1605 dlclose(handle);
1606 #elif defined(__APPLE__)
1607 uint32_t count;
1608 uint32_t i;
1610 count = _dyld_image_count();
1611 for (i = 1; i < count; i++) {
1612 const char *name = _dyld_get_image_name(i);
1613 intptr_t slide = _dyld_get_image_vmaddr_slide(i);
1614 st->print_cr(PTR_FORMAT " \t%s", slide, name);
1615 }
1616 #else
1617 st->print_cr("Error: Cannot print dynamic libraries.");
1618 #endif
1619 }
1621 void os::print_os_info_brief(outputStream* st) {
1622 st->print("Bsd");
1624 os::Posix::print_uname_info(st);
1625 }
1627 void os::print_os_info(outputStream* st) {
1628 st->print("OS:");
1629 st->print("Bsd");
1631 os::Posix::print_uname_info(st);
1633 os::Posix::print_rlimit_info(st);
1635 os::Posix::print_load_average(st);
1636 }
1638 void os::pd_print_cpu_info(outputStream* st) {
1639 // Nothing to do for now.
1640 }
1642 void os::print_memory_info(outputStream* st) {
1644 st->print("Memory:");
1645 st->print(" %dk page", os::vm_page_size()>>10);
1647 st->print(", physical " UINT64_FORMAT "k",
1648 os::physical_memory() >> 10);
1649 st->print("(" UINT64_FORMAT "k free)",
1650 os::available_memory() >> 10);
1651 st->cr();
1653 // meminfo
1654 st->print("\n/proc/meminfo:\n");
1655 _print_ascii_file("/proc/meminfo", st);
1656 st->cr();
1657 }
1659 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific
1660 // but they're the same for all the bsd arch that we support
1661 // and they're the same for solaris but there's no common place to put this.
1662 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
1663 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
1664 "ILL_COPROC", "ILL_BADSTK" };
1666 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
1667 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
1668 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
1670 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
1672 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
1674 void os::print_siginfo(outputStream* st, void* siginfo) {
1675 st->print("siginfo:");
1677 const int buflen = 100;
1678 char buf[buflen];
1679 siginfo_t *si = (siginfo_t*)siginfo;
1680 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
1681 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
1682 st->print("si_errno=%s", buf);
1683 } else {
1684 st->print("si_errno=%d", si->si_errno);
1685 }
1686 const int c = si->si_code;
1687 assert(c > 0, "unexpected si_code");
1688 switch (si->si_signo) {
1689 case SIGILL:
1690 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
1691 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1692 break;
1693 case SIGFPE:
1694 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
1695 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1696 break;
1697 case SIGSEGV:
1698 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
1699 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1700 break;
1701 case SIGBUS:
1702 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
1703 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1704 break;
1705 default:
1706 st->print(", si_code=%d", si->si_code);
1707 // no si_addr
1708 }
1710 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
1711 UseSharedSpaces) {
1712 FileMapInfo* mapinfo = FileMapInfo::current_info();
1713 if (mapinfo->is_in_shared_space(si->si_addr)) {
1714 st->print("\n\nError accessing class data sharing archive." \
1715 " Mapped file inaccessible during execution, " \
1716 " possible disk/network problem.");
1717 }
1718 }
1719 st->cr();
1720 }
1723 static void print_signal_handler(outputStream* st, int sig,
1724 char* buf, size_t buflen);
1726 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1727 st->print_cr("Signal Handlers:");
1728 print_signal_handler(st, SIGSEGV, buf, buflen);
1729 print_signal_handler(st, SIGBUS , buf, buflen);
1730 print_signal_handler(st, SIGFPE , buf, buflen);
1731 print_signal_handler(st, SIGPIPE, buf, buflen);
1732 print_signal_handler(st, SIGXFSZ, buf, buflen);
1733 print_signal_handler(st, SIGILL , buf, buflen);
1734 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
1735 print_signal_handler(st, SR_signum, buf, buflen);
1736 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1737 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1738 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1739 print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1740 }
1742 static char saved_jvm_path[MAXPATHLEN] = {0};
1744 // Find the full path to the current module, libjvm
1745 void os::jvm_path(char *buf, jint buflen) {
1746 // Error checking.
1747 if (buflen < MAXPATHLEN) {
1748 assert(false, "must use a large-enough buffer");
1749 buf[0] = '\0';
1750 return;
1751 }
1752 // Lazy resolve the path to current module.
1753 if (saved_jvm_path[0] != 0) {
1754 strcpy(buf, saved_jvm_path);
1755 return;
1756 }
1758 char dli_fname[MAXPATHLEN];
1759 bool ret = dll_address_to_library_name(
1760 CAST_FROM_FN_PTR(address, os::jvm_path),
1761 dli_fname, sizeof(dli_fname), NULL);
1762 assert(ret, "cannot locate libjvm");
1763 char *rp = NULL;
1764 if (ret && dli_fname[0] != '\0') {
1765 rp = realpath(dli_fname, buf);
1766 }
1767 if (rp == NULL)
1768 return;
1770 if (Arguments::created_by_gamma_launcher()) {
1771 // Support for the gamma launcher. Typical value for buf is
1772 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at
1773 // the right place in the string, then assume we are installed in a JDK and
1774 // we're done. Otherwise, check for a JAVA_HOME environment variable and
1775 // construct a path to the JVM being overridden.
1777 const char *p = buf + strlen(buf) - 1;
1778 for (int count = 0; p > buf && count < 5; ++count) {
1779 for (--p; p > buf && *p != '/'; --p)
1780 /* empty */ ;
1781 }
1783 if (strncmp(p, "/jre/lib/", 9) != 0) {
1784 // Look for JAVA_HOME in the environment.
1785 char* java_home_var = ::getenv("JAVA_HOME");
1786 if (java_home_var != NULL && java_home_var[0] != 0) {
1787 char* jrelib_p;
1788 int len;
1790 // Check the current module name "libjvm"
1791 p = strrchr(buf, '/');
1792 assert(strstr(p, "/libjvm") == p, "invalid library name");
1794 rp = realpath(java_home_var, buf);
1795 if (rp == NULL)
1796 return;
1798 // determine if this is a legacy image or modules image
1799 // modules image doesn't have "jre" subdirectory
1800 len = strlen(buf);
1801 jrelib_p = buf + len;
1803 // Add the appropriate library subdir
1804 snprintf(jrelib_p, buflen-len, "/jre/lib");
1805 if (0 != access(buf, F_OK)) {
1806 snprintf(jrelib_p, buflen-len, "/lib");
1807 }
1809 // Add the appropriate client or server subdir
1810 len = strlen(buf);
1811 jrelib_p = buf + len;
1812 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1813 if (0 != access(buf, F_OK)) {
1814 snprintf(jrelib_p, buflen-len, "");
1815 }
1817 // If the path exists within JAVA_HOME, add the JVM library name
1818 // to complete the path to JVM being overridden. Otherwise fallback
1819 // to the path to the current library.
1820 if (0 == access(buf, F_OK)) {
1821 // Use current module name "libjvm"
1822 len = strlen(buf);
1823 snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1824 } else {
1825 // Fall back to path of current library
1826 rp = realpath(dli_fname, buf);
1827 if (rp == NULL)
1828 return;
1829 }
1830 }
1831 }
1832 }
1834 strcpy(saved_jvm_path, buf);
1835 }
1837 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1838 // no prefix required, not even "_"
1839 }
1841 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1842 // no suffix required
1843 }
1845 ////////////////////////////////////////////////////////////////////////////////
1846 // sun.misc.Signal support
1848 static volatile jint sigint_count = 0;
1850 static void
1851 UserHandler(int sig, void *siginfo, void *context) {
1852 // 4511530 - sem_post is serialized and handled by the manager thread. When
1853 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
1854 // don't want to flood the manager thread with sem_post requests.
1855 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
1856 return;
1858 // Ctrl-C is pressed during error reporting, likely because the error
1859 // handler fails to abort. Let VM die immediately.
1860 if (sig == SIGINT && is_error_reported()) {
1861 os::die();
1862 }
1864 os::signal_notify(sig);
1865 }
1867 void* os::user_handler() {
1868 return CAST_FROM_FN_PTR(void*, UserHandler);
1869 }
1871 extern "C" {
1872 typedef void (*sa_handler_t)(int);
1873 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1874 }
1876 void* os::signal(int signal_number, void* handler) {
1877 struct sigaction sigAct, oldSigAct;
1879 sigfillset(&(sigAct.sa_mask));
1880 sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
1881 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1883 if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1884 // -1 means registration failed
1885 return (void *)-1;
1886 }
1888 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1889 }
1891 void os::signal_raise(int signal_number) {
1892 ::raise(signal_number);
1893 }
1895 /*
1896 * The following code is moved from os.cpp for making this
1897 * code platform specific, which it is by its very nature.
1898 */
1900 // Will be modified when max signal is changed to be dynamic
1901 int os::sigexitnum_pd() {
1902 return NSIG;
1903 }
1905 // a counter for each possible signal value
1906 static volatile jint pending_signals[NSIG+1] = { 0 };
1908 // Bsd(POSIX) specific hand shaking semaphore.
1909 #ifdef __APPLE__
1910 typedef semaphore_t os_semaphore_t;
1911 #define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
1912 #define SEM_WAIT(sem) semaphore_wait(sem)
1913 #define SEM_POST(sem) semaphore_signal(sem)
1914 #define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem)
1915 #else
1916 typedef sem_t os_semaphore_t;
1917 #define SEM_INIT(sem, value) sem_init(&sem, 0, value)
1918 #define SEM_WAIT(sem) sem_wait(&sem)
1919 #define SEM_POST(sem) sem_post(&sem)
1920 #define SEM_DESTROY(sem) sem_destroy(&sem)
1921 #endif
1923 class Semaphore : public StackObj {
1924 public:
1925 Semaphore();
1926 ~Semaphore();
1927 void signal();
1928 void wait();
1929 bool trywait();
1930 bool timedwait(unsigned int sec, int nsec);
1931 private:
1932 jlong currenttime() const;
1933 os_semaphore_t _semaphore;
1934 };
1936 Semaphore::Semaphore() : _semaphore(0) {
1937 SEM_INIT(_semaphore, 0);
1938 }
1940 Semaphore::~Semaphore() {
1941 SEM_DESTROY(_semaphore);
1942 }
1944 void Semaphore::signal() {
1945 SEM_POST(_semaphore);
1946 }
1948 void Semaphore::wait() {
1949 SEM_WAIT(_semaphore);
1950 }
1952 jlong Semaphore::currenttime() const {
1953 struct timeval tv;
1954 gettimeofday(&tv, NULL);
1955 return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
1956 }
1958 #ifdef __APPLE__
1959 bool Semaphore::trywait() {
1960 return timedwait(0, 0);
1961 }
1963 bool Semaphore::timedwait(unsigned int sec, int nsec) {
1964 kern_return_t kr = KERN_ABORTED;
1965 mach_timespec_t waitspec;
1966 waitspec.tv_sec = sec;
1967 waitspec.tv_nsec = nsec;
1969 jlong starttime = currenttime();
1971 kr = semaphore_timedwait(_semaphore, waitspec);
1972 while (kr == KERN_ABORTED) {
1973 jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
1975 jlong current = currenttime();
1976 jlong passedtime = current - starttime;
1978 if (passedtime >= totalwait) {
1979 waitspec.tv_sec = 0;
1980 waitspec.tv_nsec = 0;
1981 } else {
1982 jlong waittime = totalwait - (current - starttime);
1983 waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
1984 waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
1985 }
1987 kr = semaphore_timedwait(_semaphore, waitspec);
1988 }
1990 return kr == KERN_SUCCESS;
1991 }
1993 #else
1995 bool Semaphore::trywait() {
1996 return sem_trywait(&_semaphore) == 0;
1997 }
1999 bool Semaphore::timedwait(unsigned int sec, int nsec) {
2000 struct timespec ts;
2001 unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2003 while (1) {
2004 int result = sem_timedwait(&_semaphore, &ts);
2005 if (result == 0) {
2006 return true;
2007 } else if (errno == EINTR) {
2008 continue;
2009 } else if (errno == ETIMEDOUT) {
2010 return false;
2011 } else {
2012 return false;
2013 }
2014 }
2015 }
2017 #endif // __APPLE__
2019 static os_semaphore_t sig_sem;
2020 static Semaphore sr_semaphore;
2022 void os::signal_init_pd() {
2023 // Initialize signal structures
2024 ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2026 // Initialize signal semaphore
2027 ::SEM_INIT(sig_sem, 0);
2028 }
2030 void os::signal_notify(int sig) {
2031 Atomic::inc(&pending_signals[sig]);
2032 ::SEM_POST(sig_sem);
2033 }
2035 static int check_pending_signals(bool wait) {
2036 Atomic::store(0, &sigint_count);
2037 for (;;) {
2038 for (int i = 0; i < NSIG + 1; i++) {
2039 jint n = pending_signals[i];
2040 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2041 return i;
2042 }
2043 }
2044 if (!wait) {
2045 return -1;
2046 }
2047 JavaThread *thread = JavaThread::current();
2048 ThreadBlockInVM tbivm(thread);
2050 bool threadIsSuspended;
2051 do {
2052 thread->set_suspend_equivalent();
2053 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2054 ::SEM_WAIT(sig_sem);
2056 // were we externally suspended while we were waiting?
2057 threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2058 if (threadIsSuspended) {
2059 //
2060 // The semaphore has been incremented, but while we were waiting
2061 // another thread suspended us. We don't want to continue running
2062 // while suspended because that would surprise the thread that
2063 // suspended us.
2064 //
2065 ::SEM_POST(sig_sem);
2067 thread->java_suspend_self();
2068 }
2069 } while (threadIsSuspended);
2070 }
2071 }
2073 int os::signal_lookup() {
2074 return check_pending_signals(false);
2075 }
2077 int os::signal_wait() {
2078 return check_pending_signals(true);
2079 }
2081 ////////////////////////////////////////////////////////////////////////////////
2082 // Virtual Memory
2084 int os::vm_page_size() {
2085 // Seems redundant as all get out
2086 assert(os::Bsd::page_size() != -1, "must call os::init");
2087 return os::Bsd::page_size();
2088 }
2090 // Solaris allocates memory by pages.
2091 int os::vm_allocation_granularity() {
2092 assert(os::Bsd::page_size() != -1, "must call os::init");
2093 return os::Bsd::page_size();
2094 }
2096 // Rationale behind this function:
2097 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2098 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2099 // samples for JITted code. Here we create private executable mapping over the code cache
2100 // and then we can use standard (well, almost, as mapping can change) way to provide
2101 // info for the reporting script by storing timestamp and location of symbol
2102 void bsd_wrap_code(char* base, size_t size) {
2103 static volatile jint cnt = 0;
2105 if (!UseOprofile) {
2106 return;
2107 }
2109 char buf[PATH_MAX + 1];
2110 int num = Atomic::add(1, &cnt);
2112 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
2113 os::get_temp_directory(), os::current_process_id(), num);
2114 unlink(buf);
2116 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2118 if (fd != -1) {
2119 off_t rv = ::lseek(fd, size-2, SEEK_SET);
2120 if (rv != (off_t)-1) {
2121 if (::write(fd, "", 1) == 1) {
2122 mmap(base, size,
2123 PROT_READ|PROT_WRITE|PROT_EXEC,
2124 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2125 }
2126 }
2127 ::close(fd);
2128 unlink(buf);
2129 }
2130 }
2132 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2133 int err) {
2134 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2135 ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
2136 strerror(err), err);
2137 }
2139 // NOTE: Bsd kernel does not really reserve the pages for us.
2140 // All it does is to check if there are enough free pages
2141 // left at the time of mmap(). This could be a potential
2142 // problem.
2143 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2144 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2145 #ifdef __OpenBSD__
2146 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2147 if (::mprotect(addr, size, prot) == 0) {
2148 return true;
2149 }
2150 #else
2151 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2152 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2153 if (res != (uintptr_t) MAP_FAILED) {
2154 return true;
2155 }
2156 #endif
2158 // Warn about any commit errors we see in non-product builds just
2159 // in case mmap() doesn't work as described on the man page.
2160 NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
2162 return false;
2163 }
2165 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2166 bool exec) {
2167 // alignment_hint is ignored on this OS
2168 return pd_commit_memory(addr, size, exec);
2169 }
2171 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2172 const char* mesg) {
2173 assert(mesg != NULL, "mesg must be specified");
2174 if (!pd_commit_memory(addr, size, exec)) {
2175 // add extra info in product mode for vm_exit_out_of_memory():
2176 PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
2177 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2178 }
2179 }
2181 void os::pd_commit_memory_or_exit(char* addr, size_t size,
2182 size_t alignment_hint, bool exec,
2183 const char* mesg) {
2184 // alignment_hint is ignored on this OS
2185 pd_commit_memory_or_exit(addr, size, exec, mesg);
2186 }
2188 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2189 }
2191 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2192 ::madvise(addr, bytes, MADV_DONTNEED);
2193 }
2195 void os::numa_make_global(char *addr, size_t bytes) {
2196 }
2198 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2199 }
2201 bool os::numa_topology_changed() { return false; }
2203 size_t os::numa_get_groups_num() {
2204 return 1;
2205 }
2207 int os::numa_get_group_id() {
2208 return 0;
2209 }
2211 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2212 if (size > 0) {
2213 ids[0] = 0;
2214 return 1;
2215 }
2216 return 0;
2217 }
2219 bool os::get_page_info(char *start, page_info* info) {
2220 return false;
2221 }
2223 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2224 return end;
2225 }
2228 bool os::pd_uncommit_memory(char* addr, size_t size) {
2229 #ifdef __OpenBSD__
2230 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2231 return ::mprotect(addr, size, PROT_NONE) == 0;
2232 #else
2233 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2234 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2235 return res != (uintptr_t) MAP_FAILED;
2236 #endif
2237 }
2239 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2240 return os::commit_memory(addr, size, !ExecMem);
2241 }
2243 // If this is a growable mapping, remove the guard pages entirely by
2244 // munmap()ping them. If not, just call uncommit_memory().
2245 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2246 return os::uncommit_memory(addr, size);
2247 }
2249 static address _highest_vm_reserved_address = NULL;
2251 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2252 // at 'requested_addr'. If there are existing memory mappings at the same
2253 // location, however, they will be overwritten. If 'fixed' is false,
2254 // 'requested_addr' is only treated as a hint, the return value may or
2255 // may not start from the requested address. Unlike Bsd mmap(), this
2256 // function returns NULL to indicate failure.
2257 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2258 char * addr;
2259 int flags;
2261 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2262 if (fixed) {
2263 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2264 flags |= MAP_FIXED;
2265 }
2267 // Map reserved/uncommitted pages PROT_NONE so we fail early if we
2268 // touch an uncommitted page. Otherwise, the read/write might
2269 // succeed if we have enough swap space to back the physical page.
2270 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
2271 flags, -1, 0);
2273 if (addr != MAP_FAILED) {
2274 // anon_mmap() should only get called during VM initialization,
2275 // don't need lock (actually we can skip locking even it can be called
2276 // from multiple threads, because _highest_vm_reserved_address is just a
2277 // hint about the upper limit of non-stack memory regions.)
2278 if ((address)addr + bytes > _highest_vm_reserved_address) {
2279 _highest_vm_reserved_address = (address)addr + bytes;
2280 }
2281 }
2283 return addr == MAP_FAILED ? NULL : addr;
2284 }
2286 // Don't update _highest_vm_reserved_address, because there might be memory
2287 // regions above addr + size. If so, releasing a memory region only creates
2288 // a hole in the address space, it doesn't help prevent heap-stack collision.
2289 //
2290 static int anon_munmap(char * addr, size_t size) {
2291 return ::munmap(addr, size) == 0;
2292 }
2294 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2295 size_t alignment_hint) {
2296 return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2297 }
2299 bool os::pd_release_memory(char* addr, size_t size) {
2300 return anon_munmap(addr, size);
2301 }
2303 static bool bsd_mprotect(char* addr, size_t size, int prot) {
2304 // Bsd wants the mprotect address argument to be page aligned.
2305 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
2307 // According to SUSv3, mprotect() should only be used with mappings
2308 // established by mmap(), and mmap() always maps whole pages. Unaligned
2309 // 'addr' likely indicates problem in the VM (e.g. trying to change
2310 // protection of malloc'ed or statically allocated memory). Check the
2311 // caller if you hit this assert.
2312 assert(addr == bottom, "sanity check");
2314 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2315 return ::mprotect(bottom, size, prot) == 0;
2316 }
2318 // Set protections specified
2319 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2320 bool is_committed) {
2321 unsigned int p = 0;
2322 switch (prot) {
2323 case MEM_PROT_NONE: p = PROT_NONE; break;
2324 case MEM_PROT_READ: p = PROT_READ; break;
2325 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
2326 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2327 default:
2328 ShouldNotReachHere();
2329 }
2330 // is_committed is unused.
2331 return bsd_mprotect(addr, bytes, p);
2332 }
2334 bool os::guard_memory(char* addr, size_t size) {
2335 return bsd_mprotect(addr, size, PROT_NONE);
2336 }
2338 bool os::unguard_memory(char* addr, size_t size) {
2339 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2340 }
2342 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2343 return false;
2344 }
2346 // Large page support
2348 static size_t _large_page_size = 0;
2350 void os::large_page_init() {
2351 }
2354 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
2355 fatal("This code is not used or maintained.");
2357 // "exec" is passed in but not used. Creating the shared image for
2358 // the code cache doesn't have an SHM_X executable permission to check.
2359 assert(UseLargePages && UseSHM, "only for SHM large pages");
2361 key_t key = IPC_PRIVATE;
2362 char *addr;
2364 bool warn_on_failure = UseLargePages &&
2365 (!FLAG_IS_DEFAULT(UseLargePages) ||
2366 !FLAG_IS_DEFAULT(LargePageSizeInBytes)
2367 );
2368 char msg[128];
2370 // Create a large shared memory region to attach to based on size.
2371 // Currently, size is the total size of the heap
2372 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
2373 if (shmid == -1) {
2374 // Possible reasons for shmget failure:
2375 // 1. shmmax is too small for Java heap.
2376 // > check shmmax value: cat /proc/sys/kernel/shmmax
2377 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
2378 // 2. not enough large page memory.
2379 // > check available large pages: cat /proc/meminfo
2380 // > increase amount of large pages:
2381 // echo new_value > /proc/sys/vm/nr_hugepages
2382 // Note 1: different Bsd may use different name for this property,
2383 // e.g. on Redhat AS-3 it is "hugetlb_pool".
2384 // Note 2: it's possible there's enough physical memory available but
2385 // they are so fragmented after a long run that they can't
2386 // coalesce into large pages. Try to reserve large pages when
2387 // the system is still "fresh".
2388 if (warn_on_failure) {
2389 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
2390 warning(msg);
2391 }
2392 return NULL;
2393 }
2395 // attach to the region
2396 addr = (char*)shmat(shmid, req_addr, 0);
2397 int err = errno;
2399 // Remove shmid. If shmat() is successful, the actual shared memory segment
2400 // will be deleted when it's detached by shmdt() or when the process
2401 // terminates. If shmat() is not successful this will remove the shared
2402 // segment immediately.
2403 shmctl(shmid, IPC_RMID, NULL);
2405 if ((intptr_t)addr == -1) {
2406 if (warn_on_failure) {
2407 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
2408 warning(msg);
2409 }
2410 return NULL;
2411 }
2413 // The memory is committed
2414 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
2416 return addr;
2417 }
2419 bool os::release_memory_special(char* base, size_t bytes) {
2420 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
2421 // detaching the SHM segment will also delete it, see reserve_memory_special()
2422 int rslt = shmdt(base);
2423 if (rslt == 0) {
2424 tkr.record((address)base, bytes);
2425 return true;
2426 } else {
2427 tkr.discard();
2428 return false;
2429 }
2431 }
2433 size_t os::large_page_size() {
2434 return _large_page_size;
2435 }
2437 // HugeTLBFS allows application to commit large page memory on demand;
2438 // with SysV SHM the entire memory region must be allocated as shared
2439 // memory.
2440 bool os::can_commit_large_page_memory() {
2441 return UseHugeTLBFS;
2442 }
2444 bool os::can_execute_large_page_memory() {
2445 return UseHugeTLBFS;
2446 }
2448 // Reserve memory at an arbitrary address, only if that area is
2449 // available (and not reserved for something else).
2451 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2452 const int max_tries = 10;
2453 char* base[max_tries];
2454 size_t size[max_tries];
2455 const size_t gap = 0x000000;
2457 // Assert only that the size is a multiple of the page size, since
2458 // that's all that mmap requires, and since that's all we really know
2459 // about at this low abstraction level. If we need higher alignment,
2460 // we can either pass an alignment to this method or verify alignment
2461 // in one of the methods further up the call chain. See bug 5044738.
2462 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2464 // Repeatedly allocate blocks until the block is allocated at the
2465 // right spot. Give up after max_tries. Note that reserve_memory() will
2466 // automatically update _highest_vm_reserved_address if the call is
2467 // successful. The variable tracks the highest memory address every reserved
2468 // by JVM. It is used to detect heap-stack collision if running with
2469 // fixed-stack BsdThreads. Because here we may attempt to reserve more
2470 // space than needed, it could confuse the collision detecting code. To
2471 // solve the problem, save current _highest_vm_reserved_address and
2472 // calculate the correct value before return.
2473 address old_highest = _highest_vm_reserved_address;
2475 // Bsd mmap allows caller to pass an address as hint; give it a try first,
2476 // if kernel honors the hint then we can return immediately.
2477 char * addr = anon_mmap(requested_addr, bytes, false);
2478 if (addr == requested_addr) {
2479 return requested_addr;
2480 }
2482 if (addr != NULL) {
2483 // mmap() is successful but it fails to reserve at the requested address
2484 anon_munmap(addr, bytes);
2485 }
2487 int i;
2488 for (i = 0; i < max_tries; ++i) {
2489 base[i] = reserve_memory(bytes);
2491 if (base[i] != NULL) {
2492 // Is this the block we wanted?
2493 if (base[i] == requested_addr) {
2494 size[i] = bytes;
2495 break;
2496 }
2498 // Does this overlap the block we wanted? Give back the overlapped
2499 // parts and try again.
2501 size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2502 if (top_overlap >= 0 && top_overlap < bytes) {
2503 unmap_memory(base[i], top_overlap);
2504 base[i] += top_overlap;
2505 size[i] = bytes - top_overlap;
2506 } else {
2507 size_t bottom_overlap = base[i] + bytes - requested_addr;
2508 if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2509 unmap_memory(requested_addr, bottom_overlap);
2510 size[i] = bytes - bottom_overlap;
2511 } else {
2512 size[i] = bytes;
2513 }
2514 }
2515 }
2516 }
2518 // Give back the unused reserved pieces.
2520 for (int j = 0; j < i; ++j) {
2521 if (base[j] != NULL) {
2522 unmap_memory(base[j], size[j]);
2523 }
2524 }
2526 if (i < max_tries) {
2527 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
2528 return requested_addr;
2529 } else {
2530 _highest_vm_reserved_address = old_highest;
2531 return NULL;
2532 }
2533 }
2535 size_t os::read(int fd, void *buf, unsigned int nBytes) {
2536 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
2537 }
2539 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
2540 // Solaris uses poll(), bsd uses park().
2541 // Poll() is likely a better choice, assuming that Thread.interrupt()
2542 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
2543 // SIGSEGV, see 4355769.
2545 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
2546 assert(thread == Thread::current(), "thread consistency check");
2548 ParkEvent * const slp = thread->_SleepEvent ;
2549 slp->reset() ;
2550 OrderAccess::fence() ;
2552 if (interruptible) {
2553 jlong prevtime = javaTimeNanos();
2555 for (;;) {
2556 if (os::is_interrupted(thread, true)) {
2557 return OS_INTRPT;
2558 }
2560 jlong newtime = javaTimeNanos();
2562 if (newtime - prevtime < 0) {
2563 // time moving backwards, should only happen if no monotonic clock
2564 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2565 assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2566 } else {
2567 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2568 }
2570 if(millis <= 0) {
2571 return OS_OK;
2572 }
2574 prevtime = newtime;
2576 {
2577 assert(thread->is_Java_thread(), "sanity check");
2578 JavaThread *jt = (JavaThread *) thread;
2579 ThreadBlockInVM tbivm(jt);
2580 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
2582 jt->set_suspend_equivalent();
2583 // cleared by handle_special_suspend_equivalent_condition() or
2584 // java_suspend_self() via check_and_wait_while_suspended()
2586 slp->park(millis);
2588 // were we externally suspended while we were waiting?
2589 jt->check_and_wait_while_suspended();
2590 }
2591 }
2592 } else {
2593 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
2594 jlong prevtime = javaTimeNanos();
2596 for (;;) {
2597 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
2598 // the 1st iteration ...
2599 jlong newtime = javaTimeNanos();
2601 if (newtime - prevtime < 0) {
2602 // time moving backwards, should only happen if no monotonic clock
2603 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2604 assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2605 } else {
2606 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2607 }
2609 if(millis <= 0) break ;
2611 prevtime = newtime;
2612 slp->park(millis);
2613 }
2614 return OS_OK ;
2615 }
2616 }
2618 int os::naked_sleep() {
2619 // %% make the sleep time an integer flag. for now use 1 millisec.
2620 return os::sleep(Thread::current(), 1, false);
2621 }
2623 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2624 void os::infinite_sleep() {
2625 while (true) { // sleep forever ...
2626 ::sleep(100); // ... 100 seconds at a time
2627 }
2628 }
2630 // Used to convert frequent JVM_Yield() to nops
2631 bool os::dont_yield() {
2632 return DontYieldALot;
2633 }
2635 void os::yield() {
2636 sched_yield();
2637 }
2639 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
2641 void os::yield_all(int attempts) {
2642 // Yields to all threads, including threads with lower priorities
2643 // Threads on Bsd are all with same priority. The Solaris style
2644 // os::yield_all() with nanosleep(1ms) is not necessary.
2645 sched_yield();
2646 }
2648 // Called from the tight loops to possibly influence time-sharing heuristics
2649 void os::loop_breaker(int attempts) {
2650 os::yield_all(attempts);
2651 }
2653 ////////////////////////////////////////////////////////////////////////////////
2654 // thread priority support
2656 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2657 // only supports dynamic priority, static priority must be zero. For real-time
2658 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2659 // However, for large multi-threaded applications, SCHED_RR is not only slower
2660 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2661 // of 5 runs - Sep 2005).
2662 //
2663 // The following code actually changes the niceness of kernel-thread/LWP. It
2664 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2665 // not the entire user process, and user level threads are 1:1 mapped to kernel
2666 // threads. It has always been the case, but could change in the future. For
2667 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2668 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
2670 #if !defined(__APPLE__)
2671 int os::java_to_os_priority[CriticalPriority + 1] = {
2672 19, // 0 Entry should never be used
2674 0, // 1 MinPriority
2675 3, // 2
2676 6, // 3
2678 10, // 4
2679 15, // 5 NormPriority
2680 18, // 6
2682 21, // 7
2683 25, // 8
2684 28, // 9 NearMaxPriority
2686 31, // 10 MaxPriority
2688 31 // 11 CriticalPriority
2689 };
2690 #else
2691 /* Using Mach high-level priority assignments */
2692 int os::java_to_os_priority[CriticalPriority + 1] = {
2693 0, // 0 Entry should never be used (MINPRI_USER)
2695 27, // 1 MinPriority
2696 28, // 2
2697 29, // 3
2699 30, // 4
2700 31, // 5 NormPriority (BASEPRI_DEFAULT)
2701 32, // 6
2703 33, // 7
2704 34, // 8
2705 35, // 9 NearMaxPriority
2707 36, // 10 MaxPriority
2709 36 // 11 CriticalPriority
2710 };
2711 #endif
2713 static int prio_init() {
2714 if (ThreadPriorityPolicy == 1) {
2715 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
2716 // if effective uid is not root. Perhaps, a more elegant way of doing
2717 // this is to test CAP_SYS_NICE capability, but that will require libcap.so
2718 if (geteuid() != 0) {
2719 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
2720 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
2721 }
2722 ThreadPriorityPolicy = 0;
2723 }
2724 }
2725 if (UseCriticalJavaThreadPriority) {
2726 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2727 }
2728 return 0;
2729 }
2731 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2732 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
2734 #ifdef __OpenBSD__
2735 // OpenBSD pthread_setprio starves low priority threads
2736 return OS_OK;
2737 #elif defined(__FreeBSD__)
2738 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2739 #elif defined(__APPLE__) || defined(__NetBSD__)
2740 struct sched_param sp;
2741 int policy;
2742 pthread_t self = pthread_self();
2744 if (pthread_getschedparam(self, &policy, &sp) != 0)
2745 return OS_ERR;
2747 sp.sched_priority = newpri;
2748 if (pthread_setschedparam(self, policy, &sp) != 0)
2749 return OS_ERR;
2751 return OS_OK;
2752 #else
2753 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2754 return (ret == 0) ? OS_OK : OS_ERR;
2755 #endif
2756 }
2758 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2759 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
2760 *priority_ptr = java_to_os_priority[NormPriority];
2761 return OS_OK;
2762 }
2764 errno = 0;
2765 #if defined(__OpenBSD__) || defined(__FreeBSD__)
2766 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2767 #elif defined(__APPLE__) || defined(__NetBSD__)
2768 int policy;
2769 struct sched_param sp;
2771 pthread_getschedparam(pthread_self(), &policy, &sp);
2772 *priority_ptr = sp.sched_priority;
2773 #else
2774 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2775 #endif
2776 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2777 }
2779 // Hint to the underlying OS that a task switch would not be good.
2780 // Void return because it's a hint and can fail.
2781 void os::hint_no_preempt() {}
2783 ////////////////////////////////////////////////////////////////////////////////
2784 // suspend/resume support
2786 // the low-level signal-based suspend/resume support is a remnant from the
2787 // old VM-suspension that used to be for java-suspension, safepoints etc,
2788 // within hotspot. Now there is a single use-case for this:
2789 // - calling get_thread_pc() on the VMThread by the flat-profiler task
2790 // that runs in the watcher thread.
2791 // The remaining code is greatly simplified from the more general suspension
2792 // code that used to be used.
2793 //
2794 // The protocol is quite simple:
2795 // - suspend:
2796 // - sends a signal to the target thread
2797 // - polls the suspend state of the osthread using a yield loop
2798 // - target thread signal handler (SR_handler) sets suspend state
2799 // and blocks in sigsuspend until continued
2800 // - resume:
2801 // - sets target osthread state to continue
2802 // - sends signal to end the sigsuspend loop in the SR_handler
2803 //
2804 // Note that the SR_lock plays no role in this suspend/resume protocol.
2805 //
2807 static void resume_clear_context(OSThread *osthread) {
2808 osthread->set_ucontext(NULL);
2809 osthread->set_siginfo(NULL);
2810 }
2812 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2813 osthread->set_ucontext(context);
2814 osthread->set_siginfo(siginfo);
2815 }
2817 //
2818 // Handler function invoked when a thread's execution is suspended or
2819 // resumed. We have to be careful that only async-safe functions are
2820 // called here (Note: most pthread functions are not async safe and
2821 // should be avoided.)
2822 //
2823 // Note: sigwait() is a more natural fit than sigsuspend() from an
2824 // interface point of view, but sigwait() prevents the signal hander
2825 // from being run. libpthread would get very confused by not having
2826 // its signal handlers run and prevents sigwait()'s use with the
2827 // mutex granting granting signal.
2828 //
2829 // Currently only ever called on the VMThread or JavaThread
2830 //
2831 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2832 // Save and restore errno to avoid confusing native code with EINTR
2833 // after sigsuspend.
2834 int old_errno = errno;
2836 Thread* thread = Thread::current();
2837 OSThread* osthread = thread->osthread();
2838 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
2840 os::SuspendResume::State current = osthread->sr.state();
2841 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
2842 suspend_save_context(osthread, siginfo, context);
2844 // attempt to switch the state, we assume we had a SUSPEND_REQUEST
2845 os::SuspendResume::State state = osthread->sr.suspended();
2846 if (state == os::SuspendResume::SR_SUSPENDED) {
2847 sigset_t suspend_set; // signals for sigsuspend()
2849 // get current set of blocked signals and unblock resume signal
2850 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2851 sigdelset(&suspend_set, SR_signum);
2853 sr_semaphore.signal();
2854 // wait here until we are resumed
2855 while (1) {
2856 sigsuspend(&suspend_set);
2858 os::SuspendResume::State result = osthread->sr.running();
2859 if (result == os::SuspendResume::SR_RUNNING) {
2860 sr_semaphore.signal();
2861 break;
2862 } else if (result != os::SuspendResume::SR_SUSPENDED) {
2863 ShouldNotReachHere();
2864 }
2865 }
2867 } else if (state == os::SuspendResume::SR_RUNNING) {
2868 // request was cancelled, continue
2869 } else {
2870 ShouldNotReachHere();
2871 }
2873 resume_clear_context(osthread);
2874 } else if (current == os::SuspendResume::SR_RUNNING) {
2875 // request was cancelled, continue
2876 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
2877 // ignore
2878 } else {
2879 // ignore
2880 }
2882 errno = old_errno;
2883 }
2886 static int SR_initialize() {
2887 struct sigaction act;
2888 char *s;
2889 /* Get signal number to use for suspend/resume */
2890 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2891 int sig = ::strtol(s, 0, 10);
2892 if (sig > 0 || sig < NSIG) {
2893 SR_signum = sig;
2894 }
2895 }
2897 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2898 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2900 sigemptyset(&SR_sigset);
2901 sigaddset(&SR_sigset, SR_signum);
2903 /* Set up signal handler for suspend/resume */
2904 act.sa_flags = SA_RESTART|SA_SIGINFO;
2905 act.sa_handler = (void (*)(int)) SR_handler;
2907 // SR_signum is blocked by default.
2908 // 4528190 - We also need to block pthread restart signal (32 on all
2909 // supported Bsd platforms). Note that BsdThreads need to block
2910 // this signal for all threads to work properly. So we don't have
2911 // to use hard-coded signal number when setting up the mask.
2912 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2914 if (sigaction(SR_signum, &act, 0) == -1) {
2915 return -1;
2916 }
2918 // Save signal flag
2919 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2920 return 0;
2921 }
2923 static int sr_notify(OSThread* osthread) {
2924 int status = pthread_kill(osthread->pthread_id(), SR_signum);
2925 assert_status(status == 0, status, "pthread_kill");
2926 return status;
2927 }
2929 // "Randomly" selected value for how long we want to spin
2930 // before bailing out on suspending a thread, also how often
2931 // we send a signal to a thread we want to resume
2932 static const int RANDOMLY_LARGE_INTEGER = 1000000;
2933 static const int RANDOMLY_LARGE_INTEGER2 = 100;
2935 // returns true on success and false on error - really an error is fatal
2936 // but this seems the normal response to library errors
2937 static bool do_suspend(OSThread* osthread) {
2938 assert(osthread->sr.is_running(), "thread should be running");
2939 assert(!sr_semaphore.trywait(), "semaphore has invalid state");
2941 // mark as suspended and send signal
2942 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
2943 // failed to switch, state wasn't running?
2944 ShouldNotReachHere();
2945 return false;
2946 }
2948 if (sr_notify(osthread) != 0) {
2949 ShouldNotReachHere();
2950 }
2952 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
2953 while (true) {
2954 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2955 break;
2956 } else {
2957 // timeout
2958 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
2959 if (cancelled == os::SuspendResume::SR_RUNNING) {
2960 return false;
2961 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
2962 // make sure that we consume the signal on the semaphore as well
2963 sr_semaphore.wait();
2964 break;
2965 } else {
2966 ShouldNotReachHere();
2967 return false;
2968 }
2969 }
2970 }
2972 guarantee(osthread->sr.is_suspended(), "Must be suspended");
2973 return true;
2974 }
2976 static void do_resume(OSThread* osthread) {
2977 assert(osthread->sr.is_suspended(), "thread should be suspended");
2978 assert(!sr_semaphore.trywait(), "invalid semaphore state");
2980 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
2981 // failed to switch to WAKEUP_REQUEST
2982 ShouldNotReachHere();
2983 return;
2984 }
2986 while (true) {
2987 if (sr_notify(osthread) == 0) {
2988 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2989 if (osthread->sr.is_running()) {
2990 return;
2991 }
2992 }
2993 } else {
2994 ShouldNotReachHere();
2995 }
2996 }
2998 guarantee(osthread->sr.is_running(), "Must be running!");
2999 }
3001 ////////////////////////////////////////////////////////////////////////////////
3002 // interrupt support
3004 void os::interrupt(Thread* thread) {
3005 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3006 "possibility of dangling Thread pointer");
3008 OSThread* osthread = thread->osthread();
3010 if (!osthread->interrupted()) {
3011 osthread->set_interrupted(true);
3012 // More than one thread can get here with the same value of osthread,
3013 // resulting in multiple notifications. We do, however, want the store
3014 // to interrupted() to be visible to other threads before we execute unpark().
3015 OrderAccess::fence();
3016 ParkEvent * const slp = thread->_SleepEvent ;
3017 if (slp != NULL) slp->unpark() ;
3018 }
3020 // For JSR166. Unpark even if interrupt status already was set
3021 if (thread->is_Java_thread())
3022 ((JavaThread*)thread)->parker()->unpark();
3024 ParkEvent * ev = thread->_ParkEvent ;
3025 if (ev != NULL) ev->unpark() ;
3027 }
3029 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
3030 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3031 "possibility of dangling Thread pointer");
3033 OSThread* osthread = thread->osthread();
3035 bool interrupted = osthread->interrupted();
3037 if (interrupted && clear_interrupted) {
3038 osthread->set_interrupted(false);
3039 // consider thread->_SleepEvent->reset() ... optional optimization
3040 }
3042 return interrupted;
3043 }
3045 ///////////////////////////////////////////////////////////////////////////////////
3046 // signal handling (except suspend/resume)
3048 // This routine may be used by user applications as a "hook" to catch signals.
3049 // The user-defined signal handler must pass unrecognized signals to this
3050 // routine, and if it returns true (non-zero), then the signal handler must
3051 // return immediately. If the flag "abort_if_unrecognized" is true, then this
3052 // routine will never retun false (zero), but instead will execute a VM panic
3053 // routine kill the process.
3054 //
3055 // If this routine returns false, it is OK to call it again. This allows
3056 // the user-defined signal handler to perform checks either before or after
3057 // the VM performs its own checks. Naturally, the user code would be making
3058 // a serious error if it tried to handle an exception (such as a null check
3059 // or breakpoint) that the VM was generating for its own correct operation.
3060 //
3061 // This routine may recognize any of the following kinds of signals:
3062 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
3063 // It should be consulted by handlers for any of those signals.
3064 //
3065 // The caller of this routine must pass in the three arguments supplied
3066 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
3067 // field of the structure passed to sigaction(). This routine assumes that
3068 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3069 //
3070 // Note that the VM will print warnings if it detects conflicting signal
3071 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3072 //
3073 extern "C" JNIEXPORT int
3074 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
3075 void* ucontext, int abort_if_unrecognized);
3077 void signalHandler(int sig, siginfo_t* info, void* uc) {
3078 assert(info != NULL && uc != NULL, "it must be old kernel");
3079 int orig_errno = errno; // Preserve errno value over signal handler.
3080 JVM_handle_bsd_signal(sig, info, uc, true);
3081 errno = orig_errno;
3082 }
3085 // This boolean allows users to forward their own non-matching signals
3086 // to JVM_handle_bsd_signal, harmlessly.
3087 bool os::Bsd::signal_handlers_are_installed = false;
3089 // For signal-chaining
3090 struct sigaction os::Bsd::sigact[MAXSIGNUM];
3091 unsigned int os::Bsd::sigs = 0;
3092 bool os::Bsd::libjsig_is_loaded = false;
3093 typedef struct sigaction *(*get_signal_t)(int);
3094 get_signal_t os::Bsd::get_signal_action = NULL;
3096 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
3097 struct sigaction *actp = NULL;
3099 if (libjsig_is_loaded) {
3100 // Retrieve the old signal handler from libjsig
3101 actp = (*get_signal_action)(sig);
3102 }
3103 if (actp == NULL) {
3104 // Retrieve the preinstalled signal handler from jvm
3105 actp = get_preinstalled_handler(sig);
3106 }
3108 return actp;
3109 }
3111 static bool call_chained_handler(struct sigaction *actp, int sig,
3112 siginfo_t *siginfo, void *context) {
3113 // Call the old signal handler
3114 if (actp->sa_handler == SIG_DFL) {
3115 // It's more reasonable to let jvm treat it as an unexpected exception
3116 // instead of taking the default action.
3117 return false;
3118 } else if (actp->sa_handler != SIG_IGN) {
3119 if ((actp->sa_flags & SA_NODEFER) == 0) {
3120 // automaticlly block the signal
3121 sigaddset(&(actp->sa_mask), sig);
3122 }
3124 sa_handler_t hand;
3125 sa_sigaction_t sa;
3126 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3127 // retrieve the chained handler
3128 if (siginfo_flag_set) {
3129 sa = actp->sa_sigaction;
3130 } else {
3131 hand = actp->sa_handler;
3132 }
3134 if ((actp->sa_flags & SA_RESETHAND) != 0) {
3135 actp->sa_handler = SIG_DFL;
3136 }
3138 // try to honor the signal mask
3139 sigset_t oset;
3140 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3142 // call into the chained handler
3143 if (siginfo_flag_set) {
3144 (*sa)(sig, siginfo, context);
3145 } else {
3146 (*hand)(sig);
3147 }
3149 // restore the signal mask
3150 pthread_sigmask(SIG_SETMASK, &oset, 0);
3151 }
3152 // Tell jvm's signal handler the signal is taken care of.
3153 return true;
3154 }
3156 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3157 bool chained = false;
3158 // signal-chaining
3159 if (UseSignalChaining) {
3160 struct sigaction *actp = get_chained_signal_action(sig);
3161 if (actp != NULL) {
3162 chained = call_chained_handler(actp, sig, siginfo, context);
3163 }
3164 }
3165 return chained;
3166 }
3168 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
3169 if ((( (unsigned int)1 << sig ) & sigs) != 0) {
3170 return &sigact[sig];
3171 }
3172 return NULL;
3173 }
3175 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
3176 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3177 sigact[sig] = oldAct;
3178 sigs |= (unsigned int)1 << sig;
3179 }
3181 // for diagnostic
3182 int os::Bsd::sigflags[MAXSIGNUM];
3184 int os::Bsd::get_our_sigflags(int sig) {
3185 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3186 return sigflags[sig];
3187 }
3189 void os::Bsd::set_our_sigflags(int sig, int flags) {
3190 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3191 sigflags[sig] = flags;
3192 }
3194 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
3195 // Check for overwrite.
3196 struct sigaction oldAct;
3197 sigaction(sig, (struct sigaction*)NULL, &oldAct);
3199 void* oldhand = oldAct.sa_sigaction
3200 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3201 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3202 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3203 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3204 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
3205 if (AllowUserSignalHandlers || !set_installed) {
3206 // Do not overwrite; user takes responsibility to forward to us.
3207 return;
3208 } else if (UseSignalChaining) {
3209 // save the old handler in jvm
3210 save_preinstalled_handler(sig, oldAct);
3211 // libjsig also interposes the sigaction() call below and saves the
3212 // old sigaction on it own.
3213 } else {
3214 fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
3215 "%#lx for signal %d.", (long)oldhand, sig));
3216 }
3217 }
3219 struct sigaction sigAct;
3220 sigfillset(&(sigAct.sa_mask));
3221 sigAct.sa_handler = SIG_DFL;
3222 if (!set_installed) {
3223 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3224 } else {
3225 sigAct.sa_sigaction = signalHandler;
3226 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3227 }
3228 #if __APPLE__
3229 // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
3230 // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
3231 // if the signal handler declares it will handle it on alternate stack.
3232 // Notice we only declare we will handle it on alt stack, but we are not
3233 // actually going to use real alt stack - this is just a workaround.
3234 // Please see ux_exception.c, method catch_mach_exception_raise for details
3235 // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
3236 if (sig == SIGSEGV) {
3237 sigAct.sa_flags |= SA_ONSTACK;
3238 }
3239 #endif
3241 // Save flags, which are set by ours
3242 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3243 sigflags[sig] = sigAct.sa_flags;
3245 int ret = sigaction(sig, &sigAct, &oldAct);
3246 assert(ret == 0, "check");
3248 void* oldhand2 = oldAct.sa_sigaction
3249 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3250 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3251 assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3252 }
3254 // install signal handlers for signals that HotSpot needs to
3255 // handle in order to support Java-level exception handling.
3257 void os::Bsd::install_signal_handlers() {
3258 if (!signal_handlers_are_installed) {
3259 signal_handlers_are_installed = true;
3261 // signal-chaining
3262 typedef void (*signal_setting_t)();
3263 signal_setting_t begin_signal_setting = NULL;
3264 signal_setting_t end_signal_setting = NULL;
3265 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3266 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
3267 if (begin_signal_setting != NULL) {
3268 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3269 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
3270 get_signal_action = CAST_TO_FN_PTR(get_signal_t,
3271 dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
3272 libjsig_is_loaded = true;
3273 assert(UseSignalChaining, "should enable signal-chaining");
3274 }
3275 if (libjsig_is_loaded) {
3276 // Tell libjsig jvm is setting signal handlers
3277 (*begin_signal_setting)();
3278 }
3280 set_signal_handler(SIGSEGV, true);
3281 set_signal_handler(SIGPIPE, true);
3282 set_signal_handler(SIGBUS, true);
3283 set_signal_handler(SIGILL, true);
3284 set_signal_handler(SIGFPE, true);
3285 set_signal_handler(SIGXFSZ, true);
3287 #if defined(__APPLE__)
3288 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
3289 // signals caught and handled by the JVM. To work around this, we reset the mach task
3290 // signal handler that's placed on our process by CrashReporter. This disables
3291 // CrashReporter-based reporting.
3292 //
3293 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
3294 // on caught fatal signals.
3295 //
3296 // Additionally, gdb installs both standard BSD signal handlers, and mach exception
3297 // handlers. By replacing the existing task exception handler, we disable gdb's mach
3298 // exception handling, while leaving the standard BSD signal handlers functional.
3299 kern_return_t kr;
3300 kr = task_set_exception_ports(mach_task_self(),
3301 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
3302 MACH_PORT_NULL,
3303 EXCEPTION_STATE_IDENTITY,
3304 MACHINE_THREAD_STATE);
3306 assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
3307 #endif
3309 if (libjsig_is_loaded) {
3310 // Tell libjsig jvm finishes setting signal handlers
3311 (*end_signal_setting)();
3312 }
3314 // We don't activate signal checker if libjsig is in place, we trust ourselves
3315 // and if UserSignalHandler is installed all bets are off
3316 if (CheckJNICalls) {
3317 if (libjsig_is_loaded) {
3318 if (PrintJNIResolving) {
3319 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
3320 }
3321 check_signals = false;
3322 }
3323 if (AllowUserSignalHandlers) {
3324 if (PrintJNIResolving) {
3325 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
3326 }
3327 check_signals = false;
3328 }
3329 }
3330 }
3331 }
3334 /////
3335 // glibc on Bsd platform uses non-documented flag
3336 // to indicate, that some special sort of signal
3337 // trampoline is used.
3338 // We will never set this flag, and we should
3339 // ignore this flag in our diagnostic
3340 #ifdef SIGNIFICANT_SIGNAL_MASK
3341 #undef SIGNIFICANT_SIGNAL_MASK
3342 #endif
3343 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
3345 static const char* get_signal_handler_name(address handler,
3346 char* buf, int buflen) {
3347 int offset;
3348 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
3349 if (found) {
3350 // skip directory names
3351 const char *p1, *p2;
3352 p1 = buf;
3353 size_t len = strlen(os::file_separator());
3354 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
3355 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
3356 } else {
3357 jio_snprintf(buf, buflen, PTR_FORMAT, handler);
3358 }
3359 return buf;
3360 }
3362 static void print_signal_handler(outputStream* st, int sig,
3363 char* buf, size_t buflen) {
3364 struct sigaction sa;
3366 sigaction(sig, NULL, &sa);
3368 // See comment for SIGNIFICANT_SIGNAL_MASK define
3369 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3371 st->print("%s: ", os::exception_name(sig, buf, buflen));
3373 address handler = (sa.sa_flags & SA_SIGINFO)
3374 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
3375 : CAST_FROM_FN_PTR(address, sa.sa_handler);
3377 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
3378 st->print("SIG_DFL");
3379 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
3380 st->print("SIG_IGN");
3381 } else {
3382 st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
3383 }
3385 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
3387 address rh = VMError::get_resetted_sighandler(sig);
3388 // May be, handler was resetted by VMError?
3389 if(rh != NULL) {
3390 handler = rh;
3391 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
3392 }
3394 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags);
3396 // Check: is it our handler?
3397 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
3398 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
3399 // It is our signal handler
3400 // check for flags, reset system-used one!
3401 if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3402 st->print(
3403 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
3404 os::Bsd::get_our_sigflags(sig));
3405 }
3406 }
3407 st->cr();
3408 }
3411 #define DO_SIGNAL_CHECK(sig) \
3412 if (!sigismember(&check_signal_done, sig)) \
3413 os::Bsd::check_signal_handler(sig)
3415 // This method is a periodic task to check for misbehaving JNI applications
3416 // under CheckJNI, we can add any periodic checks here
3418 void os::run_periodic_checks() {
3420 if (check_signals == false) return;
3422 // SEGV and BUS if overridden could potentially prevent
3423 // generation of hs*.log in the event of a crash, debugging
3424 // such a case can be very challenging, so we absolutely
3425 // check the following for a good measure:
3426 DO_SIGNAL_CHECK(SIGSEGV);
3427 DO_SIGNAL_CHECK(SIGILL);
3428 DO_SIGNAL_CHECK(SIGFPE);
3429 DO_SIGNAL_CHECK(SIGBUS);
3430 DO_SIGNAL_CHECK(SIGPIPE);
3431 DO_SIGNAL_CHECK(SIGXFSZ);
3434 // ReduceSignalUsage allows the user to override these handlers
3435 // see comments at the very top and jvm_solaris.h
3436 if (!ReduceSignalUsage) {
3437 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3438 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3439 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3440 DO_SIGNAL_CHECK(BREAK_SIGNAL);
3441 }
3443 DO_SIGNAL_CHECK(SR_signum);
3444 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
3445 }
3447 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3449 static os_sigaction_t os_sigaction = NULL;
3451 void os::Bsd::check_signal_handler(int sig) {
3452 char buf[O_BUFLEN];
3453 address jvmHandler = NULL;
3456 struct sigaction act;
3457 if (os_sigaction == NULL) {
3458 // only trust the default sigaction, in case it has been interposed
3459 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3460 if (os_sigaction == NULL) return;
3461 }
3463 os_sigaction(sig, (struct sigaction*)NULL, &act);
3466 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3468 address thisHandler = (act.sa_flags & SA_SIGINFO)
3469 ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3470 : CAST_FROM_FN_PTR(address, act.sa_handler) ;
3473 switch(sig) {
3474 case SIGSEGV:
3475 case SIGBUS:
3476 case SIGFPE:
3477 case SIGPIPE:
3478 case SIGILL:
3479 case SIGXFSZ:
3480 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3481 break;
3483 case SHUTDOWN1_SIGNAL:
3484 case SHUTDOWN2_SIGNAL:
3485 case SHUTDOWN3_SIGNAL:
3486 case BREAK_SIGNAL:
3487 jvmHandler = (address)user_handler();
3488 break;
3490 case INTERRUPT_SIGNAL:
3491 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
3492 break;
3494 default:
3495 if (sig == SR_signum) {
3496 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3497 } else {
3498 return;
3499 }
3500 break;
3501 }
3503 if (thisHandler != jvmHandler) {
3504 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3505 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3506 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3507 // No need to check this sig any longer
3508 sigaddset(&check_signal_done, sig);
3509 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3510 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3511 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
3512 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);
3513 // No need to check this sig any longer
3514 sigaddset(&check_signal_done, sig);
3515 }
3517 // Dump all the signal
3518 if (sigismember(&check_signal_done, sig)) {
3519 print_signal_handlers(tty, buf, O_BUFLEN);
3520 }
3521 }
3523 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
3525 extern bool signal_name(int signo, char* buf, size_t len);
3527 const char* os::exception_name(int exception_code, char* buf, size_t size) {
3528 if (0 < exception_code && exception_code <= SIGRTMAX) {
3529 // signal
3530 if (!signal_name(exception_code, buf, size)) {
3531 jio_snprintf(buf, size, "SIG%d", exception_code);
3532 }
3533 return buf;
3534 } else {
3535 return NULL;
3536 }
3537 }
3539 // this is called _before_ the most of global arguments have been parsed
3540 void os::init(void) {
3541 char dummy; /* used to get a guess on initial stack address */
3542 // first_hrtime = gethrtime();
3544 // With BsdThreads the JavaMain thread pid (primordial thread)
3545 // is different than the pid of the java launcher thread.
3546 // So, on Bsd, the launcher thread pid is passed to the VM
3547 // via the sun.java.launcher.pid property.
3548 // Use this property instead of getpid() if it was correctly passed.
3549 // See bug 6351349.
3550 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
3552 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
3554 clock_tics_per_sec = CLK_TCK;
3556 init_random(1234567);
3558 ThreadCritical::initialize();
3560 Bsd::set_page_size(getpagesize());
3561 if (Bsd::page_size() == -1) {
3562 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
3563 strerror(errno)));
3564 }
3565 init_page_sizes((size_t) Bsd::page_size());
3567 Bsd::initialize_system_info();
3569 // main_thread points to the aboriginal thread
3570 Bsd::_main_thread = pthread_self();
3572 Bsd::clock_init();
3573 initial_time_count = os::elapsed_counter();
3575 #ifdef __APPLE__
3576 // XXXDARWIN
3577 // Work around the unaligned VM callbacks in hotspot's
3578 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
3579 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
3580 // alignment when doing symbol lookup. To work around this, we force early
3581 // binding of all symbols now, thus binding when alignment is known-good.
3582 _dyld_bind_fully_image_containing_address((const void *) &os::init);
3583 #endif
3584 }
3586 // To install functions for atexit system call
3587 extern "C" {
3588 static void perfMemory_exit_helper() {
3589 perfMemory_exit();
3590 }
3591 }
3593 // this is called _after_ the global arguments have been parsed
3594 jint os::init_2(void)
3595 {
3596 // Allocate a single page and mark it as readable for safepoint polling
3597 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3598 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
3600 os::set_polling_page( polling_page );
3602 #ifndef PRODUCT
3603 if(Verbose && PrintMiscellaneous)
3604 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
3605 #endif
3607 if (!UseMembar) {
3608 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3609 guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
3610 os::set_memory_serialize_page( mem_serialize_page );
3612 #ifndef PRODUCT
3613 if(Verbose && PrintMiscellaneous)
3614 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
3615 #endif
3616 }
3618 // initialize suspend/resume support - must do this before signal_sets_init()
3619 if (SR_initialize() != 0) {
3620 perror("SR_initialize failed");
3621 return JNI_ERR;
3622 }
3624 Bsd::signal_sets_init();
3625 Bsd::install_signal_handlers();
3627 // Check minimum allowable stack size for thread creation and to initialize
3628 // the java system classes, including StackOverflowError - depends on page
3629 // size. Add a page for compiler2 recursion in main thread.
3630 // Add in 2*BytesPerWord times page size to account for VM stack during
3631 // class initialization depending on 32 or 64 bit VM.
3632 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
3633 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
3634 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
3636 size_t threadStackSizeInBytes = ThreadStackSize * K;
3637 if (threadStackSizeInBytes != 0 &&
3638 threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
3639 tty->print_cr("\nThe stack size specified is too small, "
3640 "Specify at least %dk",
3641 os::Bsd::min_stack_allowed/ K);
3642 return JNI_ERR;
3643 }
3645 // Make the stack size a multiple of the page size so that
3646 // the yellow/red zones can be guarded.
3647 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
3648 vm_page_size()));
3650 if (MaxFDLimit) {
3651 // set the number of file descriptors to max. print out error
3652 // if getrlimit/setrlimit fails but continue regardless.
3653 struct rlimit nbr_files;
3654 int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3655 if (status != 0) {
3656 if (PrintMiscellaneous && (Verbose || WizardMode))
3657 perror("os::init_2 getrlimit failed");
3658 } else {
3659 nbr_files.rlim_cur = nbr_files.rlim_max;
3661 #ifdef __APPLE__
3662 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3663 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3664 // be used instead
3665 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3666 #endif
3668 status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3669 if (status != 0) {
3670 if (PrintMiscellaneous && (Verbose || WizardMode))
3671 perror("os::init_2 setrlimit failed");
3672 }
3673 }
3674 }
3676 // at-exit methods are called in the reverse order of their registration.
3677 // atexit functions are called on return from main or as a result of a
3678 // call to exit(3C). There can be only 32 of these functions registered
3679 // and atexit() does not set errno.
3681 if (PerfAllowAtExitRegistration) {
3682 // only register atexit functions if PerfAllowAtExitRegistration is set.
3683 // atexit functions can be delayed until process exit time, which
3684 // can be problematic for embedded VM situations. Embedded VMs should
3685 // call DestroyJavaVM() to assure that VM resources are released.
3687 // note: perfMemory_exit_helper atexit function may be removed in
3688 // the future if the appropriate cleanup code can be added to the
3689 // VM_Exit VMOperation's doit method.
3690 if (atexit(perfMemory_exit_helper) != 0) {
3691 warning("os::init2 atexit(perfMemory_exit_helper) failed");
3692 }
3693 }
3695 // initialize thread priority policy
3696 prio_init();
3698 #ifdef __APPLE__
3699 // dynamically link to objective c gc registration
3700 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3701 if (handleLibObjc != NULL) {
3702 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3703 }
3704 #endif
3706 return JNI_OK;
3707 }
3709 // this is called at the end of vm_initialization
3710 void os::init_3(void) { }
3712 // Mark the polling page as unreadable
3713 void os::make_polling_page_unreadable(void) {
3714 if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
3715 fatal("Could not disable polling page");
3716 };
3718 // Mark the polling page as readable
3719 void os::make_polling_page_readable(void) {
3720 if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
3721 fatal("Could not enable polling page");
3722 }
3723 };
3725 int os::active_processor_count() {
3726 return _processor_count;
3727 }
3729 void os::set_native_thread_name(const char *name) {
3730 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3731 // This is only supported in Snow Leopard and beyond
3732 if (name != NULL) {
3733 // Add a "Java: " prefix to the name
3734 char buf[MAXTHREADNAMESIZE];
3735 snprintf(buf, sizeof(buf), "Java: %s", name);
3736 pthread_setname_np(buf);
3737 }
3738 #endif
3739 }
3741 bool os::distribute_processes(uint length, uint* distribution) {
3742 // Not yet implemented.
3743 return false;
3744 }
3746 bool os::bind_to_processor(uint processor_id) {
3747 // Not yet implemented.
3748 return false;
3749 }
3751 void os::SuspendedThreadTask::internal_do_task() {
3752 if (do_suspend(_thread->osthread())) {
3753 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3754 do_task(context);
3755 do_resume(_thread->osthread());
3756 }
3757 }
3759 ///
3760 class PcFetcher : public os::SuspendedThreadTask {
3761 public:
3762 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3763 ExtendedPC result();
3764 protected:
3765 void do_task(const os::SuspendedThreadTaskContext& context);
3766 private:
3767 ExtendedPC _epc;
3768 };
3770 ExtendedPC PcFetcher::result() {
3771 guarantee(is_done(), "task is not done yet.");
3772 return _epc;
3773 }
3775 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3776 Thread* thread = context.thread();
3777 OSThread* osthread = thread->osthread();
3778 if (osthread->ucontext() != NULL) {
3779 _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());
3780 } else {
3781 // NULL context is unexpected, double-check this is the VMThread
3782 guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3783 }
3784 }
3786 // Suspends the target using the signal mechanism and then grabs the PC before
3787 // resuming the target. Used by the flat-profiler only
3788 ExtendedPC os::get_thread_pc(Thread* thread) {
3789 // Make sure that it is called by the watcher for the VMThread
3790 assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
3791 assert(thread->is_VM_thread(), "Can only be called for VMThread");
3793 PcFetcher fetcher(thread);
3794 fetcher.run();
3795 return fetcher.result();
3796 }
3798 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
3799 {
3800 return pthread_cond_timedwait(_cond, _mutex, _abstime);
3801 }
3803 ////////////////////////////////////////////////////////////////////////////////
3804 // debug support
3806 bool os::find(address addr, outputStream* st) {
3807 Dl_info dlinfo;
3808 memset(&dlinfo, 0, sizeof(dlinfo));
3809 if (dladdr(addr, &dlinfo) != 0) {
3810 st->print(PTR_FORMAT ": ", addr);
3811 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
3812 st->print("%s+%#x", dlinfo.dli_sname,
3813 addr - (intptr_t)dlinfo.dli_saddr);
3814 } else if (dlinfo.dli_fbase != NULL) {
3815 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
3816 } else {
3817 st->print("<absolute address>");
3818 }
3819 if (dlinfo.dli_fname != NULL) {
3820 st->print(" in %s", dlinfo.dli_fname);
3821 }
3822 if (dlinfo.dli_fbase != NULL) {
3823 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
3824 }
3825 st->cr();
3827 if (Verbose) {
3828 // decode some bytes around the PC
3829 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
3830 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());
3831 address lowest = (address) dlinfo.dli_sname;
3832 if (!lowest) lowest = (address) dlinfo.dli_fbase;
3833 if (begin < lowest) begin = lowest;
3834 Dl_info dlinfo2;
3835 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
3836 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
3837 end = (address) dlinfo2.dli_saddr;
3838 Disassembler::decode(begin, end, st);
3839 }
3840 return true;
3841 }
3842 return false;
3843 }
3845 ////////////////////////////////////////////////////////////////////////////////
3846 // misc
3848 // This does not do anything on Bsd. This is basically a hook for being
3849 // able to use structured exception handling (thread-local exception filters)
3850 // on, e.g., Win32.
3851 void
3852 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
3853 JavaCallArguments* args, Thread* thread) {
3854 f(value, method, args, thread);
3855 }
3857 void os::print_statistics() {
3858 }
3860 int os::message_box(const char* title, const char* message) {
3861 int i;
3862 fdStream err(defaultStream::error_fd());
3863 for (i = 0; i < 78; i++) err.print_raw("=");
3864 err.cr();
3865 err.print_raw_cr(title);
3866 for (i = 0; i < 78; i++) err.print_raw("-");
3867 err.cr();
3868 err.print_raw_cr(message);
3869 for (i = 0; i < 78; i++) err.print_raw("=");
3870 err.cr();
3872 char buf[16];
3873 // Prevent process from exiting upon "read error" without consuming all CPU
3874 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3876 return buf[0] == 'y' || buf[0] == 'Y';
3877 }
3879 int os::stat(const char *path, struct stat *sbuf) {
3880 char pathbuf[MAX_PATH];
3881 if (strlen(path) > MAX_PATH - 1) {
3882 errno = ENAMETOOLONG;
3883 return -1;
3884 }
3885 os::native_path(strcpy(pathbuf, path));
3886 return ::stat(pathbuf, sbuf);
3887 }
3889 bool os::check_heap(bool force) {
3890 return true;
3891 }
3893 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
3894 return ::vsnprintf(buf, count, format, args);
3895 }
3897 // Is a (classpath) directory empty?
3898 bool os::dir_is_empty(const char* path) {
3899 DIR *dir = NULL;
3900 struct dirent *ptr;
3902 dir = opendir(path);
3903 if (dir == NULL) return true;
3905 /* Scan the directory */
3906 bool result = true;
3907 char buf[sizeof(struct dirent) + MAX_PATH];
3908 while (result && (ptr = ::readdir(dir)) != NULL) {
3909 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3910 result = false;
3911 }
3912 }
3913 closedir(dir);
3914 return result;
3915 }
3917 // This code originates from JDK's sysOpen and open64_w
3918 // from src/solaris/hpi/src/system_md.c
3920 #ifndef O_DELETE
3921 #define O_DELETE 0x10000
3922 #endif
3924 // Open a file. Unlink the file immediately after open returns
3925 // if the specified oflag has the O_DELETE flag set.
3926 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
3928 int os::open(const char *path, int oflag, int mode) {
3930 if (strlen(path) > MAX_PATH - 1) {
3931 errno = ENAMETOOLONG;
3932 return -1;
3933 }
3934 int fd;
3935 int o_delete = (oflag & O_DELETE);
3936 oflag = oflag & ~O_DELETE;
3938 fd = ::open(path, oflag, mode);
3939 if (fd == -1) return -1;
3941 //If the open succeeded, the file might still be a directory
3942 {
3943 struct stat buf;
3944 int ret = ::fstat(fd, &buf);
3945 int st_mode = buf.st_mode;
3947 if (ret != -1) {
3948 if ((st_mode & S_IFMT) == S_IFDIR) {
3949 errno = EISDIR;
3950 ::close(fd);
3951 return -1;
3952 }
3953 } else {
3954 ::close(fd);
3955 return -1;
3956 }
3957 }
3959 /*
3960 * All file descriptors that are opened in the JVM and not
3961 * specifically destined for a subprocess should have the
3962 * close-on-exec flag set. If we don't set it, then careless 3rd
3963 * party native code might fork and exec without closing all
3964 * appropriate file descriptors (e.g. as we do in closeDescriptors in
3965 * UNIXProcess.c), and this in turn might:
3966 *
3967 * - cause end-of-file to fail to be detected on some file
3968 * descriptors, resulting in mysterious hangs, or
3969 *
3970 * - might cause an fopen in the subprocess to fail on a system
3971 * suffering from bug 1085341.
3972 *
3973 * (Yes, the default setting of the close-on-exec flag is a Unix
3974 * design flaw)
3975 *
3976 * See:
3977 * 1085341: 32-bit stdio routines should support file descriptors >255
3978 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3979 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3980 */
3981 #ifdef FD_CLOEXEC
3982 {
3983 int flags = ::fcntl(fd, F_GETFD);
3984 if (flags != -1)
3985 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3986 }
3987 #endif
3989 if (o_delete != 0) {
3990 ::unlink(path);
3991 }
3992 return fd;
3993 }
3996 // create binary file, rewriting existing file if required
3997 int os::create_binary_file(const char* path, bool rewrite_existing) {
3998 int oflags = O_WRONLY | O_CREAT;
3999 if (!rewrite_existing) {
4000 oflags |= O_EXCL;
4001 }
4002 return ::open(path, oflags, S_IREAD | S_IWRITE);
4003 }
4005 // return current position of file pointer
4006 jlong os::current_file_offset(int fd) {
4007 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
4008 }
4010 // move file pointer to the specified offset
4011 jlong os::seek_to_file_offset(int fd, jlong offset) {
4012 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
4013 }
4015 // This code originates from JDK's sysAvailable
4016 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
4018 int os::available(int fd, jlong *bytes) {
4019 jlong cur, end;
4020 int mode;
4021 struct stat buf;
4023 if (::fstat(fd, &buf) >= 0) {
4024 mode = buf.st_mode;
4025 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4026 /*
4027 * XXX: is the following call interruptible? If so, this might
4028 * need to go through the INTERRUPT_IO() wrapper as for other
4029 * blocking, interruptible calls in this file.
4030 */
4031 int n;
4032 if (::ioctl(fd, FIONREAD, &n) >= 0) {
4033 *bytes = n;
4034 return 1;
4035 }
4036 }
4037 }
4038 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
4039 return 0;
4040 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
4041 return 0;
4042 } else if (::lseek(fd, cur, SEEK_SET) == -1) {
4043 return 0;
4044 }
4045 *bytes = end - cur;
4046 return 1;
4047 }
4049 int os::socket_available(int fd, jint *pbytes) {
4050 if (fd < 0)
4051 return OS_OK;
4053 int ret;
4055 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
4057 //%% note ioctl can return 0 when successful, JVM_SocketAvailable
4058 // is expected to return 0 on failure and 1 on success to the jdk.
4060 return (ret == OS_ERR) ? 0 : 1;
4061 }
4063 // Map a block of memory.
4064 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4065 char *addr, size_t bytes, bool read_only,
4066 bool allow_exec) {
4067 int prot;
4068 int flags;
4070 if (read_only) {
4071 prot = PROT_READ;
4072 flags = MAP_SHARED;
4073 } else {
4074 prot = PROT_READ | PROT_WRITE;
4075 flags = MAP_PRIVATE;
4076 }
4078 if (allow_exec) {
4079 prot |= PROT_EXEC;
4080 }
4082 if (addr != NULL) {
4083 flags |= MAP_FIXED;
4084 }
4086 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4087 fd, file_offset);
4088 if (mapped_address == MAP_FAILED) {
4089 return NULL;
4090 }
4091 return mapped_address;
4092 }
4095 // Remap a block of memory.
4096 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4097 char *addr, size_t bytes, bool read_only,
4098 bool allow_exec) {
4099 // same as map_memory() on this OS
4100 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4101 allow_exec);
4102 }
4105 // Unmap a block of memory.
4106 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4107 return munmap(addr, bytes) == 0;
4108 }
4110 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4111 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4112 // of a thread.
4113 //
4114 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
4115 // the fast estimate available on the platform.
4117 jlong os::current_thread_cpu_time() {
4118 #ifdef __APPLE__
4119 return os::thread_cpu_time(Thread::current(), true /* user + sys */);
4120 #else
4121 Unimplemented();
4122 return 0;
4123 #endif
4124 }
4126 jlong os::thread_cpu_time(Thread* thread) {
4127 #ifdef __APPLE__
4128 return os::thread_cpu_time(thread, true /* user + sys */);
4129 #else
4130 Unimplemented();
4131 return 0;
4132 #endif
4133 }
4135 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
4136 #ifdef __APPLE__
4137 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
4138 #else
4139 Unimplemented();
4140 return 0;
4141 #endif
4142 }
4144 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
4145 #ifdef __APPLE__
4146 struct thread_basic_info tinfo;
4147 mach_msg_type_number_t tcount = THREAD_INFO_MAX;
4148 kern_return_t kr;
4149 thread_t mach_thread;
4151 mach_thread = thread->osthread()->thread_id();
4152 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
4153 if (kr != KERN_SUCCESS)
4154 return -1;
4156 if (user_sys_cpu_time) {
4157 jlong nanos;
4158 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
4159 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
4160 return nanos;
4161 } else {
4162 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
4163 }
4164 #else
4165 Unimplemented();
4166 return 0;
4167 #endif
4168 }
4171 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4172 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
4173 info_ptr->may_skip_backward = false; // elapsed time not wall time
4174 info_ptr->may_skip_forward = false; // elapsed time not wall time
4175 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
4176 }
4178 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4179 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
4180 info_ptr->may_skip_backward = false; // elapsed time not wall time
4181 info_ptr->may_skip_forward = false; // elapsed time not wall time
4182 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
4183 }
4185 bool os::is_thread_cpu_time_supported() {
4186 #ifdef __APPLE__
4187 return true;
4188 #else
4189 return false;
4190 #endif
4191 }
4193 // System loadavg support. Returns -1 if load average cannot be obtained.
4194 // Bsd doesn't yet have a (official) notion of processor sets,
4195 // so just return the system wide load average.
4196 int os::loadavg(double loadavg[], int nelem) {
4197 return ::getloadavg(loadavg, nelem);
4198 }
4200 void os::pause() {
4201 char filename[MAX_PATH];
4202 if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4203 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4204 } else {
4205 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4206 }
4208 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4209 if (fd != -1) {
4210 struct stat buf;
4211 ::close(fd);
4212 while (::stat(filename, &buf) == 0) {
4213 (void)::poll(NULL, 0, 100);
4214 }
4215 } else {
4216 jio_fprintf(stderr,
4217 "Could not open pause file '%s', continuing immediately.\n", filename);
4218 }
4219 }
4222 // Refer to the comments in os_solaris.cpp park-unpark.
4223 //
4224 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
4225 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
4226 // For specifics regarding the bug see GLIBC BUGID 261237 :
4227 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
4228 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
4229 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
4230 // is used. (The simple C test-case provided in the GLIBC bug report manifests the
4231 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
4232 // and monitorenter when we're using 1-0 locking. All those operations may result in
4233 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
4234 // of libpthread avoids the problem, but isn't practical.
4235 //
4236 // Possible remedies:
4237 //
4238 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
4239 // This is palliative and probabilistic, however. If the thread is preempted
4240 // between the call to compute_abstime() and pthread_cond_timedwait(), more
4241 // than the minimum period may have passed, and the abstime may be stale (in the
4242 // past) resultin in a hang. Using this technique reduces the odds of a hang
4243 // but the JVM is still vulnerable, particularly on heavily loaded systems.
4244 //
4245 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
4246 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set
4247 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
4248 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant
4249 // thread.
4250 //
4251 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
4252 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
4253 // a timeout request to the chron thread and then blocking via pthread_cond_wait().
4254 // This also works well. In fact it avoids kernel-level scalability impediments
4255 // on certain platforms that don't handle lots of active pthread_cond_timedwait()
4256 // timers in a graceful fashion.
4257 //
4258 // 4. When the abstime value is in the past it appears that control returns
4259 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
4260 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we
4261 // can avoid the problem by reinitializing the condvar -- by cond_destroy()
4262 // followed by cond_init() -- after all calls to pthread_cond_timedwait().
4263 // It may be possible to avoid reinitialization by checking the return
4264 // value from pthread_cond_timedwait(). In addition to reinitializing the
4265 // condvar we must establish the invariant that cond_signal() is only called
4266 // within critical sections protected by the adjunct mutex. This prevents
4267 // cond_signal() from "seeing" a condvar that's in the midst of being
4268 // reinitialized or that is corrupt. Sadly, this invariant obviates the
4269 // desirable signal-after-unlock optimization that avoids futile context switching.
4270 //
4271 // I'm also concerned that some versions of NTPL might allocate an auxilliary
4272 // structure when a condvar is used or initialized. cond_destroy() would
4273 // release the helper structure. Our reinitialize-after-timedwait fix
4274 // put excessive stress on malloc/free and locks protecting the c-heap.
4275 //
4276 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
4277 // It may be possible to refine (4) by checking the kernel and NTPL verisons
4278 // and only enabling the work-around for vulnerable environments.
4280 // utility to compute the abstime argument to timedwait:
4281 // millis is the relative timeout time
4282 // abstime will be the absolute timeout time
4283 // TODO: replace compute_abstime() with unpackTime()
4285 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
4286 if (millis < 0) millis = 0;
4287 struct timeval now;
4288 int status = gettimeofday(&now, NULL);
4289 assert(status == 0, "gettimeofday");
4290 jlong seconds = millis / 1000;
4291 millis %= 1000;
4292 if (seconds > 50000000) { // see man cond_timedwait(3T)
4293 seconds = 50000000;
4294 }
4295 abstime->tv_sec = now.tv_sec + seconds;
4296 long usec = now.tv_usec + millis * 1000;
4297 if (usec >= 1000000) {
4298 abstime->tv_sec += 1;
4299 usec -= 1000000;
4300 }
4301 abstime->tv_nsec = usec * 1000;
4302 return abstime;
4303 }
4306 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
4307 // Conceptually TryPark() should be equivalent to park(0).
4309 int os::PlatformEvent::TryPark() {
4310 for (;;) {
4311 const int v = _Event ;
4312 guarantee ((v == 0) || (v == 1), "invariant") ;
4313 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;
4314 }
4315 }
4317 void os::PlatformEvent::park() { // AKA "down()"
4318 // Invariant: Only the thread associated with the Event/PlatformEvent
4319 // may call park().
4320 // TODO: assert that _Assoc != NULL or _Assoc == Self
4321 int v ;
4322 for (;;) {
4323 v = _Event ;
4324 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4325 }
4326 guarantee (v >= 0, "invariant") ;
4327 if (v == 0) {
4328 // Do this the hard way by blocking ...
4329 int status = pthread_mutex_lock(_mutex);
4330 assert_status(status == 0, status, "mutex_lock");
4331 guarantee (_nParked == 0, "invariant") ;
4332 ++ _nParked ;
4333 while (_Event < 0) {
4334 status = pthread_cond_wait(_cond, _mutex);
4335 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
4336 // Treat this the same as if the wait was interrupted
4337 if (status == ETIMEDOUT) { status = EINTR; }
4338 assert_status(status == 0 || status == EINTR, status, "cond_wait");
4339 }
4340 -- _nParked ;
4342 _Event = 0 ;
4343 status = pthread_mutex_unlock(_mutex);
4344 assert_status(status == 0, status, "mutex_unlock");
4345 // Paranoia to ensure our locked and lock-free paths interact
4346 // correctly with each other.
4347 OrderAccess::fence();
4348 }
4349 guarantee (_Event >= 0, "invariant") ;
4350 }
4352 int os::PlatformEvent::park(jlong millis) {
4353 guarantee (_nParked == 0, "invariant") ;
4355 int v ;
4356 for (;;) {
4357 v = _Event ;
4358 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4359 }
4360 guarantee (v >= 0, "invariant") ;
4361 if (v != 0) return OS_OK ;
4363 // We do this the hard way, by blocking the thread.
4364 // Consider enforcing a minimum timeout value.
4365 struct timespec abst;
4366 compute_abstime(&abst, millis);
4368 int ret = OS_TIMEOUT;
4369 int status = pthread_mutex_lock(_mutex);
4370 assert_status(status == 0, status, "mutex_lock");
4371 guarantee (_nParked == 0, "invariant") ;
4372 ++_nParked ;
4374 // Object.wait(timo) will return because of
4375 // (a) notification
4376 // (b) timeout
4377 // (c) thread.interrupt
4378 //
4379 // Thread.interrupt and object.notify{All} both call Event::set.
4380 // That is, we treat thread.interrupt as a special case of notification.
4381 // The underlying Solaris implementation, cond_timedwait, admits
4382 // spurious/premature wakeups, but the JLS/JVM spec prevents the
4383 // JVM from making those visible to Java code. As such, we must
4384 // filter out spurious wakeups. We assume all ETIME returns are valid.
4385 //
4386 // TODO: properly differentiate simultaneous notify+interrupt.
4387 // In that case, we should propagate the notify to another waiter.
4389 while (_Event < 0) {
4390 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
4391 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4392 pthread_cond_destroy (_cond);
4393 pthread_cond_init (_cond, NULL) ;
4394 }
4395 assert_status(status == 0 || status == EINTR ||
4396 status == ETIMEDOUT,
4397 status, "cond_timedwait");
4398 if (!FilterSpuriousWakeups) break ; // previous semantics
4399 if (status == ETIMEDOUT) break ;
4400 // We consume and ignore EINTR and spurious wakeups.
4401 }
4402 --_nParked ;
4403 if (_Event >= 0) {
4404 ret = OS_OK;
4405 }
4406 _Event = 0 ;
4407 status = pthread_mutex_unlock(_mutex);
4408 assert_status(status == 0, status, "mutex_unlock");
4409 assert (_nParked == 0, "invariant") ;
4410 // Paranoia to ensure our locked and lock-free paths interact
4411 // correctly with each other.
4412 OrderAccess::fence();
4413 return ret;
4414 }
4416 void os::PlatformEvent::unpark() {
4417 // Transitions for _Event:
4418 // 0 :=> 1
4419 // 1 :=> 1
4420 // -1 :=> either 0 or 1; must signal target thread
4421 // That is, we can safely transition _Event from -1 to either
4422 // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
4423 // unpark() calls.
4424 // See also: "Semaphores in Plan 9" by Mullender & Cox
4425 //
4426 // Note: Forcing a transition from "-1" to "1" on an unpark() means
4427 // that it will take two back-to-back park() calls for the owning
4428 // thread to block. This has the benefit of forcing a spurious return
4429 // from the first park() call after an unpark() call which will help
4430 // shake out uses of park() and unpark() without condition variables.
4432 if (Atomic::xchg(1, &_Event) >= 0) return;
4434 // Wait for the thread associated with the event to vacate
4435 int status = pthread_mutex_lock(_mutex);
4436 assert_status(status == 0, status, "mutex_lock");
4437 int AnyWaiters = _nParked;
4438 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
4439 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
4440 AnyWaiters = 0;
4441 pthread_cond_signal(_cond);
4442 }
4443 status = pthread_mutex_unlock(_mutex);
4444 assert_status(status == 0, status, "mutex_unlock");
4445 if (AnyWaiters != 0) {
4446 status = pthread_cond_signal(_cond);
4447 assert_status(status == 0, status, "cond_signal");
4448 }
4450 // Note that we signal() _after dropping the lock for "immortal" Events.
4451 // This is safe and avoids a common class of futile wakeups. In rare
4452 // circumstances this can cause a thread to return prematurely from
4453 // cond_{timed}wait() but the spurious wakeup is benign and the victim will
4454 // simply re-test the condition and re-park itself.
4455 }
4458 // JSR166
4459 // -------------------------------------------------------
4461 /*
4462 * The solaris and bsd implementations of park/unpark are fairly
4463 * conservative for now, but can be improved. They currently use a
4464 * mutex/condvar pair, plus a a count.
4465 * Park decrements count if > 0, else does a condvar wait. Unpark
4466 * sets count to 1 and signals condvar. Only one thread ever waits
4467 * on the condvar. Contention seen when trying to park implies that someone
4468 * is unparking you, so don't wait. And spurious returns are fine, so there
4469 * is no need to track notifications.
4470 */
4472 #define MAX_SECS 100000000
4473 /*
4474 * This code is common to bsd and solaris and will be moved to a
4475 * common place in dolphin.
4476 *
4477 * The passed in time value is either a relative time in nanoseconds
4478 * or an absolute time in milliseconds. Either way it has to be unpacked
4479 * into suitable seconds and nanoseconds components and stored in the
4480 * given timespec structure.
4481 * Given time is a 64-bit value and the time_t used in the timespec is only
4482 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
4483 * overflow if times way in the future are given. Further on Solaris versions
4484 * prior to 10 there is a restriction (see cond_timedwait) that the specified
4485 * number of seconds, in abstime, is less than current_time + 100,000,000.
4486 * As it will be 28 years before "now + 100000000" will overflow we can
4487 * ignore overflow and just impose a hard-limit on seconds using the value
4488 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
4489 * years from "now".
4490 */
4492 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
4493 assert (time > 0, "convertTime");
4495 struct timeval now;
4496 int status = gettimeofday(&now, NULL);
4497 assert(status == 0, "gettimeofday");
4499 time_t max_secs = now.tv_sec + MAX_SECS;
4501 if (isAbsolute) {
4502 jlong secs = time / 1000;
4503 if (secs > max_secs) {
4504 absTime->tv_sec = max_secs;
4505 }
4506 else {
4507 absTime->tv_sec = secs;
4508 }
4509 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
4510 }
4511 else {
4512 jlong secs = time / NANOSECS_PER_SEC;
4513 if (secs >= MAX_SECS) {
4514 absTime->tv_sec = max_secs;
4515 absTime->tv_nsec = 0;
4516 }
4517 else {
4518 absTime->tv_sec = now.tv_sec + secs;
4519 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
4520 if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
4521 absTime->tv_nsec -= NANOSECS_PER_SEC;
4522 ++absTime->tv_sec; // note: this must be <= max_secs
4523 }
4524 }
4525 }
4526 assert(absTime->tv_sec >= 0, "tv_sec < 0");
4527 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
4528 assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
4529 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
4530 }
4532 void Parker::park(bool isAbsolute, jlong time) {
4533 // Ideally we'd do something useful while spinning, such
4534 // as calling unpackTime().
4536 // Optional fast-path check:
4537 // Return immediately if a permit is available.
4538 // We depend on Atomic::xchg() having full barrier semantics
4539 // since we are doing a lock-free update to _counter.
4540 if (Atomic::xchg(0, &_counter) > 0) return;
4542 Thread* thread = Thread::current();
4543 assert(thread->is_Java_thread(), "Must be JavaThread");
4544 JavaThread *jt = (JavaThread *)thread;
4546 // Optional optimization -- avoid state transitions if there's an interrupt pending.
4547 // Check interrupt before trying to wait
4548 if (Thread::is_interrupted(thread, false)) {
4549 return;
4550 }
4552 // Next, demultiplex/decode time arguments
4553 struct timespec absTime;
4554 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
4555 return;
4556 }
4557 if (time > 0) {
4558 unpackTime(&absTime, isAbsolute, time);
4559 }
4562 // Enter safepoint region
4563 // Beware of deadlocks such as 6317397.
4564 // The per-thread Parker:: mutex is a classic leaf-lock.
4565 // In particular a thread must never block on the Threads_lock while
4566 // holding the Parker:: mutex. If safepoints are pending both the
4567 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
4568 ThreadBlockInVM tbivm(jt);
4570 // Don't wait if cannot get lock since interference arises from
4571 // unblocking. Also. check interrupt before trying wait
4572 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
4573 return;
4574 }
4576 int status ;
4577 if (_counter > 0) { // no wait needed
4578 _counter = 0;
4579 status = pthread_mutex_unlock(_mutex);
4580 assert (status == 0, "invariant") ;
4581 // Paranoia to ensure our locked and lock-free paths interact
4582 // correctly with each other and Java-level accesses.
4583 OrderAccess::fence();
4584 return;
4585 }
4587 #ifdef ASSERT
4588 // Don't catch signals while blocked; let the running threads have the signals.
4589 // (This allows a debugger to break into the running thread.)
4590 sigset_t oldsigs;
4591 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
4592 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
4593 #endif
4595 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
4596 jt->set_suspend_equivalent();
4597 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
4599 if (time == 0) {
4600 status = pthread_cond_wait (_cond, _mutex) ;
4601 } else {
4602 status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
4603 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4604 pthread_cond_destroy (_cond) ;
4605 pthread_cond_init (_cond, NULL);
4606 }
4607 }
4608 assert_status(status == 0 || status == EINTR ||
4609 status == ETIMEDOUT,
4610 status, "cond_timedwait");
4612 #ifdef ASSERT
4613 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
4614 #endif
4616 _counter = 0 ;
4617 status = pthread_mutex_unlock(_mutex) ;
4618 assert_status(status == 0, status, "invariant") ;
4619 // Paranoia to ensure our locked and lock-free paths interact
4620 // correctly with each other and Java-level accesses.
4621 OrderAccess::fence();
4623 // If externally suspended while waiting, re-suspend
4624 if (jt->handle_special_suspend_equivalent_condition()) {
4625 jt->java_suspend_self();
4626 }
4627 }
4629 void Parker::unpark() {
4630 int s, status ;
4631 status = pthread_mutex_lock(_mutex);
4632 assert (status == 0, "invariant") ;
4633 s = _counter;
4634 _counter = 1;
4635 if (s < 1) {
4636 if (WorkAroundNPTLTimedWaitHang) {
4637 status = pthread_cond_signal (_cond) ;
4638 assert (status == 0, "invariant") ;
4639 status = pthread_mutex_unlock(_mutex);
4640 assert (status == 0, "invariant") ;
4641 } else {
4642 status = pthread_mutex_unlock(_mutex);
4643 assert (status == 0, "invariant") ;
4644 status = pthread_cond_signal (_cond) ;
4645 assert (status == 0, "invariant") ;
4646 }
4647 } else {
4648 pthread_mutex_unlock(_mutex);
4649 assert (status == 0, "invariant") ;
4650 }
4651 }
4654 /* Darwin has no "environ" in a dynamic library. */
4655 #ifdef __APPLE__
4656 #include <crt_externs.h>
4657 #define environ (*_NSGetEnviron())
4658 #else
4659 extern char** environ;
4660 #endif
4662 // Run the specified command in a separate process. Return its exit value,
4663 // or -1 on failure (e.g. can't fork a new process).
4664 // Unlike system(), this function can be called from signal handler. It
4665 // doesn't block SIGINT et al.
4666 int os::fork_and_exec(char* cmd) {
4667 const char * argv[4] = {"sh", "-c", cmd, NULL};
4669 // fork() in BsdThreads/NPTL is not async-safe. It needs to run
4670 // pthread_atfork handlers and reset pthread library. All we need is a
4671 // separate process to execve. Make a direct syscall to fork process.
4672 // On IA64 there's no fork syscall, we have to use fork() and hope for
4673 // the best...
4674 pid_t pid = fork();
4676 if (pid < 0) {
4677 // fork failed
4678 return -1;
4680 } else if (pid == 0) {
4681 // child process
4683 // execve() in BsdThreads will call pthread_kill_other_threads_np()
4684 // first to kill every thread on the thread list. Because this list is
4685 // not reset by fork() (see notes above), execve() will instead kill
4686 // every thread in the parent process. We know this is the only thread
4687 // in the new process, so make a system call directly.
4688 // IA64 should use normal execve() from glibc to match the glibc fork()
4689 // above.
4690 execve("/bin/sh", (char* const*)argv, environ);
4692 // execve failed
4693 _exit(-1);
4695 } else {
4696 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
4697 // care about the actual exit code, for now.
4699 int status;
4701 // Wait for the child process to exit. This returns immediately if
4702 // the child has already exited. */
4703 while (waitpid(pid, &status, 0) < 0) {
4704 switch (errno) {
4705 case ECHILD: return 0;
4706 case EINTR: break;
4707 default: return -1;
4708 }
4709 }
4711 if (WIFEXITED(status)) {
4712 // The child exited normally; get its exit code.
4713 return WEXITSTATUS(status);
4714 } else if (WIFSIGNALED(status)) {
4715 // The child exited because of a signal
4716 // The best value to return is 0x80 + signal number,
4717 // because that is what all Unix shells do, and because
4718 // it allows callers to distinguish between process exit and
4719 // process death by signal.
4720 return 0x80 + WTERMSIG(status);
4721 } else {
4722 // Unknown exit code; pass it through
4723 return status;
4724 }
4725 }
4726 }
4728 // is_headless_jre()
4729 //
4730 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
4731 // in order to report if we are running in a headless jre
4732 //
4733 // Since JDK8 xawt/libmawt.so was moved into the same directory
4734 // as libawt.so, and renamed libawt_xawt.so
4735 //
4736 bool os::is_headless_jre() {
4737 struct stat statbuf;
4738 char buf[MAXPATHLEN];
4739 char libmawtpath[MAXPATHLEN];
4740 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX;
4741 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
4742 char *p;
4744 // Get path to libjvm.so
4745 os::jvm_path(buf, sizeof(buf));
4747 // Get rid of libjvm.so
4748 p = strrchr(buf, '/');
4749 if (p == NULL) return false;
4750 else *p = '\0';
4752 // Get rid of client or server
4753 p = strrchr(buf, '/');
4754 if (p == NULL) return false;
4755 else *p = '\0';
4757 // check xawt/libmawt.so
4758 strcpy(libmawtpath, buf);
4759 strcat(libmawtpath, xawtstr);
4760 if (::stat(libmawtpath, &statbuf) == 0) return false;
4762 // check libawt_xawt.so
4763 strcpy(libmawtpath, buf);
4764 strcat(libmawtpath, new_xawtstr);
4765 if (::stat(libmawtpath, &statbuf) == 0) return false;
4767 return true;
4768 }
4770 // Get the default path to the core file
4771 // Returns the length of the string
4772 int os::get_core_path(char* buffer, size_t bufferSize) {
4773 int n = jio_snprintf(buffer, bufferSize, "/cores");
4775 // Truncate if theoretical string was longer than bufferSize
4776 n = MIN2(n, (int)bufferSize);
4778 return n;
4779 }
4781 #ifndef PRODUCT
4782 void TestReserveMemorySpecial_test() {
4783 // No tests available for this platform
4784 }
4785 #endif