Wed, 02 Oct 2013 20:58:44 +0400
8025283: Nits in os_bsd file breaks compilation of open hotspot
Summary: Couple of nits in os_bsd.cpp brake compilation of open hotspot on non-apple platforms
Reviewed-by: sla, sspitsyn
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 #ifdef __APPLE__
695 // thread_id is mach thread on macos, which pthreads graciously caches and provides for us
696 mach_port_t thread_id = ::pthread_mach_thread_np(::pthread_self());
697 guarantee(thread_id != 0, "thread id missing from pthreads");
698 osthread->set_thread_id(thread_id);
700 uint64_t unique_thread_id = locate_unique_thread_id(thread_id);
701 guarantee(unique_thread_id != 0, "unique thread id was not found");
702 osthread->set_unique_thread_id(unique_thread_id);
703 #else
704 // thread_id is pthread_id on BSD
705 osthread->set_thread_id(::pthread_self());
706 #endif
707 // initialize signal mask for this thread
708 os::Bsd::hotspot_sigmask(thread);
710 // initialize floating point control register
711 os::Bsd::init_thread_fpu_state();
713 #ifdef __APPLE__
714 // register thread with objc gc
715 if (objc_registerThreadWithCollectorFunction != NULL) {
716 objc_registerThreadWithCollectorFunction();
717 }
718 #endif
720 // handshaking with parent thread
721 {
722 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
724 // notify parent thread
725 osthread->set_state(INITIALIZED);
726 sync->notify_all();
728 // wait until os::start_thread()
729 while (osthread->get_state() == INITIALIZED) {
730 sync->wait(Mutex::_no_safepoint_check_flag);
731 }
732 }
734 // call one more level start routine
735 thread->run();
737 return 0;
738 }
740 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
741 assert(thread->osthread() == NULL, "caller responsible");
743 // Allocate the OSThread object
744 OSThread* osthread = new OSThread(NULL, NULL);
745 if (osthread == NULL) {
746 return false;
747 }
749 // set the correct thread state
750 osthread->set_thread_type(thr_type);
752 // Initial state is ALLOCATED but not INITIALIZED
753 osthread->set_state(ALLOCATED);
755 thread->set_osthread(osthread);
757 // init thread attributes
758 pthread_attr_t attr;
759 pthread_attr_init(&attr);
760 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
762 // stack size
763 if (os::Bsd::supports_variable_stack_size()) {
764 // calculate stack size if it's not specified by caller
765 if (stack_size == 0) {
766 stack_size = os::Bsd::default_stack_size(thr_type);
768 switch (thr_type) {
769 case os::java_thread:
770 // Java threads use ThreadStackSize which default value can be
771 // changed with the flag -Xss
772 assert (JavaThread::stack_size_at_create() > 0, "this should be set");
773 stack_size = JavaThread::stack_size_at_create();
774 break;
775 case os::compiler_thread:
776 if (CompilerThreadStackSize > 0) {
777 stack_size = (size_t)(CompilerThreadStackSize * K);
778 break;
779 } // else fall through:
780 // use VMThreadStackSize if CompilerThreadStackSize is not defined
781 case os::vm_thread:
782 case os::pgc_thread:
783 case os::cgc_thread:
784 case os::watcher_thread:
785 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
786 break;
787 }
788 }
790 stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
791 pthread_attr_setstacksize(&attr, stack_size);
792 } else {
793 // let pthread_create() pick the default value.
794 }
796 ThreadState state;
798 {
799 pthread_t tid;
800 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
802 pthread_attr_destroy(&attr);
804 if (ret != 0) {
805 if (PrintMiscellaneous && (Verbose || WizardMode)) {
806 perror("pthread_create()");
807 }
808 // Need to clean up stuff we've allocated so far
809 thread->set_osthread(NULL);
810 delete osthread;
811 return false;
812 }
814 // Store pthread info into the OSThread
815 osthread->set_pthread_id(tid);
817 // Wait until child thread is either initialized or aborted
818 {
819 Monitor* sync_with_child = osthread->startThread_lock();
820 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
821 while ((state = osthread->get_state()) == ALLOCATED) {
822 sync_with_child->wait(Mutex::_no_safepoint_check_flag);
823 }
824 }
826 }
828 // Aborted due to thread limit being reached
829 if (state == ZOMBIE) {
830 thread->set_osthread(NULL);
831 delete osthread;
832 return false;
833 }
835 // The thread is returned suspended (in state INITIALIZED),
836 // and is started higher up in the call chain
837 assert(state == INITIALIZED, "race condition");
838 return true;
839 }
841 /////////////////////////////////////////////////////////////////////////////
842 // attach existing thread
844 // bootstrap the main thread
845 bool os::create_main_thread(JavaThread* thread) {
846 assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
847 return create_attached_thread(thread);
848 }
850 bool os::create_attached_thread(JavaThread* thread) {
851 #ifdef ASSERT
852 thread->verify_not_published();
853 #endif
855 // Allocate the OSThread object
856 OSThread* osthread = new OSThread(NULL, NULL);
858 if (osthread == NULL) {
859 return false;
860 }
862 // Store pthread info into the OSThread
863 #ifdef __APPLE__
864 // thread_id is mach thread on macos, which pthreads graciously caches and provides for us
865 mach_port_t thread_id = ::pthread_mach_thread_np(::pthread_self());
866 guarantee(thread_id != 0, "just checking");
867 osthread->set_thread_id(thread_id);
869 uint64_t unique_thread_id = locate_unique_thread_id(thread_id);
870 guarantee(unique_thread_id != 0, "just checking");
871 osthread->set_unique_thread_id(unique_thread_id);
872 #else
873 osthread->set_thread_id(::pthread_self());
874 #endif
875 osthread->set_pthread_id(::pthread_self());
877 // initialize floating point control register
878 os::Bsd::init_thread_fpu_state();
880 // Initial thread state is RUNNABLE
881 osthread->set_state(RUNNABLE);
883 thread->set_osthread(osthread);
885 // initialize signal mask for this thread
886 // and save the caller's signal mask
887 os::Bsd::hotspot_sigmask(thread);
889 return true;
890 }
892 void os::pd_start_thread(Thread* thread) {
893 OSThread * osthread = thread->osthread();
894 assert(osthread->get_state() != INITIALIZED, "just checking");
895 Monitor* sync_with_child = osthread->startThread_lock();
896 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
897 sync_with_child->notify();
898 }
900 // Free Bsd resources related to the OSThread
901 void os::free_thread(OSThread* osthread) {
902 assert(osthread != NULL, "osthread not set");
904 if (Thread::current()->osthread() == osthread) {
905 // Restore caller's signal mask
906 sigset_t sigmask = osthread->caller_sigmask();
907 pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
908 }
910 delete osthread;
911 }
913 //////////////////////////////////////////////////////////////////////////////
914 // thread local storage
916 int os::allocate_thread_local_storage() {
917 pthread_key_t key;
918 int rslt = pthread_key_create(&key, NULL);
919 assert(rslt == 0, "cannot allocate thread local storage");
920 return (int)key;
921 }
923 // Note: This is currently not used by VM, as we don't destroy TLS key
924 // on VM exit.
925 void os::free_thread_local_storage(int index) {
926 int rslt = pthread_key_delete((pthread_key_t)index);
927 assert(rslt == 0, "invalid index");
928 }
930 void os::thread_local_storage_at_put(int index, void* value) {
931 int rslt = pthread_setspecific((pthread_key_t)index, value);
932 assert(rslt == 0, "pthread_setspecific failed");
933 }
935 extern "C" Thread* get_thread() {
936 return ThreadLocalStorage::thread();
937 }
940 ////////////////////////////////////////////////////////////////////////////////
941 // time support
943 // Time since start-up in seconds to a fine granularity.
944 // Used by VMSelfDestructTimer and the MemProfiler.
945 double os::elapsedTime() {
947 return (double)(os::elapsed_counter()) * 0.000001;
948 }
950 jlong os::elapsed_counter() {
951 timeval time;
952 int status = gettimeofday(&time, NULL);
953 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
954 }
956 jlong os::elapsed_frequency() {
957 return (1000 * 1000);
958 }
960 bool os::supports_vtime() { return true; }
961 bool os::enable_vtime() { return false; }
962 bool os::vtime_enabled() { return false; }
964 double os::elapsedVTime() {
965 // better than nothing, but not much
966 return elapsedTime();
967 }
969 jlong os::javaTimeMillis() {
970 timeval time;
971 int status = gettimeofday(&time, NULL);
972 assert(status != -1, "bsd error");
973 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
974 }
976 #ifndef CLOCK_MONOTONIC
977 #define CLOCK_MONOTONIC (1)
978 #endif
980 #ifdef __APPLE__
981 void os::Bsd::clock_init() {
982 // XXXDARWIN: Investigate replacement monotonic clock
983 }
984 #else
985 void os::Bsd::clock_init() {
986 struct timespec res;
987 struct timespec tp;
988 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
989 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
990 // yes, monotonic clock is supported
991 _clock_gettime = ::clock_gettime;
992 }
993 }
994 #endif
997 jlong os::javaTimeNanos() {
998 if (Bsd::supports_monotonic_clock()) {
999 struct timespec tp;
1000 int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
1001 assert(status == 0, "gettime error");
1002 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1003 return result;
1004 } else {
1005 timeval time;
1006 int status = gettimeofday(&time, NULL);
1007 assert(status != -1, "bsd error");
1008 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1009 return 1000 * usecs;
1010 }
1011 }
1013 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1014 if (Bsd::supports_monotonic_clock()) {
1015 info_ptr->max_value = ALL_64_BITS;
1017 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1018 info_ptr->may_skip_backward = false; // not subject to resetting or drifting
1019 info_ptr->may_skip_forward = false; // not subject to resetting or drifting
1020 } else {
1021 // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1022 info_ptr->max_value = ALL_64_BITS;
1024 // gettimeofday is a real time clock so it skips
1025 info_ptr->may_skip_backward = true;
1026 info_ptr->may_skip_forward = true;
1027 }
1029 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
1030 }
1032 // Return the real, user, and system times in seconds from an
1033 // arbitrary fixed point in the past.
1034 bool os::getTimesSecs(double* process_real_time,
1035 double* process_user_time,
1036 double* process_system_time) {
1037 struct tms ticks;
1038 clock_t real_ticks = times(&ticks);
1040 if (real_ticks == (clock_t) (-1)) {
1041 return false;
1042 } else {
1043 double ticks_per_second = (double) clock_tics_per_sec;
1044 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1045 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1046 *process_real_time = ((double) real_ticks) / ticks_per_second;
1048 return true;
1049 }
1050 }
1053 char * os::local_time_string(char *buf, size_t buflen) {
1054 struct tm t;
1055 time_t long_time;
1056 time(&long_time);
1057 localtime_r(&long_time, &t);
1058 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1059 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1060 t.tm_hour, t.tm_min, t.tm_sec);
1061 return buf;
1062 }
1064 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
1065 return localtime_r(clock, res);
1066 }
1068 ////////////////////////////////////////////////////////////////////////////////
1069 // runtime exit support
1071 // Note: os::shutdown() might be called very early during initialization, or
1072 // called from signal handler. Before adding something to os::shutdown(), make
1073 // sure it is async-safe and can handle partially initialized VM.
1074 void os::shutdown() {
1076 // allow PerfMemory to attempt cleanup of any persistent resources
1077 perfMemory_exit();
1079 // needs to remove object in file system
1080 AttachListener::abort();
1082 // flush buffered output, finish log files
1083 ostream_abort();
1085 // Check for abort hook
1086 abort_hook_t abort_hook = Arguments::abort_hook();
1087 if (abort_hook != NULL) {
1088 abort_hook();
1089 }
1091 }
1093 // Note: os::abort() might be called very early during initialization, or
1094 // called from signal handler. Before adding something to os::abort(), make
1095 // sure it is async-safe and can handle partially initialized VM.
1096 void os::abort(bool dump_core) {
1097 os::shutdown();
1098 if (dump_core) {
1099 #ifndef PRODUCT
1100 fdStream out(defaultStream::output_fd());
1101 out.print_raw("Current thread is ");
1102 char buf[16];
1103 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1104 out.print_raw_cr(buf);
1105 out.print_raw_cr("Dumping core ...");
1106 #endif
1107 ::abort(); // dump core
1108 }
1110 ::exit(1);
1111 }
1113 // Die immediately, no exit hook, no abort hook, no cleanup.
1114 void os::die() {
1115 // _exit() on BsdThreads only kills current thread
1116 ::abort();
1117 }
1119 // unused on bsd for now.
1120 void os::set_error_file(const char *logfile) {}
1123 // This method is a copy of JDK's sysGetLastErrorString
1124 // from src/solaris/hpi/src/system_md.c
1126 size_t os::lasterror(char *buf, size_t len) {
1128 if (errno == 0) return 0;
1130 const char *s = ::strerror(errno);
1131 size_t n = ::strlen(s);
1132 if (n >= len) {
1133 n = len - 1;
1134 }
1135 ::strncpy(buf, s, n);
1136 buf[n] = '\0';
1137 return n;
1138 }
1140 intx os::current_thread_id() {
1141 #ifdef __APPLE__
1142 return (intx)::pthread_mach_thread_np(::pthread_self());
1143 #else
1144 return (intx)::pthread_self();
1145 #endif
1146 }
1147 int os::current_process_id() {
1149 // Under the old bsd thread library, bsd gives each thread
1150 // its own process id. Because of this each thread will return
1151 // a different pid if this method were to return the result
1152 // of getpid(2). Bsd provides no api that returns the pid
1153 // of the launcher thread for the vm. This implementation
1154 // returns a unique pid, the pid of the launcher thread
1155 // that starts the vm 'process'.
1157 // Under the NPTL, getpid() returns the same pid as the
1158 // launcher thread rather than a unique pid per thread.
1159 // Use gettid() if you want the old pre NPTL behaviour.
1161 // if you are looking for the result of a call to getpid() that
1162 // returns a unique pid for the calling thread, then look at the
1163 // OSThread::thread_id() method in osThread_bsd.hpp file
1165 return (int)(_initial_pid ? _initial_pid : getpid());
1166 }
1168 // DLL functions
1170 #define JNI_LIB_PREFIX "lib"
1171 #ifdef __APPLE__
1172 #define JNI_LIB_SUFFIX ".dylib"
1173 #else
1174 #define JNI_LIB_SUFFIX ".so"
1175 #endif
1177 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1179 // This must be hard coded because it's the system's temporary
1180 // directory not the java application's temp directory, ala java.io.tmpdir.
1181 #ifdef __APPLE__
1182 // macosx has a secure per-user temporary directory
1183 char temp_path_storage[PATH_MAX];
1184 const char* os::get_temp_directory() {
1185 static char *temp_path = NULL;
1186 if (temp_path == NULL) {
1187 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1188 if (pathSize == 0 || pathSize > PATH_MAX) {
1189 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1190 }
1191 temp_path = temp_path_storage;
1192 }
1193 return temp_path;
1194 }
1195 #else /* __APPLE__ */
1196 const char* os::get_temp_directory() { return "/tmp"; }
1197 #endif /* __APPLE__ */
1199 static bool file_exists(const char* filename) {
1200 struct stat statbuf;
1201 if (filename == NULL || strlen(filename) == 0) {
1202 return false;
1203 }
1204 return os::stat(filename, &statbuf) == 0;
1205 }
1207 bool os::dll_build_name(char* buffer, size_t buflen,
1208 const char* pname, const char* fname) {
1209 bool retval = false;
1210 // Copied from libhpi
1211 const size_t pnamelen = pname ? strlen(pname) : 0;
1213 // Return error on buffer overflow.
1214 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
1215 return retval;
1216 }
1218 if (pnamelen == 0) {
1219 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
1220 retval = true;
1221 } else if (strchr(pname, *os::path_separator()) != NULL) {
1222 int n;
1223 char** pelements = split_path(pname, &n);
1224 if (pelements == NULL) {
1225 return false;
1226 }
1227 for (int i = 0 ; i < n ; i++) {
1228 // Really shouldn't be NULL, but check can't hurt
1229 if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1230 continue; // skip the empty path values
1231 }
1232 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
1233 pelements[i], fname);
1234 if (file_exists(buffer)) {
1235 retval = true;
1236 break;
1237 }
1238 }
1239 // release the storage
1240 for (int i = 0 ; i < n ; i++) {
1241 if (pelements[i] != NULL) {
1242 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1243 }
1244 }
1245 if (pelements != NULL) {
1246 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1247 }
1248 } else {
1249 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
1250 retval = true;
1251 }
1252 return retval;
1253 }
1255 // check if addr is inside libjvm.so
1256 bool os::address_is_in_vm(address addr) {
1257 static address libjvm_base_addr;
1258 Dl_info dlinfo;
1260 if (libjvm_base_addr == NULL) {
1261 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1262 libjvm_base_addr = (address)dlinfo.dli_fbase;
1263 }
1264 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1265 }
1267 if (dladdr((void *)addr, &dlinfo) != 0) {
1268 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1269 }
1271 return false;
1272 }
1275 #define MACH_MAXSYMLEN 256
1277 bool os::dll_address_to_function_name(address addr, char *buf,
1278 int buflen, int *offset) {
1279 // buf is not optional, but offset is optional
1280 assert(buf != NULL, "sanity check");
1282 Dl_info dlinfo;
1283 char localbuf[MACH_MAXSYMLEN];
1285 if (dladdr((void*)addr, &dlinfo) != 0) {
1286 // see if we have a matching symbol
1287 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1288 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1289 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1290 }
1291 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1292 return true;
1293 }
1294 // no matching symbol so try for just file info
1295 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1296 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1297 buf, buflen, offset, dlinfo.dli_fname)) {
1298 return true;
1299 }
1300 }
1302 // Handle non-dynamic manually:
1303 if (dlinfo.dli_fbase != NULL &&
1304 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
1305 dlinfo.dli_fbase)) {
1306 if (!Decoder::demangle(localbuf, buf, buflen)) {
1307 jio_snprintf(buf, buflen, "%s", localbuf);
1308 }
1309 return true;
1310 }
1311 }
1312 buf[0] = '\0';
1313 if (offset != NULL) *offset = -1;
1314 return false;
1315 }
1317 // ported from solaris version
1318 bool os::dll_address_to_library_name(address addr, char* buf,
1319 int buflen, int* offset) {
1320 // buf is not optional, but offset is optional
1321 assert(buf != NULL, "sanity check");
1323 Dl_info dlinfo;
1325 if (dladdr((void*)addr, &dlinfo) != 0) {
1326 if (dlinfo.dli_fname != NULL) {
1327 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1328 }
1329 if (dlinfo.dli_fbase != NULL && offset != NULL) {
1330 *offset = addr - (address)dlinfo.dli_fbase;
1331 }
1332 return true;
1333 }
1335 buf[0] = '\0';
1336 if (offset) *offset = -1;
1337 return false;
1338 }
1340 // Loads .dll/.so and
1341 // in case of error it checks if .dll/.so was built for the
1342 // same architecture as Hotspot is running on
1344 #ifdef __APPLE__
1345 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1346 void * result= ::dlopen(filename, RTLD_LAZY);
1347 if (result != NULL) {
1348 // Successful loading
1349 return result;
1350 }
1352 // Read system error message into ebuf
1353 ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1354 ebuf[ebuflen-1]='\0';
1356 return NULL;
1357 }
1358 #else
1359 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1360 {
1361 void * result= ::dlopen(filename, RTLD_LAZY);
1362 if (result != NULL) {
1363 // Successful loading
1364 return result;
1365 }
1367 Elf32_Ehdr elf_head;
1369 // Read system error message into ebuf
1370 // It may or may not be overwritten below
1371 ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1372 ebuf[ebuflen-1]='\0';
1373 int diag_msg_max_length=ebuflen-strlen(ebuf);
1374 char* diag_msg_buf=ebuf+strlen(ebuf);
1376 if (diag_msg_max_length==0) {
1377 // No more space in ebuf for additional diagnostics message
1378 return NULL;
1379 }
1382 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1384 if (file_descriptor < 0) {
1385 // Can't open library, report dlerror() message
1386 return NULL;
1387 }
1389 bool failed_to_read_elf_head=
1390 (sizeof(elf_head)!=
1391 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1393 ::close(file_descriptor);
1394 if (failed_to_read_elf_head) {
1395 // file i/o error - report dlerror() msg
1396 return NULL;
1397 }
1399 typedef struct {
1400 Elf32_Half code; // Actual value as defined in elf.h
1401 Elf32_Half compat_class; // Compatibility of archs at VM's sense
1402 char elf_class; // 32 or 64 bit
1403 char endianess; // MSB or LSB
1404 char* name; // String representation
1405 } arch_t;
1407 #ifndef EM_486
1408 #define EM_486 6 /* Intel 80486 */
1409 #endif
1411 #ifndef EM_MIPS_RS3_LE
1412 #define EM_MIPS_RS3_LE 10 /* MIPS */
1413 #endif
1415 #ifndef EM_PPC64
1416 #define EM_PPC64 21 /* PowerPC64 */
1417 #endif
1419 #ifndef EM_S390
1420 #define EM_S390 22 /* IBM System/390 */
1421 #endif
1423 #ifndef EM_IA_64
1424 #define EM_IA_64 50 /* HP/Intel IA-64 */
1425 #endif
1427 #ifndef EM_X86_64
1428 #define EM_X86_64 62 /* AMD x86-64 */
1429 #endif
1431 static const arch_t arch_array[]={
1432 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1433 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1434 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1435 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1436 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1437 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1438 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1439 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1440 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1441 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1442 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1443 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1444 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1445 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1446 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1447 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1448 };
1450 #if (defined IA32)
1451 static Elf32_Half running_arch_code=EM_386;
1452 #elif (defined AMD64)
1453 static Elf32_Half running_arch_code=EM_X86_64;
1454 #elif (defined IA64)
1455 static Elf32_Half running_arch_code=EM_IA_64;
1456 #elif (defined __sparc) && (defined _LP64)
1457 static Elf32_Half running_arch_code=EM_SPARCV9;
1458 #elif (defined __sparc) && (!defined _LP64)
1459 static Elf32_Half running_arch_code=EM_SPARC;
1460 #elif (defined __powerpc64__)
1461 static Elf32_Half running_arch_code=EM_PPC64;
1462 #elif (defined __powerpc__)
1463 static Elf32_Half running_arch_code=EM_PPC;
1464 #elif (defined ARM)
1465 static Elf32_Half running_arch_code=EM_ARM;
1466 #elif (defined S390)
1467 static Elf32_Half running_arch_code=EM_S390;
1468 #elif (defined ALPHA)
1469 static Elf32_Half running_arch_code=EM_ALPHA;
1470 #elif (defined MIPSEL)
1471 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1472 #elif (defined PARISC)
1473 static Elf32_Half running_arch_code=EM_PARISC;
1474 #elif (defined MIPS)
1475 static Elf32_Half running_arch_code=EM_MIPS;
1476 #elif (defined M68K)
1477 static Elf32_Half running_arch_code=EM_68K;
1478 #else
1479 #error Method os::dll_load requires that one of following is defined:\
1480 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1481 #endif
1483 // Identify compatability class for VM's architecture and library's architecture
1484 // Obtain string descriptions for architectures
1486 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1487 int running_arch_index=-1;
1489 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
1490 if (running_arch_code == arch_array[i].code) {
1491 running_arch_index = i;
1492 }
1493 if (lib_arch.code == arch_array[i].code) {
1494 lib_arch.compat_class = arch_array[i].compat_class;
1495 lib_arch.name = arch_array[i].name;
1496 }
1497 }
1499 assert(running_arch_index != -1,
1500 "Didn't find running architecture code (running_arch_code) in arch_array");
1501 if (running_arch_index == -1) {
1502 // Even though running architecture detection failed
1503 // we may still continue with reporting dlerror() message
1504 return NULL;
1505 }
1507 if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1508 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1509 return NULL;
1510 }
1512 #ifndef S390
1513 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1514 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1515 return NULL;
1516 }
1517 #endif // !S390
1519 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1520 if ( lib_arch.name!=NULL ) {
1521 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1522 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1523 lib_arch.name, arch_array[running_arch_index].name);
1524 } else {
1525 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1526 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1527 lib_arch.code,
1528 arch_array[running_arch_index].name);
1529 }
1530 }
1532 return NULL;
1533 }
1534 #endif /* !__APPLE__ */
1536 // XXX: Do we need a lock around this as per Linux?
1537 void* os::dll_lookup(void* handle, const char* name) {
1538 return dlsym(handle, name);
1539 }
1542 static bool _print_ascii_file(const char* filename, outputStream* st) {
1543 int fd = ::open(filename, O_RDONLY);
1544 if (fd == -1) {
1545 return false;
1546 }
1548 char buf[32];
1549 int bytes;
1550 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1551 st->print_raw(buf, bytes);
1552 }
1554 ::close(fd);
1556 return true;
1557 }
1559 void os::print_dll_info(outputStream *st) {
1560 st->print_cr("Dynamic libraries:");
1561 #ifdef RTLD_DI_LINKMAP
1562 Dl_info dli;
1563 void *handle;
1564 Link_map *map;
1565 Link_map *p;
1567 if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
1568 dli.dli_fname == NULL) {
1569 st->print_cr("Error: Cannot print dynamic libraries.");
1570 return;
1571 }
1572 handle = dlopen(dli.dli_fname, RTLD_LAZY);
1573 if (handle == NULL) {
1574 st->print_cr("Error: Cannot print dynamic libraries.");
1575 return;
1576 }
1577 dlinfo(handle, RTLD_DI_LINKMAP, &map);
1578 if (map == NULL) {
1579 st->print_cr("Error: Cannot print dynamic libraries.");
1580 return;
1581 }
1583 while (map->l_prev != NULL)
1584 map = map->l_prev;
1586 while (map != NULL) {
1587 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
1588 map = map->l_next;
1589 }
1591 dlclose(handle);
1592 #elif defined(__APPLE__)
1593 uint32_t count;
1594 uint32_t i;
1596 count = _dyld_image_count();
1597 for (i = 1; i < count; i++) {
1598 const char *name = _dyld_get_image_name(i);
1599 intptr_t slide = _dyld_get_image_vmaddr_slide(i);
1600 st->print_cr(PTR_FORMAT " \t%s", slide, name);
1601 }
1602 #else
1603 st->print_cr("Error: Cannot print dynamic libraries.");
1604 #endif
1605 }
1607 void os::print_os_info_brief(outputStream* st) {
1608 st->print("Bsd");
1610 os::Posix::print_uname_info(st);
1611 }
1613 void os::print_os_info(outputStream* st) {
1614 st->print("OS:");
1615 st->print("Bsd");
1617 os::Posix::print_uname_info(st);
1619 os::Posix::print_rlimit_info(st);
1621 os::Posix::print_load_average(st);
1622 }
1624 void os::pd_print_cpu_info(outputStream* st) {
1625 // Nothing to do for now.
1626 }
1628 void os::print_memory_info(outputStream* st) {
1630 st->print("Memory:");
1631 st->print(" %dk page", os::vm_page_size()>>10);
1633 st->print(", physical " UINT64_FORMAT "k",
1634 os::physical_memory() >> 10);
1635 st->print("(" UINT64_FORMAT "k free)",
1636 os::available_memory() >> 10);
1637 st->cr();
1639 // meminfo
1640 st->print("\n/proc/meminfo:\n");
1641 _print_ascii_file("/proc/meminfo", st);
1642 st->cr();
1643 }
1645 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific
1646 // but they're the same for all the bsd arch that we support
1647 // and they're the same for solaris but there's no common place to put this.
1648 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
1649 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
1650 "ILL_COPROC", "ILL_BADSTK" };
1652 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
1653 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
1654 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
1656 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
1658 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
1660 void os::print_siginfo(outputStream* st, void* siginfo) {
1661 st->print("siginfo:");
1663 const int buflen = 100;
1664 char buf[buflen];
1665 siginfo_t *si = (siginfo_t*)siginfo;
1666 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
1667 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
1668 st->print("si_errno=%s", buf);
1669 } else {
1670 st->print("si_errno=%d", si->si_errno);
1671 }
1672 const int c = si->si_code;
1673 assert(c > 0, "unexpected si_code");
1674 switch (si->si_signo) {
1675 case SIGILL:
1676 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
1677 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1678 break;
1679 case SIGFPE:
1680 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
1681 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1682 break;
1683 case SIGSEGV:
1684 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
1685 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1686 break;
1687 case SIGBUS:
1688 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
1689 st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1690 break;
1691 default:
1692 st->print(", si_code=%d", si->si_code);
1693 // no si_addr
1694 }
1696 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
1697 UseSharedSpaces) {
1698 FileMapInfo* mapinfo = FileMapInfo::current_info();
1699 if (mapinfo->is_in_shared_space(si->si_addr)) {
1700 st->print("\n\nError accessing class data sharing archive." \
1701 " Mapped file inaccessible during execution, " \
1702 " possible disk/network problem.");
1703 }
1704 }
1705 st->cr();
1706 }
1709 static void print_signal_handler(outputStream* st, int sig,
1710 char* buf, size_t buflen);
1712 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1713 st->print_cr("Signal Handlers:");
1714 print_signal_handler(st, SIGSEGV, buf, buflen);
1715 print_signal_handler(st, SIGBUS , buf, buflen);
1716 print_signal_handler(st, SIGFPE , buf, buflen);
1717 print_signal_handler(st, SIGPIPE, buf, buflen);
1718 print_signal_handler(st, SIGXFSZ, buf, buflen);
1719 print_signal_handler(st, SIGILL , buf, buflen);
1720 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
1721 print_signal_handler(st, SR_signum, buf, buflen);
1722 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1723 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1724 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1725 print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1726 }
1728 static char saved_jvm_path[MAXPATHLEN] = {0};
1730 // Find the full path to the current module, libjvm
1731 void os::jvm_path(char *buf, jint buflen) {
1732 // Error checking.
1733 if (buflen < MAXPATHLEN) {
1734 assert(false, "must use a large-enough buffer");
1735 buf[0] = '\0';
1736 return;
1737 }
1738 // Lazy resolve the path to current module.
1739 if (saved_jvm_path[0] != 0) {
1740 strcpy(buf, saved_jvm_path);
1741 return;
1742 }
1744 char dli_fname[MAXPATHLEN];
1745 bool ret = dll_address_to_library_name(
1746 CAST_FROM_FN_PTR(address, os::jvm_path),
1747 dli_fname, sizeof(dli_fname), NULL);
1748 assert(ret, "cannot locate libjvm");
1749 char *rp = NULL;
1750 if (ret && dli_fname[0] != '\0') {
1751 rp = realpath(dli_fname, buf);
1752 }
1753 if (rp == NULL)
1754 return;
1756 if (Arguments::created_by_gamma_launcher()) {
1757 // Support for the gamma launcher. Typical value for buf is
1758 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at
1759 // the right place in the string, then assume we are installed in a JDK and
1760 // we're done. Otherwise, check for a JAVA_HOME environment variable and
1761 // construct a path to the JVM being overridden.
1763 const char *p = buf + strlen(buf) - 1;
1764 for (int count = 0; p > buf && count < 5; ++count) {
1765 for (--p; p > buf && *p != '/'; --p)
1766 /* empty */ ;
1767 }
1769 if (strncmp(p, "/jre/lib/", 9) != 0) {
1770 // Look for JAVA_HOME in the environment.
1771 char* java_home_var = ::getenv("JAVA_HOME");
1772 if (java_home_var != NULL && java_home_var[0] != 0) {
1773 char* jrelib_p;
1774 int len;
1776 // Check the current module name "libjvm"
1777 p = strrchr(buf, '/');
1778 assert(strstr(p, "/libjvm") == p, "invalid library name");
1780 rp = realpath(java_home_var, buf);
1781 if (rp == NULL)
1782 return;
1784 // determine if this is a legacy image or modules image
1785 // modules image doesn't have "jre" subdirectory
1786 len = strlen(buf);
1787 jrelib_p = buf + len;
1789 // Add the appropriate library subdir
1790 snprintf(jrelib_p, buflen-len, "/jre/lib");
1791 if (0 != access(buf, F_OK)) {
1792 snprintf(jrelib_p, buflen-len, "/lib");
1793 }
1795 // Add the appropriate client or server subdir
1796 len = strlen(buf);
1797 jrelib_p = buf + len;
1798 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1799 if (0 != access(buf, F_OK)) {
1800 snprintf(jrelib_p, buflen-len, "");
1801 }
1803 // If the path exists within JAVA_HOME, add the JVM library name
1804 // to complete the path to JVM being overridden. Otherwise fallback
1805 // to the path to the current library.
1806 if (0 == access(buf, F_OK)) {
1807 // Use current module name "libjvm"
1808 len = strlen(buf);
1809 snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1810 } else {
1811 // Fall back to path of current library
1812 rp = realpath(dli_fname, buf);
1813 if (rp == NULL)
1814 return;
1815 }
1816 }
1817 }
1818 }
1820 strcpy(saved_jvm_path, buf);
1821 }
1823 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1824 // no prefix required, not even "_"
1825 }
1827 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1828 // no suffix required
1829 }
1831 ////////////////////////////////////////////////////////////////////////////////
1832 // sun.misc.Signal support
1834 static volatile jint sigint_count = 0;
1836 static void
1837 UserHandler(int sig, void *siginfo, void *context) {
1838 // 4511530 - sem_post is serialized and handled by the manager thread. When
1839 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
1840 // don't want to flood the manager thread with sem_post requests.
1841 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
1842 return;
1844 // Ctrl-C is pressed during error reporting, likely because the error
1845 // handler fails to abort. Let VM die immediately.
1846 if (sig == SIGINT && is_error_reported()) {
1847 os::die();
1848 }
1850 os::signal_notify(sig);
1851 }
1853 void* os::user_handler() {
1854 return CAST_FROM_FN_PTR(void*, UserHandler);
1855 }
1857 extern "C" {
1858 typedef void (*sa_handler_t)(int);
1859 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1860 }
1862 void* os::signal(int signal_number, void* handler) {
1863 struct sigaction sigAct, oldSigAct;
1865 sigfillset(&(sigAct.sa_mask));
1866 sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
1867 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1869 if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1870 // -1 means registration failed
1871 return (void *)-1;
1872 }
1874 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1875 }
1877 void os::signal_raise(int signal_number) {
1878 ::raise(signal_number);
1879 }
1881 /*
1882 * The following code is moved from os.cpp for making this
1883 * code platform specific, which it is by its very nature.
1884 */
1886 // Will be modified when max signal is changed to be dynamic
1887 int os::sigexitnum_pd() {
1888 return NSIG;
1889 }
1891 // a counter for each possible signal value
1892 static volatile jint pending_signals[NSIG+1] = { 0 };
1894 // Bsd(POSIX) specific hand shaking semaphore.
1895 #ifdef __APPLE__
1896 typedef semaphore_t os_semaphore_t;
1897 #define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
1898 #define SEM_WAIT(sem) semaphore_wait(sem)
1899 #define SEM_POST(sem) semaphore_signal(sem)
1900 #define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem)
1901 #else
1902 typedef sem_t os_semaphore_t;
1903 #define SEM_INIT(sem, value) sem_init(&sem, 0, value)
1904 #define SEM_WAIT(sem) sem_wait(&sem)
1905 #define SEM_POST(sem) sem_post(&sem)
1906 #define SEM_DESTROY(sem) sem_destroy(&sem)
1907 #endif
1909 class Semaphore : public StackObj {
1910 public:
1911 Semaphore();
1912 ~Semaphore();
1913 void signal();
1914 void wait();
1915 bool trywait();
1916 bool timedwait(unsigned int sec, int nsec);
1917 private:
1918 jlong currenttime() const;
1919 os_semaphore_t _semaphore;
1920 };
1922 Semaphore::Semaphore() : _semaphore(0) {
1923 SEM_INIT(_semaphore, 0);
1924 }
1926 Semaphore::~Semaphore() {
1927 SEM_DESTROY(_semaphore);
1928 }
1930 void Semaphore::signal() {
1931 SEM_POST(_semaphore);
1932 }
1934 void Semaphore::wait() {
1935 SEM_WAIT(_semaphore);
1936 }
1938 jlong Semaphore::currenttime() const {
1939 struct timeval tv;
1940 gettimeofday(&tv, NULL);
1941 return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
1942 }
1944 #ifdef __APPLE__
1945 bool Semaphore::trywait() {
1946 return timedwait(0, 0);
1947 }
1949 bool Semaphore::timedwait(unsigned int sec, int nsec) {
1950 kern_return_t kr = KERN_ABORTED;
1951 mach_timespec_t waitspec;
1952 waitspec.tv_sec = sec;
1953 waitspec.tv_nsec = nsec;
1955 jlong starttime = currenttime();
1957 kr = semaphore_timedwait(_semaphore, waitspec);
1958 while (kr == KERN_ABORTED) {
1959 jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
1961 jlong current = currenttime();
1962 jlong passedtime = current - starttime;
1964 if (passedtime >= totalwait) {
1965 waitspec.tv_sec = 0;
1966 waitspec.tv_nsec = 0;
1967 } else {
1968 jlong waittime = totalwait - (current - starttime);
1969 waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
1970 waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
1971 }
1973 kr = semaphore_timedwait(_semaphore, waitspec);
1974 }
1976 return kr == KERN_SUCCESS;
1977 }
1979 #else
1981 bool Semaphore::trywait() {
1982 return sem_trywait(&_semaphore) == 0;
1983 }
1985 bool Semaphore::timedwait(unsigned int sec, int nsec) {
1986 struct timespec ts;
1987 unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
1989 while (1) {
1990 int result = sem_timedwait(&_semaphore, &ts);
1991 if (result == 0) {
1992 return true;
1993 } else if (errno == EINTR) {
1994 continue;
1995 } else if (errno == ETIMEDOUT) {
1996 return false;
1997 } else {
1998 return false;
1999 }
2000 }
2001 }
2003 #endif // __APPLE__
2005 static os_semaphore_t sig_sem;
2006 static Semaphore sr_semaphore;
2008 void os::signal_init_pd() {
2009 // Initialize signal structures
2010 ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2012 // Initialize signal semaphore
2013 ::SEM_INIT(sig_sem, 0);
2014 }
2016 void os::signal_notify(int sig) {
2017 Atomic::inc(&pending_signals[sig]);
2018 ::SEM_POST(sig_sem);
2019 }
2021 static int check_pending_signals(bool wait) {
2022 Atomic::store(0, &sigint_count);
2023 for (;;) {
2024 for (int i = 0; i < NSIG + 1; i++) {
2025 jint n = pending_signals[i];
2026 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2027 return i;
2028 }
2029 }
2030 if (!wait) {
2031 return -1;
2032 }
2033 JavaThread *thread = JavaThread::current();
2034 ThreadBlockInVM tbivm(thread);
2036 bool threadIsSuspended;
2037 do {
2038 thread->set_suspend_equivalent();
2039 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2040 ::SEM_WAIT(sig_sem);
2042 // were we externally suspended while we were waiting?
2043 threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2044 if (threadIsSuspended) {
2045 //
2046 // The semaphore has been incremented, but while we were waiting
2047 // another thread suspended us. We don't want to continue running
2048 // while suspended because that would surprise the thread that
2049 // suspended us.
2050 //
2051 ::SEM_POST(sig_sem);
2053 thread->java_suspend_self();
2054 }
2055 } while (threadIsSuspended);
2056 }
2057 }
2059 int os::signal_lookup() {
2060 return check_pending_signals(false);
2061 }
2063 int os::signal_wait() {
2064 return check_pending_signals(true);
2065 }
2067 ////////////////////////////////////////////////////////////////////////////////
2068 // Virtual Memory
2070 int os::vm_page_size() {
2071 // Seems redundant as all get out
2072 assert(os::Bsd::page_size() != -1, "must call os::init");
2073 return os::Bsd::page_size();
2074 }
2076 // Solaris allocates memory by pages.
2077 int os::vm_allocation_granularity() {
2078 assert(os::Bsd::page_size() != -1, "must call os::init");
2079 return os::Bsd::page_size();
2080 }
2082 // Rationale behind this function:
2083 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2084 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2085 // samples for JITted code. Here we create private executable mapping over the code cache
2086 // and then we can use standard (well, almost, as mapping can change) way to provide
2087 // info for the reporting script by storing timestamp and location of symbol
2088 void bsd_wrap_code(char* base, size_t size) {
2089 static volatile jint cnt = 0;
2091 if (!UseOprofile) {
2092 return;
2093 }
2095 char buf[PATH_MAX + 1];
2096 int num = Atomic::add(1, &cnt);
2098 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
2099 os::get_temp_directory(), os::current_process_id(), num);
2100 unlink(buf);
2102 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2104 if (fd != -1) {
2105 off_t rv = ::lseek(fd, size-2, SEEK_SET);
2106 if (rv != (off_t)-1) {
2107 if (::write(fd, "", 1) == 1) {
2108 mmap(base, size,
2109 PROT_READ|PROT_WRITE|PROT_EXEC,
2110 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2111 }
2112 }
2113 ::close(fd);
2114 unlink(buf);
2115 }
2116 }
2118 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2119 int err) {
2120 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2121 ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
2122 strerror(err), err);
2123 }
2125 // NOTE: Bsd kernel does not really reserve the pages for us.
2126 // All it does is to check if there are enough free pages
2127 // left at the time of mmap(). This could be a potential
2128 // problem.
2129 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2130 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2131 #ifdef __OpenBSD__
2132 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2133 if (::mprotect(addr, size, prot) == 0) {
2134 return true;
2135 }
2136 #else
2137 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2138 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2139 if (res != (uintptr_t) MAP_FAILED) {
2140 return true;
2141 }
2142 #endif
2144 // Warn about any commit errors we see in non-product builds just
2145 // in case mmap() doesn't work as described on the man page.
2146 NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
2148 return false;
2149 }
2151 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2152 bool exec) {
2153 // alignment_hint is ignored on this OS
2154 return pd_commit_memory(addr, size, exec);
2155 }
2157 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2158 const char* mesg) {
2159 assert(mesg != NULL, "mesg must be specified");
2160 if (!pd_commit_memory(addr, size, exec)) {
2161 // add extra info in product mode for vm_exit_out_of_memory():
2162 PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
2163 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2164 }
2165 }
2167 void os::pd_commit_memory_or_exit(char* addr, size_t size,
2168 size_t alignment_hint, bool exec,
2169 const char* mesg) {
2170 // alignment_hint is ignored on this OS
2171 pd_commit_memory_or_exit(addr, size, exec, mesg);
2172 }
2174 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2175 }
2177 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2178 ::madvise(addr, bytes, MADV_DONTNEED);
2179 }
2181 void os::numa_make_global(char *addr, size_t bytes) {
2182 }
2184 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2185 }
2187 bool os::numa_topology_changed() { return false; }
2189 size_t os::numa_get_groups_num() {
2190 return 1;
2191 }
2193 int os::numa_get_group_id() {
2194 return 0;
2195 }
2197 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2198 if (size > 0) {
2199 ids[0] = 0;
2200 return 1;
2201 }
2202 return 0;
2203 }
2205 bool os::get_page_info(char *start, page_info* info) {
2206 return false;
2207 }
2209 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2210 return end;
2211 }
2214 bool os::pd_uncommit_memory(char* addr, size_t size) {
2215 #ifdef __OpenBSD__
2216 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2217 return ::mprotect(addr, size, PROT_NONE) == 0;
2218 #else
2219 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2220 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2221 return res != (uintptr_t) MAP_FAILED;
2222 #endif
2223 }
2225 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2226 return os::commit_memory(addr, size, !ExecMem);
2227 }
2229 // If this is a growable mapping, remove the guard pages entirely by
2230 // munmap()ping them. If not, just call uncommit_memory().
2231 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2232 return os::uncommit_memory(addr, size);
2233 }
2235 static address _highest_vm_reserved_address = NULL;
2237 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2238 // at 'requested_addr'. If there are existing memory mappings at the same
2239 // location, however, they will be overwritten. If 'fixed' is false,
2240 // 'requested_addr' is only treated as a hint, the return value may or
2241 // may not start from the requested address. Unlike Bsd mmap(), this
2242 // function returns NULL to indicate failure.
2243 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2244 char * addr;
2245 int flags;
2247 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2248 if (fixed) {
2249 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2250 flags |= MAP_FIXED;
2251 }
2253 // Map reserved/uncommitted pages PROT_NONE so we fail early if we
2254 // touch an uncommitted page. Otherwise, the read/write might
2255 // succeed if we have enough swap space to back the physical page.
2256 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
2257 flags, -1, 0);
2259 if (addr != MAP_FAILED) {
2260 // anon_mmap() should only get called during VM initialization,
2261 // don't need lock (actually we can skip locking even it can be called
2262 // from multiple threads, because _highest_vm_reserved_address is just a
2263 // hint about the upper limit of non-stack memory regions.)
2264 if ((address)addr + bytes > _highest_vm_reserved_address) {
2265 _highest_vm_reserved_address = (address)addr + bytes;
2266 }
2267 }
2269 return addr == MAP_FAILED ? NULL : addr;
2270 }
2272 // Don't update _highest_vm_reserved_address, because there might be memory
2273 // regions above addr + size. If so, releasing a memory region only creates
2274 // a hole in the address space, it doesn't help prevent heap-stack collision.
2275 //
2276 static int anon_munmap(char * addr, size_t size) {
2277 return ::munmap(addr, size) == 0;
2278 }
2280 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2281 size_t alignment_hint) {
2282 return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2283 }
2285 bool os::pd_release_memory(char* addr, size_t size) {
2286 return anon_munmap(addr, size);
2287 }
2289 static bool bsd_mprotect(char* addr, size_t size, int prot) {
2290 // Bsd wants the mprotect address argument to be page aligned.
2291 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
2293 // According to SUSv3, mprotect() should only be used with mappings
2294 // established by mmap(), and mmap() always maps whole pages. Unaligned
2295 // 'addr' likely indicates problem in the VM (e.g. trying to change
2296 // protection of malloc'ed or statically allocated memory). Check the
2297 // caller if you hit this assert.
2298 assert(addr == bottom, "sanity check");
2300 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2301 return ::mprotect(bottom, size, prot) == 0;
2302 }
2304 // Set protections specified
2305 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2306 bool is_committed) {
2307 unsigned int p = 0;
2308 switch (prot) {
2309 case MEM_PROT_NONE: p = PROT_NONE; break;
2310 case MEM_PROT_READ: p = PROT_READ; break;
2311 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
2312 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2313 default:
2314 ShouldNotReachHere();
2315 }
2316 // is_committed is unused.
2317 return bsd_mprotect(addr, bytes, p);
2318 }
2320 bool os::guard_memory(char* addr, size_t size) {
2321 return bsd_mprotect(addr, size, PROT_NONE);
2322 }
2324 bool os::unguard_memory(char* addr, size_t size) {
2325 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2326 }
2328 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2329 return false;
2330 }
2332 // Large page support
2334 static size_t _large_page_size = 0;
2336 void os::large_page_init() {
2337 }
2340 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
2341 fatal("This code is not used or maintained.");
2343 // "exec" is passed in but not used. Creating the shared image for
2344 // the code cache doesn't have an SHM_X executable permission to check.
2345 assert(UseLargePages && UseSHM, "only for SHM large pages");
2347 key_t key = IPC_PRIVATE;
2348 char *addr;
2350 bool warn_on_failure = UseLargePages &&
2351 (!FLAG_IS_DEFAULT(UseLargePages) ||
2352 !FLAG_IS_DEFAULT(LargePageSizeInBytes)
2353 );
2354 char msg[128];
2356 // Create a large shared memory region to attach to based on size.
2357 // Currently, size is the total size of the heap
2358 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
2359 if (shmid == -1) {
2360 // Possible reasons for shmget failure:
2361 // 1. shmmax is too small for Java heap.
2362 // > check shmmax value: cat /proc/sys/kernel/shmmax
2363 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
2364 // 2. not enough large page memory.
2365 // > check available large pages: cat /proc/meminfo
2366 // > increase amount of large pages:
2367 // echo new_value > /proc/sys/vm/nr_hugepages
2368 // Note 1: different Bsd may use different name for this property,
2369 // e.g. on Redhat AS-3 it is "hugetlb_pool".
2370 // Note 2: it's possible there's enough physical memory available but
2371 // they are so fragmented after a long run that they can't
2372 // coalesce into large pages. Try to reserve large pages when
2373 // the system is still "fresh".
2374 if (warn_on_failure) {
2375 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
2376 warning(msg);
2377 }
2378 return NULL;
2379 }
2381 // attach to the region
2382 addr = (char*)shmat(shmid, req_addr, 0);
2383 int err = errno;
2385 // Remove shmid. If shmat() is successful, the actual shared memory segment
2386 // will be deleted when it's detached by shmdt() or when the process
2387 // terminates. If shmat() is not successful this will remove the shared
2388 // segment immediately.
2389 shmctl(shmid, IPC_RMID, NULL);
2391 if ((intptr_t)addr == -1) {
2392 if (warn_on_failure) {
2393 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
2394 warning(msg);
2395 }
2396 return NULL;
2397 }
2399 // The memory is committed
2400 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
2402 return addr;
2403 }
2405 bool os::release_memory_special(char* base, size_t bytes) {
2406 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
2407 // detaching the SHM segment will also delete it, see reserve_memory_special()
2408 int rslt = shmdt(base);
2409 if (rslt == 0) {
2410 tkr.record((address)base, bytes);
2411 return true;
2412 } else {
2413 tkr.discard();
2414 return false;
2415 }
2417 }
2419 size_t os::large_page_size() {
2420 return _large_page_size;
2421 }
2423 // HugeTLBFS allows application to commit large page memory on demand;
2424 // with SysV SHM the entire memory region must be allocated as shared
2425 // memory.
2426 bool os::can_commit_large_page_memory() {
2427 return UseHugeTLBFS;
2428 }
2430 bool os::can_execute_large_page_memory() {
2431 return UseHugeTLBFS;
2432 }
2434 // Reserve memory at an arbitrary address, only if that area is
2435 // available (and not reserved for something else).
2437 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2438 const int max_tries = 10;
2439 char* base[max_tries];
2440 size_t size[max_tries];
2441 const size_t gap = 0x000000;
2443 // Assert only that the size is a multiple of the page size, since
2444 // that's all that mmap requires, and since that's all we really know
2445 // about at this low abstraction level. If we need higher alignment,
2446 // we can either pass an alignment to this method or verify alignment
2447 // in one of the methods further up the call chain. See bug 5044738.
2448 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2450 // Repeatedly allocate blocks until the block is allocated at the
2451 // right spot. Give up after max_tries. Note that reserve_memory() will
2452 // automatically update _highest_vm_reserved_address if the call is
2453 // successful. The variable tracks the highest memory address every reserved
2454 // by JVM. It is used to detect heap-stack collision if running with
2455 // fixed-stack BsdThreads. Because here we may attempt to reserve more
2456 // space than needed, it could confuse the collision detecting code. To
2457 // solve the problem, save current _highest_vm_reserved_address and
2458 // calculate the correct value before return.
2459 address old_highest = _highest_vm_reserved_address;
2461 // Bsd mmap allows caller to pass an address as hint; give it a try first,
2462 // if kernel honors the hint then we can return immediately.
2463 char * addr = anon_mmap(requested_addr, bytes, false);
2464 if (addr == requested_addr) {
2465 return requested_addr;
2466 }
2468 if (addr != NULL) {
2469 // mmap() is successful but it fails to reserve at the requested address
2470 anon_munmap(addr, bytes);
2471 }
2473 int i;
2474 for (i = 0; i < max_tries; ++i) {
2475 base[i] = reserve_memory(bytes);
2477 if (base[i] != NULL) {
2478 // Is this the block we wanted?
2479 if (base[i] == requested_addr) {
2480 size[i] = bytes;
2481 break;
2482 }
2484 // Does this overlap the block we wanted? Give back the overlapped
2485 // parts and try again.
2487 size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2488 if (top_overlap >= 0 && top_overlap < bytes) {
2489 unmap_memory(base[i], top_overlap);
2490 base[i] += top_overlap;
2491 size[i] = bytes - top_overlap;
2492 } else {
2493 size_t bottom_overlap = base[i] + bytes - requested_addr;
2494 if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2495 unmap_memory(requested_addr, bottom_overlap);
2496 size[i] = bytes - bottom_overlap;
2497 } else {
2498 size[i] = bytes;
2499 }
2500 }
2501 }
2502 }
2504 // Give back the unused reserved pieces.
2506 for (int j = 0; j < i; ++j) {
2507 if (base[j] != NULL) {
2508 unmap_memory(base[j], size[j]);
2509 }
2510 }
2512 if (i < max_tries) {
2513 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
2514 return requested_addr;
2515 } else {
2516 _highest_vm_reserved_address = old_highest;
2517 return NULL;
2518 }
2519 }
2521 size_t os::read(int fd, void *buf, unsigned int nBytes) {
2522 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
2523 }
2525 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
2526 // Solaris uses poll(), bsd uses park().
2527 // Poll() is likely a better choice, assuming that Thread.interrupt()
2528 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
2529 // SIGSEGV, see 4355769.
2531 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
2532 assert(thread == Thread::current(), "thread consistency check");
2534 ParkEvent * const slp = thread->_SleepEvent ;
2535 slp->reset() ;
2536 OrderAccess::fence() ;
2538 if (interruptible) {
2539 jlong prevtime = javaTimeNanos();
2541 for (;;) {
2542 if (os::is_interrupted(thread, true)) {
2543 return OS_INTRPT;
2544 }
2546 jlong newtime = javaTimeNanos();
2548 if (newtime - prevtime < 0) {
2549 // time moving backwards, should only happen if no monotonic clock
2550 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2551 assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2552 } else {
2553 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2554 }
2556 if(millis <= 0) {
2557 return OS_OK;
2558 }
2560 prevtime = newtime;
2562 {
2563 assert(thread->is_Java_thread(), "sanity check");
2564 JavaThread *jt = (JavaThread *) thread;
2565 ThreadBlockInVM tbivm(jt);
2566 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
2568 jt->set_suspend_equivalent();
2569 // cleared by handle_special_suspend_equivalent_condition() or
2570 // java_suspend_self() via check_and_wait_while_suspended()
2572 slp->park(millis);
2574 // were we externally suspended while we were waiting?
2575 jt->check_and_wait_while_suspended();
2576 }
2577 }
2578 } else {
2579 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
2580 jlong prevtime = javaTimeNanos();
2582 for (;;) {
2583 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
2584 // the 1st iteration ...
2585 jlong newtime = javaTimeNanos();
2587 if (newtime - prevtime < 0) {
2588 // time moving backwards, should only happen if no monotonic clock
2589 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2590 assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2591 } else {
2592 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2593 }
2595 if(millis <= 0) break ;
2597 prevtime = newtime;
2598 slp->park(millis);
2599 }
2600 return OS_OK ;
2601 }
2602 }
2604 int os::naked_sleep() {
2605 // %% make the sleep time an integer flag. for now use 1 millisec.
2606 return os::sleep(Thread::current(), 1, false);
2607 }
2609 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2610 void os::infinite_sleep() {
2611 while (true) { // sleep forever ...
2612 ::sleep(100); // ... 100 seconds at a time
2613 }
2614 }
2616 // Used to convert frequent JVM_Yield() to nops
2617 bool os::dont_yield() {
2618 return DontYieldALot;
2619 }
2621 void os::yield() {
2622 sched_yield();
2623 }
2625 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
2627 void os::yield_all(int attempts) {
2628 // Yields to all threads, including threads with lower priorities
2629 // Threads on Bsd are all with same priority. The Solaris style
2630 // os::yield_all() with nanosleep(1ms) is not necessary.
2631 sched_yield();
2632 }
2634 // Called from the tight loops to possibly influence time-sharing heuristics
2635 void os::loop_breaker(int attempts) {
2636 os::yield_all(attempts);
2637 }
2639 ////////////////////////////////////////////////////////////////////////////////
2640 // thread priority support
2642 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2643 // only supports dynamic priority, static priority must be zero. For real-time
2644 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2645 // However, for large multi-threaded applications, SCHED_RR is not only slower
2646 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2647 // of 5 runs - Sep 2005).
2648 //
2649 // The following code actually changes the niceness of kernel-thread/LWP. It
2650 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2651 // not the entire user process, and user level threads are 1:1 mapped to kernel
2652 // threads. It has always been the case, but could change in the future. For
2653 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2654 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
2656 #if !defined(__APPLE__)
2657 int os::java_to_os_priority[CriticalPriority + 1] = {
2658 19, // 0 Entry should never be used
2660 0, // 1 MinPriority
2661 3, // 2
2662 6, // 3
2664 10, // 4
2665 15, // 5 NormPriority
2666 18, // 6
2668 21, // 7
2669 25, // 8
2670 28, // 9 NearMaxPriority
2672 31, // 10 MaxPriority
2674 31 // 11 CriticalPriority
2675 };
2676 #else
2677 /* Using Mach high-level priority assignments */
2678 int os::java_to_os_priority[CriticalPriority + 1] = {
2679 0, // 0 Entry should never be used (MINPRI_USER)
2681 27, // 1 MinPriority
2682 28, // 2
2683 29, // 3
2685 30, // 4
2686 31, // 5 NormPriority (BASEPRI_DEFAULT)
2687 32, // 6
2689 33, // 7
2690 34, // 8
2691 35, // 9 NearMaxPriority
2693 36, // 10 MaxPriority
2695 36 // 11 CriticalPriority
2696 };
2697 #endif
2699 static int prio_init() {
2700 if (ThreadPriorityPolicy == 1) {
2701 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
2702 // if effective uid is not root. Perhaps, a more elegant way of doing
2703 // this is to test CAP_SYS_NICE capability, but that will require libcap.so
2704 if (geteuid() != 0) {
2705 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
2706 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
2707 }
2708 ThreadPriorityPolicy = 0;
2709 }
2710 }
2711 if (UseCriticalJavaThreadPriority) {
2712 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2713 }
2714 return 0;
2715 }
2717 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2718 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
2720 #ifdef __OpenBSD__
2721 // OpenBSD pthread_setprio starves low priority threads
2722 return OS_OK;
2723 #elif defined(__FreeBSD__)
2724 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2725 #elif defined(__APPLE__) || defined(__NetBSD__)
2726 struct sched_param sp;
2727 int policy;
2728 pthread_t self = pthread_self();
2730 if (pthread_getschedparam(self, &policy, &sp) != 0)
2731 return OS_ERR;
2733 sp.sched_priority = newpri;
2734 if (pthread_setschedparam(self, policy, &sp) != 0)
2735 return OS_ERR;
2737 return OS_OK;
2738 #else
2739 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2740 return (ret == 0) ? OS_OK : OS_ERR;
2741 #endif
2742 }
2744 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2745 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
2746 *priority_ptr = java_to_os_priority[NormPriority];
2747 return OS_OK;
2748 }
2750 errno = 0;
2751 #if defined(__OpenBSD__) || defined(__FreeBSD__)
2752 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2753 #elif defined(__APPLE__) || defined(__NetBSD__)
2754 int policy;
2755 struct sched_param sp;
2757 pthread_getschedparam(pthread_self(), &policy, &sp);
2758 *priority_ptr = sp.sched_priority;
2759 #else
2760 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2761 #endif
2762 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2763 }
2765 // Hint to the underlying OS that a task switch would not be good.
2766 // Void return because it's a hint and can fail.
2767 void os::hint_no_preempt() {}
2769 ////////////////////////////////////////////////////////////////////////////////
2770 // suspend/resume support
2772 // the low-level signal-based suspend/resume support is a remnant from the
2773 // old VM-suspension that used to be for java-suspension, safepoints etc,
2774 // within hotspot. Now there is a single use-case for this:
2775 // - calling get_thread_pc() on the VMThread by the flat-profiler task
2776 // that runs in the watcher thread.
2777 // The remaining code is greatly simplified from the more general suspension
2778 // code that used to be used.
2779 //
2780 // The protocol is quite simple:
2781 // - suspend:
2782 // - sends a signal to the target thread
2783 // - polls the suspend state of the osthread using a yield loop
2784 // - target thread signal handler (SR_handler) sets suspend state
2785 // and blocks in sigsuspend until continued
2786 // - resume:
2787 // - sets target osthread state to continue
2788 // - sends signal to end the sigsuspend loop in the SR_handler
2789 //
2790 // Note that the SR_lock plays no role in this suspend/resume protocol.
2791 //
2793 static void resume_clear_context(OSThread *osthread) {
2794 osthread->set_ucontext(NULL);
2795 osthread->set_siginfo(NULL);
2796 }
2798 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2799 osthread->set_ucontext(context);
2800 osthread->set_siginfo(siginfo);
2801 }
2803 //
2804 // Handler function invoked when a thread's execution is suspended or
2805 // resumed. We have to be careful that only async-safe functions are
2806 // called here (Note: most pthread functions are not async safe and
2807 // should be avoided.)
2808 //
2809 // Note: sigwait() is a more natural fit than sigsuspend() from an
2810 // interface point of view, but sigwait() prevents the signal hander
2811 // from being run. libpthread would get very confused by not having
2812 // its signal handlers run and prevents sigwait()'s use with the
2813 // mutex granting granting signal.
2814 //
2815 // Currently only ever called on the VMThread or JavaThread
2816 //
2817 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2818 // Save and restore errno to avoid confusing native code with EINTR
2819 // after sigsuspend.
2820 int old_errno = errno;
2822 Thread* thread = Thread::current();
2823 OSThread* osthread = thread->osthread();
2824 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
2826 os::SuspendResume::State current = osthread->sr.state();
2827 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
2828 suspend_save_context(osthread, siginfo, context);
2830 // attempt to switch the state, we assume we had a SUSPEND_REQUEST
2831 os::SuspendResume::State state = osthread->sr.suspended();
2832 if (state == os::SuspendResume::SR_SUSPENDED) {
2833 sigset_t suspend_set; // signals for sigsuspend()
2835 // get current set of blocked signals and unblock resume signal
2836 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2837 sigdelset(&suspend_set, SR_signum);
2839 sr_semaphore.signal();
2840 // wait here until we are resumed
2841 while (1) {
2842 sigsuspend(&suspend_set);
2844 os::SuspendResume::State result = osthread->sr.running();
2845 if (result == os::SuspendResume::SR_RUNNING) {
2846 sr_semaphore.signal();
2847 break;
2848 } else if (result != os::SuspendResume::SR_SUSPENDED) {
2849 ShouldNotReachHere();
2850 }
2851 }
2853 } else if (state == os::SuspendResume::SR_RUNNING) {
2854 // request was cancelled, continue
2855 } else {
2856 ShouldNotReachHere();
2857 }
2859 resume_clear_context(osthread);
2860 } else if (current == os::SuspendResume::SR_RUNNING) {
2861 // request was cancelled, continue
2862 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
2863 // ignore
2864 } else {
2865 // ignore
2866 }
2868 errno = old_errno;
2869 }
2872 static int SR_initialize() {
2873 struct sigaction act;
2874 char *s;
2875 /* Get signal number to use for suspend/resume */
2876 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2877 int sig = ::strtol(s, 0, 10);
2878 if (sig > 0 || sig < NSIG) {
2879 SR_signum = sig;
2880 }
2881 }
2883 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2884 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2886 sigemptyset(&SR_sigset);
2887 sigaddset(&SR_sigset, SR_signum);
2889 /* Set up signal handler for suspend/resume */
2890 act.sa_flags = SA_RESTART|SA_SIGINFO;
2891 act.sa_handler = (void (*)(int)) SR_handler;
2893 // SR_signum is blocked by default.
2894 // 4528190 - We also need to block pthread restart signal (32 on all
2895 // supported Bsd platforms). Note that BsdThreads need to block
2896 // this signal for all threads to work properly. So we don't have
2897 // to use hard-coded signal number when setting up the mask.
2898 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2900 if (sigaction(SR_signum, &act, 0) == -1) {
2901 return -1;
2902 }
2904 // Save signal flag
2905 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2906 return 0;
2907 }
2909 static int sr_notify(OSThread* osthread) {
2910 int status = pthread_kill(osthread->pthread_id(), SR_signum);
2911 assert_status(status == 0, status, "pthread_kill");
2912 return status;
2913 }
2915 // "Randomly" selected value for how long we want to spin
2916 // before bailing out on suspending a thread, also how often
2917 // we send a signal to a thread we want to resume
2918 static const int RANDOMLY_LARGE_INTEGER = 1000000;
2919 static const int RANDOMLY_LARGE_INTEGER2 = 100;
2921 // returns true on success and false on error - really an error is fatal
2922 // but this seems the normal response to library errors
2923 static bool do_suspend(OSThread* osthread) {
2924 assert(osthread->sr.is_running(), "thread should be running");
2925 assert(!sr_semaphore.trywait(), "semaphore has invalid state");
2927 // mark as suspended and send signal
2928 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
2929 // failed to switch, state wasn't running?
2930 ShouldNotReachHere();
2931 return false;
2932 }
2934 if (sr_notify(osthread) != 0) {
2935 ShouldNotReachHere();
2936 }
2938 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
2939 while (true) {
2940 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2941 break;
2942 } else {
2943 // timeout
2944 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
2945 if (cancelled == os::SuspendResume::SR_RUNNING) {
2946 return false;
2947 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
2948 // make sure that we consume the signal on the semaphore as well
2949 sr_semaphore.wait();
2950 break;
2951 } else {
2952 ShouldNotReachHere();
2953 return false;
2954 }
2955 }
2956 }
2958 guarantee(osthread->sr.is_suspended(), "Must be suspended");
2959 return true;
2960 }
2962 static void do_resume(OSThread* osthread) {
2963 assert(osthread->sr.is_suspended(), "thread should be suspended");
2964 assert(!sr_semaphore.trywait(), "invalid semaphore state");
2966 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
2967 // failed to switch to WAKEUP_REQUEST
2968 ShouldNotReachHere();
2969 return;
2970 }
2972 while (true) {
2973 if (sr_notify(osthread) == 0) {
2974 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2975 if (osthread->sr.is_running()) {
2976 return;
2977 }
2978 }
2979 } else {
2980 ShouldNotReachHere();
2981 }
2982 }
2984 guarantee(osthread->sr.is_running(), "Must be running!");
2985 }
2987 ////////////////////////////////////////////////////////////////////////////////
2988 // interrupt support
2990 void os::interrupt(Thread* thread) {
2991 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
2992 "possibility of dangling Thread pointer");
2994 OSThread* osthread = thread->osthread();
2996 if (!osthread->interrupted()) {
2997 osthread->set_interrupted(true);
2998 // More than one thread can get here with the same value of osthread,
2999 // resulting in multiple notifications. We do, however, want the store
3000 // to interrupted() to be visible to other threads before we execute unpark().
3001 OrderAccess::fence();
3002 ParkEvent * const slp = thread->_SleepEvent ;
3003 if (slp != NULL) slp->unpark() ;
3004 }
3006 // For JSR166. Unpark even if interrupt status already was set
3007 if (thread->is_Java_thread())
3008 ((JavaThread*)thread)->parker()->unpark();
3010 ParkEvent * ev = thread->_ParkEvent ;
3011 if (ev != NULL) ev->unpark() ;
3013 }
3015 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
3016 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3017 "possibility of dangling Thread pointer");
3019 OSThread* osthread = thread->osthread();
3021 bool interrupted = osthread->interrupted();
3023 if (interrupted && clear_interrupted) {
3024 osthread->set_interrupted(false);
3025 // consider thread->_SleepEvent->reset() ... optional optimization
3026 }
3028 return interrupted;
3029 }
3031 ///////////////////////////////////////////////////////////////////////////////////
3032 // signal handling (except suspend/resume)
3034 // This routine may be used by user applications as a "hook" to catch signals.
3035 // The user-defined signal handler must pass unrecognized signals to this
3036 // routine, and if it returns true (non-zero), then the signal handler must
3037 // return immediately. If the flag "abort_if_unrecognized" is true, then this
3038 // routine will never retun false (zero), but instead will execute a VM panic
3039 // routine kill the process.
3040 //
3041 // If this routine returns false, it is OK to call it again. This allows
3042 // the user-defined signal handler to perform checks either before or after
3043 // the VM performs its own checks. Naturally, the user code would be making
3044 // a serious error if it tried to handle an exception (such as a null check
3045 // or breakpoint) that the VM was generating for its own correct operation.
3046 //
3047 // This routine may recognize any of the following kinds of signals:
3048 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
3049 // It should be consulted by handlers for any of those signals.
3050 //
3051 // The caller of this routine must pass in the three arguments supplied
3052 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
3053 // field of the structure passed to sigaction(). This routine assumes that
3054 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3055 //
3056 // Note that the VM will print warnings if it detects conflicting signal
3057 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3058 //
3059 extern "C" JNIEXPORT int
3060 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
3061 void* ucontext, int abort_if_unrecognized);
3063 void signalHandler(int sig, siginfo_t* info, void* uc) {
3064 assert(info != NULL && uc != NULL, "it must be old kernel");
3065 int orig_errno = errno; // Preserve errno value over signal handler.
3066 JVM_handle_bsd_signal(sig, info, uc, true);
3067 errno = orig_errno;
3068 }
3071 // This boolean allows users to forward their own non-matching signals
3072 // to JVM_handle_bsd_signal, harmlessly.
3073 bool os::Bsd::signal_handlers_are_installed = false;
3075 // For signal-chaining
3076 struct sigaction os::Bsd::sigact[MAXSIGNUM];
3077 unsigned int os::Bsd::sigs = 0;
3078 bool os::Bsd::libjsig_is_loaded = false;
3079 typedef struct sigaction *(*get_signal_t)(int);
3080 get_signal_t os::Bsd::get_signal_action = NULL;
3082 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
3083 struct sigaction *actp = NULL;
3085 if (libjsig_is_loaded) {
3086 // Retrieve the old signal handler from libjsig
3087 actp = (*get_signal_action)(sig);
3088 }
3089 if (actp == NULL) {
3090 // Retrieve the preinstalled signal handler from jvm
3091 actp = get_preinstalled_handler(sig);
3092 }
3094 return actp;
3095 }
3097 static bool call_chained_handler(struct sigaction *actp, int sig,
3098 siginfo_t *siginfo, void *context) {
3099 // Call the old signal handler
3100 if (actp->sa_handler == SIG_DFL) {
3101 // It's more reasonable to let jvm treat it as an unexpected exception
3102 // instead of taking the default action.
3103 return false;
3104 } else if (actp->sa_handler != SIG_IGN) {
3105 if ((actp->sa_flags & SA_NODEFER) == 0) {
3106 // automaticlly block the signal
3107 sigaddset(&(actp->sa_mask), sig);
3108 }
3110 sa_handler_t hand;
3111 sa_sigaction_t sa;
3112 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3113 // retrieve the chained handler
3114 if (siginfo_flag_set) {
3115 sa = actp->sa_sigaction;
3116 } else {
3117 hand = actp->sa_handler;
3118 }
3120 if ((actp->sa_flags & SA_RESETHAND) != 0) {
3121 actp->sa_handler = SIG_DFL;
3122 }
3124 // try to honor the signal mask
3125 sigset_t oset;
3126 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3128 // call into the chained handler
3129 if (siginfo_flag_set) {
3130 (*sa)(sig, siginfo, context);
3131 } else {
3132 (*hand)(sig);
3133 }
3135 // restore the signal mask
3136 pthread_sigmask(SIG_SETMASK, &oset, 0);
3137 }
3138 // Tell jvm's signal handler the signal is taken care of.
3139 return true;
3140 }
3142 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3143 bool chained = false;
3144 // signal-chaining
3145 if (UseSignalChaining) {
3146 struct sigaction *actp = get_chained_signal_action(sig);
3147 if (actp != NULL) {
3148 chained = call_chained_handler(actp, sig, siginfo, context);
3149 }
3150 }
3151 return chained;
3152 }
3154 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
3155 if ((( (unsigned int)1 << sig ) & sigs) != 0) {
3156 return &sigact[sig];
3157 }
3158 return NULL;
3159 }
3161 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
3162 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3163 sigact[sig] = oldAct;
3164 sigs |= (unsigned int)1 << sig;
3165 }
3167 // for diagnostic
3168 int os::Bsd::sigflags[MAXSIGNUM];
3170 int os::Bsd::get_our_sigflags(int sig) {
3171 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3172 return sigflags[sig];
3173 }
3175 void os::Bsd::set_our_sigflags(int sig, int flags) {
3176 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3177 sigflags[sig] = flags;
3178 }
3180 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
3181 // Check for overwrite.
3182 struct sigaction oldAct;
3183 sigaction(sig, (struct sigaction*)NULL, &oldAct);
3185 void* oldhand = oldAct.sa_sigaction
3186 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3187 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3188 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3189 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3190 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
3191 if (AllowUserSignalHandlers || !set_installed) {
3192 // Do not overwrite; user takes responsibility to forward to us.
3193 return;
3194 } else if (UseSignalChaining) {
3195 // save the old handler in jvm
3196 save_preinstalled_handler(sig, oldAct);
3197 // libjsig also interposes the sigaction() call below and saves the
3198 // old sigaction on it own.
3199 } else {
3200 fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
3201 "%#lx for signal %d.", (long)oldhand, sig));
3202 }
3203 }
3205 struct sigaction sigAct;
3206 sigfillset(&(sigAct.sa_mask));
3207 sigAct.sa_handler = SIG_DFL;
3208 if (!set_installed) {
3209 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3210 } else {
3211 sigAct.sa_sigaction = signalHandler;
3212 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3213 }
3214 #if __APPLE__
3215 // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
3216 // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
3217 // if the signal handler declares it will handle it on alternate stack.
3218 // Notice we only declare we will handle it on alt stack, but we are not
3219 // actually going to use real alt stack - this is just a workaround.
3220 // Please see ux_exception.c, method catch_mach_exception_raise for details
3221 // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
3222 if (sig == SIGSEGV) {
3223 sigAct.sa_flags |= SA_ONSTACK;
3224 }
3225 #endif
3227 // Save flags, which are set by ours
3228 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3229 sigflags[sig] = sigAct.sa_flags;
3231 int ret = sigaction(sig, &sigAct, &oldAct);
3232 assert(ret == 0, "check");
3234 void* oldhand2 = oldAct.sa_sigaction
3235 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3236 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3237 assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3238 }
3240 // install signal handlers for signals that HotSpot needs to
3241 // handle in order to support Java-level exception handling.
3243 void os::Bsd::install_signal_handlers() {
3244 if (!signal_handlers_are_installed) {
3245 signal_handlers_are_installed = true;
3247 // signal-chaining
3248 typedef void (*signal_setting_t)();
3249 signal_setting_t begin_signal_setting = NULL;
3250 signal_setting_t end_signal_setting = NULL;
3251 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3252 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
3253 if (begin_signal_setting != NULL) {
3254 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3255 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
3256 get_signal_action = CAST_TO_FN_PTR(get_signal_t,
3257 dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
3258 libjsig_is_loaded = true;
3259 assert(UseSignalChaining, "should enable signal-chaining");
3260 }
3261 if (libjsig_is_loaded) {
3262 // Tell libjsig jvm is setting signal handlers
3263 (*begin_signal_setting)();
3264 }
3266 set_signal_handler(SIGSEGV, true);
3267 set_signal_handler(SIGPIPE, true);
3268 set_signal_handler(SIGBUS, true);
3269 set_signal_handler(SIGILL, true);
3270 set_signal_handler(SIGFPE, true);
3271 set_signal_handler(SIGXFSZ, true);
3273 #if defined(__APPLE__)
3274 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
3275 // signals caught and handled by the JVM. To work around this, we reset the mach task
3276 // signal handler that's placed on our process by CrashReporter. This disables
3277 // CrashReporter-based reporting.
3278 //
3279 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
3280 // on caught fatal signals.
3281 //
3282 // Additionally, gdb installs both standard BSD signal handlers, and mach exception
3283 // handlers. By replacing the existing task exception handler, we disable gdb's mach
3284 // exception handling, while leaving the standard BSD signal handlers functional.
3285 kern_return_t kr;
3286 kr = task_set_exception_ports(mach_task_self(),
3287 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
3288 MACH_PORT_NULL,
3289 EXCEPTION_STATE_IDENTITY,
3290 MACHINE_THREAD_STATE);
3292 assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
3293 #endif
3295 if (libjsig_is_loaded) {
3296 // Tell libjsig jvm finishes setting signal handlers
3297 (*end_signal_setting)();
3298 }
3300 // We don't activate signal checker if libjsig is in place, we trust ourselves
3301 // and if UserSignalHandler is installed all bets are off
3302 if (CheckJNICalls) {
3303 if (libjsig_is_loaded) {
3304 if (PrintJNIResolving) {
3305 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
3306 }
3307 check_signals = false;
3308 }
3309 if (AllowUserSignalHandlers) {
3310 if (PrintJNIResolving) {
3311 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
3312 }
3313 check_signals = false;
3314 }
3315 }
3316 }
3317 }
3320 /////
3321 // glibc on Bsd platform uses non-documented flag
3322 // to indicate, that some special sort of signal
3323 // trampoline is used.
3324 // We will never set this flag, and we should
3325 // ignore this flag in our diagnostic
3326 #ifdef SIGNIFICANT_SIGNAL_MASK
3327 #undef SIGNIFICANT_SIGNAL_MASK
3328 #endif
3329 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
3331 static const char* get_signal_handler_name(address handler,
3332 char* buf, int buflen) {
3333 int offset;
3334 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
3335 if (found) {
3336 // skip directory names
3337 const char *p1, *p2;
3338 p1 = buf;
3339 size_t len = strlen(os::file_separator());
3340 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
3341 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
3342 } else {
3343 jio_snprintf(buf, buflen, PTR_FORMAT, handler);
3344 }
3345 return buf;
3346 }
3348 static void print_signal_handler(outputStream* st, int sig,
3349 char* buf, size_t buflen) {
3350 struct sigaction sa;
3352 sigaction(sig, NULL, &sa);
3354 // See comment for SIGNIFICANT_SIGNAL_MASK define
3355 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3357 st->print("%s: ", os::exception_name(sig, buf, buflen));
3359 address handler = (sa.sa_flags & SA_SIGINFO)
3360 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
3361 : CAST_FROM_FN_PTR(address, sa.sa_handler);
3363 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
3364 st->print("SIG_DFL");
3365 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
3366 st->print("SIG_IGN");
3367 } else {
3368 st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
3369 }
3371 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
3373 address rh = VMError::get_resetted_sighandler(sig);
3374 // May be, handler was resetted by VMError?
3375 if(rh != NULL) {
3376 handler = rh;
3377 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
3378 }
3380 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags);
3382 // Check: is it our handler?
3383 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
3384 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
3385 // It is our signal handler
3386 // check for flags, reset system-used one!
3387 if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3388 st->print(
3389 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
3390 os::Bsd::get_our_sigflags(sig));
3391 }
3392 }
3393 st->cr();
3394 }
3397 #define DO_SIGNAL_CHECK(sig) \
3398 if (!sigismember(&check_signal_done, sig)) \
3399 os::Bsd::check_signal_handler(sig)
3401 // This method is a periodic task to check for misbehaving JNI applications
3402 // under CheckJNI, we can add any periodic checks here
3404 void os::run_periodic_checks() {
3406 if (check_signals == false) return;
3408 // SEGV and BUS if overridden could potentially prevent
3409 // generation of hs*.log in the event of a crash, debugging
3410 // such a case can be very challenging, so we absolutely
3411 // check the following for a good measure:
3412 DO_SIGNAL_CHECK(SIGSEGV);
3413 DO_SIGNAL_CHECK(SIGILL);
3414 DO_SIGNAL_CHECK(SIGFPE);
3415 DO_SIGNAL_CHECK(SIGBUS);
3416 DO_SIGNAL_CHECK(SIGPIPE);
3417 DO_SIGNAL_CHECK(SIGXFSZ);
3420 // ReduceSignalUsage allows the user to override these handlers
3421 // see comments at the very top and jvm_solaris.h
3422 if (!ReduceSignalUsage) {
3423 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3424 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3425 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3426 DO_SIGNAL_CHECK(BREAK_SIGNAL);
3427 }
3429 DO_SIGNAL_CHECK(SR_signum);
3430 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
3431 }
3433 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3435 static os_sigaction_t os_sigaction = NULL;
3437 void os::Bsd::check_signal_handler(int sig) {
3438 char buf[O_BUFLEN];
3439 address jvmHandler = NULL;
3442 struct sigaction act;
3443 if (os_sigaction == NULL) {
3444 // only trust the default sigaction, in case it has been interposed
3445 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3446 if (os_sigaction == NULL) return;
3447 }
3449 os_sigaction(sig, (struct sigaction*)NULL, &act);
3452 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3454 address thisHandler = (act.sa_flags & SA_SIGINFO)
3455 ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3456 : CAST_FROM_FN_PTR(address, act.sa_handler) ;
3459 switch(sig) {
3460 case SIGSEGV:
3461 case SIGBUS:
3462 case SIGFPE:
3463 case SIGPIPE:
3464 case SIGILL:
3465 case SIGXFSZ:
3466 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3467 break;
3469 case SHUTDOWN1_SIGNAL:
3470 case SHUTDOWN2_SIGNAL:
3471 case SHUTDOWN3_SIGNAL:
3472 case BREAK_SIGNAL:
3473 jvmHandler = (address)user_handler();
3474 break;
3476 case INTERRUPT_SIGNAL:
3477 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
3478 break;
3480 default:
3481 if (sig == SR_signum) {
3482 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3483 } else {
3484 return;
3485 }
3486 break;
3487 }
3489 if (thisHandler != jvmHandler) {
3490 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3491 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3492 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3493 // No need to check this sig any longer
3494 sigaddset(&check_signal_done, sig);
3495 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3496 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3497 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
3498 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);
3499 // No need to check this sig any longer
3500 sigaddset(&check_signal_done, sig);
3501 }
3503 // Dump all the signal
3504 if (sigismember(&check_signal_done, sig)) {
3505 print_signal_handlers(tty, buf, O_BUFLEN);
3506 }
3507 }
3509 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
3511 extern bool signal_name(int signo, char* buf, size_t len);
3513 const char* os::exception_name(int exception_code, char* buf, size_t size) {
3514 if (0 < exception_code && exception_code <= SIGRTMAX) {
3515 // signal
3516 if (!signal_name(exception_code, buf, size)) {
3517 jio_snprintf(buf, size, "SIG%d", exception_code);
3518 }
3519 return buf;
3520 } else {
3521 return NULL;
3522 }
3523 }
3525 // this is called _before_ the most of global arguments have been parsed
3526 void os::init(void) {
3527 char dummy; /* used to get a guess on initial stack address */
3528 // first_hrtime = gethrtime();
3530 // With BsdThreads the JavaMain thread pid (primordial thread)
3531 // is different than the pid of the java launcher thread.
3532 // So, on Bsd, the launcher thread pid is passed to the VM
3533 // via the sun.java.launcher.pid property.
3534 // Use this property instead of getpid() if it was correctly passed.
3535 // See bug 6351349.
3536 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
3538 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
3540 clock_tics_per_sec = CLK_TCK;
3542 init_random(1234567);
3544 ThreadCritical::initialize();
3546 Bsd::set_page_size(getpagesize());
3547 if (Bsd::page_size() == -1) {
3548 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
3549 strerror(errno)));
3550 }
3551 init_page_sizes((size_t) Bsd::page_size());
3553 Bsd::initialize_system_info();
3555 // main_thread points to the aboriginal thread
3556 Bsd::_main_thread = pthread_self();
3558 Bsd::clock_init();
3559 initial_time_count = os::elapsed_counter();
3561 #ifdef __APPLE__
3562 // XXXDARWIN
3563 // Work around the unaligned VM callbacks in hotspot's
3564 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
3565 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
3566 // alignment when doing symbol lookup. To work around this, we force early
3567 // binding of all symbols now, thus binding when alignment is known-good.
3568 _dyld_bind_fully_image_containing_address((const void *) &os::init);
3569 #endif
3570 }
3572 // To install functions for atexit system call
3573 extern "C" {
3574 static void perfMemory_exit_helper() {
3575 perfMemory_exit();
3576 }
3577 }
3579 // this is called _after_ the global arguments have been parsed
3580 jint os::init_2(void)
3581 {
3582 // Allocate a single page and mark it as readable for safepoint polling
3583 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3584 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
3586 os::set_polling_page( polling_page );
3588 #ifndef PRODUCT
3589 if(Verbose && PrintMiscellaneous)
3590 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
3591 #endif
3593 if (!UseMembar) {
3594 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3595 guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
3596 os::set_memory_serialize_page( mem_serialize_page );
3598 #ifndef PRODUCT
3599 if(Verbose && PrintMiscellaneous)
3600 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
3601 #endif
3602 }
3604 // initialize suspend/resume support - must do this before signal_sets_init()
3605 if (SR_initialize() != 0) {
3606 perror("SR_initialize failed");
3607 return JNI_ERR;
3608 }
3610 Bsd::signal_sets_init();
3611 Bsd::install_signal_handlers();
3613 // Check minimum allowable stack size for thread creation and to initialize
3614 // the java system classes, including StackOverflowError - depends on page
3615 // size. Add a page for compiler2 recursion in main thread.
3616 // Add in 2*BytesPerWord times page size to account for VM stack during
3617 // class initialization depending on 32 or 64 bit VM.
3618 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
3619 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
3620 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
3622 size_t threadStackSizeInBytes = ThreadStackSize * K;
3623 if (threadStackSizeInBytes != 0 &&
3624 threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
3625 tty->print_cr("\nThe stack size specified is too small, "
3626 "Specify at least %dk",
3627 os::Bsd::min_stack_allowed/ K);
3628 return JNI_ERR;
3629 }
3631 // Make the stack size a multiple of the page size so that
3632 // the yellow/red zones can be guarded.
3633 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
3634 vm_page_size()));
3636 if (MaxFDLimit) {
3637 // set the number of file descriptors to max. print out error
3638 // if getrlimit/setrlimit fails but continue regardless.
3639 struct rlimit nbr_files;
3640 int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3641 if (status != 0) {
3642 if (PrintMiscellaneous && (Verbose || WizardMode))
3643 perror("os::init_2 getrlimit failed");
3644 } else {
3645 nbr_files.rlim_cur = nbr_files.rlim_max;
3647 #ifdef __APPLE__
3648 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3649 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3650 // be used instead
3651 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3652 #endif
3654 status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3655 if (status != 0) {
3656 if (PrintMiscellaneous && (Verbose || WizardMode))
3657 perror("os::init_2 setrlimit failed");
3658 }
3659 }
3660 }
3662 // at-exit methods are called in the reverse order of their registration.
3663 // atexit functions are called on return from main or as a result of a
3664 // call to exit(3C). There can be only 32 of these functions registered
3665 // and atexit() does not set errno.
3667 if (PerfAllowAtExitRegistration) {
3668 // only register atexit functions if PerfAllowAtExitRegistration is set.
3669 // atexit functions can be delayed until process exit time, which
3670 // can be problematic for embedded VM situations. Embedded VMs should
3671 // call DestroyJavaVM() to assure that VM resources are released.
3673 // note: perfMemory_exit_helper atexit function may be removed in
3674 // the future if the appropriate cleanup code can be added to the
3675 // VM_Exit VMOperation's doit method.
3676 if (atexit(perfMemory_exit_helper) != 0) {
3677 warning("os::init2 atexit(perfMemory_exit_helper) failed");
3678 }
3679 }
3681 // initialize thread priority policy
3682 prio_init();
3684 #ifdef __APPLE__
3685 // dynamically link to objective c gc registration
3686 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3687 if (handleLibObjc != NULL) {
3688 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3689 }
3690 #endif
3692 return JNI_OK;
3693 }
3695 // this is called at the end of vm_initialization
3696 void os::init_3(void) { }
3698 // Mark the polling page as unreadable
3699 void os::make_polling_page_unreadable(void) {
3700 if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
3701 fatal("Could not disable polling page");
3702 };
3704 // Mark the polling page as readable
3705 void os::make_polling_page_readable(void) {
3706 if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
3707 fatal("Could not enable polling page");
3708 }
3709 };
3711 int os::active_processor_count() {
3712 return _processor_count;
3713 }
3715 void os::set_native_thread_name(const char *name) {
3716 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3717 // This is only supported in Snow Leopard and beyond
3718 if (name != NULL) {
3719 // Add a "Java: " prefix to the name
3720 char buf[MAXTHREADNAMESIZE];
3721 snprintf(buf, sizeof(buf), "Java: %s", name);
3722 pthread_setname_np(buf);
3723 }
3724 #endif
3725 }
3727 bool os::distribute_processes(uint length, uint* distribution) {
3728 // Not yet implemented.
3729 return false;
3730 }
3732 bool os::bind_to_processor(uint processor_id) {
3733 // Not yet implemented.
3734 return false;
3735 }
3737 void os::SuspendedThreadTask::internal_do_task() {
3738 if (do_suspend(_thread->osthread())) {
3739 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3740 do_task(context);
3741 do_resume(_thread->osthread());
3742 }
3743 }
3745 ///
3746 class PcFetcher : public os::SuspendedThreadTask {
3747 public:
3748 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3749 ExtendedPC result();
3750 protected:
3751 void do_task(const os::SuspendedThreadTaskContext& context);
3752 private:
3753 ExtendedPC _epc;
3754 };
3756 ExtendedPC PcFetcher::result() {
3757 guarantee(is_done(), "task is not done yet.");
3758 return _epc;
3759 }
3761 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3762 Thread* thread = context.thread();
3763 OSThread* osthread = thread->osthread();
3764 if (osthread->ucontext() != NULL) {
3765 _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());
3766 } else {
3767 // NULL context is unexpected, double-check this is the VMThread
3768 guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3769 }
3770 }
3772 // Suspends the target using the signal mechanism and then grabs the PC before
3773 // resuming the target. Used by the flat-profiler only
3774 ExtendedPC os::get_thread_pc(Thread* thread) {
3775 // Make sure that it is called by the watcher for the VMThread
3776 assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
3777 assert(thread->is_VM_thread(), "Can only be called for VMThread");
3779 PcFetcher fetcher(thread);
3780 fetcher.run();
3781 return fetcher.result();
3782 }
3784 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
3785 {
3786 return pthread_cond_timedwait(_cond, _mutex, _abstime);
3787 }
3789 ////////////////////////////////////////////////////////////////////////////////
3790 // debug support
3792 bool os::find(address addr, outputStream* st) {
3793 Dl_info dlinfo;
3794 memset(&dlinfo, 0, sizeof(dlinfo));
3795 if (dladdr(addr, &dlinfo) != 0) {
3796 st->print(PTR_FORMAT ": ", addr);
3797 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
3798 st->print("%s+%#x", dlinfo.dli_sname,
3799 addr - (intptr_t)dlinfo.dli_saddr);
3800 } else if (dlinfo.dli_fbase != NULL) {
3801 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
3802 } else {
3803 st->print("<absolute address>");
3804 }
3805 if (dlinfo.dli_fname != NULL) {
3806 st->print(" in %s", dlinfo.dli_fname);
3807 }
3808 if (dlinfo.dli_fbase != NULL) {
3809 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
3810 }
3811 st->cr();
3813 if (Verbose) {
3814 // decode some bytes around the PC
3815 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
3816 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());
3817 address lowest = (address) dlinfo.dli_sname;
3818 if (!lowest) lowest = (address) dlinfo.dli_fbase;
3819 if (begin < lowest) begin = lowest;
3820 Dl_info dlinfo2;
3821 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
3822 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
3823 end = (address) dlinfo2.dli_saddr;
3824 Disassembler::decode(begin, end, st);
3825 }
3826 return true;
3827 }
3828 return false;
3829 }
3831 ////////////////////////////////////////////////////////////////////////////////
3832 // misc
3834 // This does not do anything on Bsd. This is basically a hook for being
3835 // able to use structured exception handling (thread-local exception filters)
3836 // on, e.g., Win32.
3837 void
3838 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
3839 JavaCallArguments* args, Thread* thread) {
3840 f(value, method, args, thread);
3841 }
3843 void os::print_statistics() {
3844 }
3846 int os::message_box(const char* title, const char* message) {
3847 int i;
3848 fdStream err(defaultStream::error_fd());
3849 for (i = 0; i < 78; i++) err.print_raw("=");
3850 err.cr();
3851 err.print_raw_cr(title);
3852 for (i = 0; i < 78; i++) err.print_raw("-");
3853 err.cr();
3854 err.print_raw_cr(message);
3855 for (i = 0; i < 78; i++) err.print_raw("=");
3856 err.cr();
3858 char buf[16];
3859 // Prevent process from exiting upon "read error" without consuming all CPU
3860 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3862 return buf[0] == 'y' || buf[0] == 'Y';
3863 }
3865 int os::stat(const char *path, struct stat *sbuf) {
3866 char pathbuf[MAX_PATH];
3867 if (strlen(path) > MAX_PATH - 1) {
3868 errno = ENAMETOOLONG;
3869 return -1;
3870 }
3871 os::native_path(strcpy(pathbuf, path));
3872 return ::stat(pathbuf, sbuf);
3873 }
3875 bool os::check_heap(bool force) {
3876 return true;
3877 }
3879 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
3880 return ::vsnprintf(buf, count, format, args);
3881 }
3883 // Is a (classpath) directory empty?
3884 bool os::dir_is_empty(const char* path) {
3885 DIR *dir = NULL;
3886 struct dirent *ptr;
3888 dir = opendir(path);
3889 if (dir == NULL) return true;
3891 /* Scan the directory */
3892 bool result = true;
3893 char buf[sizeof(struct dirent) + MAX_PATH];
3894 while (result && (ptr = ::readdir(dir)) != NULL) {
3895 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3896 result = false;
3897 }
3898 }
3899 closedir(dir);
3900 return result;
3901 }
3903 // This code originates from JDK's sysOpen and open64_w
3904 // from src/solaris/hpi/src/system_md.c
3906 #ifndef O_DELETE
3907 #define O_DELETE 0x10000
3908 #endif
3910 // Open a file. Unlink the file immediately after open returns
3911 // if the specified oflag has the O_DELETE flag set.
3912 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
3914 int os::open(const char *path, int oflag, int mode) {
3916 if (strlen(path) > MAX_PATH - 1) {
3917 errno = ENAMETOOLONG;
3918 return -1;
3919 }
3920 int fd;
3921 int o_delete = (oflag & O_DELETE);
3922 oflag = oflag & ~O_DELETE;
3924 fd = ::open(path, oflag, mode);
3925 if (fd == -1) return -1;
3927 //If the open succeeded, the file might still be a directory
3928 {
3929 struct stat buf;
3930 int ret = ::fstat(fd, &buf);
3931 int st_mode = buf.st_mode;
3933 if (ret != -1) {
3934 if ((st_mode & S_IFMT) == S_IFDIR) {
3935 errno = EISDIR;
3936 ::close(fd);
3937 return -1;
3938 }
3939 } else {
3940 ::close(fd);
3941 return -1;
3942 }
3943 }
3945 /*
3946 * All file descriptors that are opened in the JVM and not
3947 * specifically destined for a subprocess should have the
3948 * close-on-exec flag set. If we don't set it, then careless 3rd
3949 * party native code might fork and exec without closing all
3950 * appropriate file descriptors (e.g. as we do in closeDescriptors in
3951 * UNIXProcess.c), and this in turn might:
3952 *
3953 * - cause end-of-file to fail to be detected on some file
3954 * descriptors, resulting in mysterious hangs, or
3955 *
3956 * - might cause an fopen in the subprocess to fail on a system
3957 * suffering from bug 1085341.
3958 *
3959 * (Yes, the default setting of the close-on-exec flag is a Unix
3960 * design flaw)
3961 *
3962 * See:
3963 * 1085341: 32-bit stdio routines should support file descriptors >255
3964 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3965 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3966 */
3967 #ifdef FD_CLOEXEC
3968 {
3969 int flags = ::fcntl(fd, F_GETFD);
3970 if (flags != -1)
3971 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3972 }
3973 #endif
3975 if (o_delete != 0) {
3976 ::unlink(path);
3977 }
3978 return fd;
3979 }
3982 // create binary file, rewriting existing file if required
3983 int os::create_binary_file(const char* path, bool rewrite_existing) {
3984 int oflags = O_WRONLY | O_CREAT;
3985 if (!rewrite_existing) {
3986 oflags |= O_EXCL;
3987 }
3988 return ::open(path, oflags, S_IREAD | S_IWRITE);
3989 }
3991 // return current position of file pointer
3992 jlong os::current_file_offset(int fd) {
3993 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
3994 }
3996 // move file pointer to the specified offset
3997 jlong os::seek_to_file_offset(int fd, jlong offset) {
3998 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
3999 }
4001 // This code originates from JDK's sysAvailable
4002 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
4004 int os::available(int fd, jlong *bytes) {
4005 jlong cur, end;
4006 int mode;
4007 struct stat buf;
4009 if (::fstat(fd, &buf) >= 0) {
4010 mode = buf.st_mode;
4011 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4012 /*
4013 * XXX: is the following call interruptible? If so, this might
4014 * need to go through the INTERRUPT_IO() wrapper as for other
4015 * blocking, interruptible calls in this file.
4016 */
4017 int n;
4018 if (::ioctl(fd, FIONREAD, &n) >= 0) {
4019 *bytes = n;
4020 return 1;
4021 }
4022 }
4023 }
4024 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
4025 return 0;
4026 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
4027 return 0;
4028 } else if (::lseek(fd, cur, SEEK_SET) == -1) {
4029 return 0;
4030 }
4031 *bytes = end - cur;
4032 return 1;
4033 }
4035 int os::socket_available(int fd, jint *pbytes) {
4036 if (fd < 0)
4037 return OS_OK;
4039 int ret;
4041 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
4043 //%% note ioctl can return 0 when successful, JVM_SocketAvailable
4044 // is expected to return 0 on failure and 1 on success to the jdk.
4046 return (ret == OS_ERR) ? 0 : 1;
4047 }
4049 // Map a block of memory.
4050 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4051 char *addr, size_t bytes, bool read_only,
4052 bool allow_exec) {
4053 int prot;
4054 int flags;
4056 if (read_only) {
4057 prot = PROT_READ;
4058 flags = MAP_SHARED;
4059 } else {
4060 prot = PROT_READ | PROT_WRITE;
4061 flags = MAP_PRIVATE;
4062 }
4064 if (allow_exec) {
4065 prot |= PROT_EXEC;
4066 }
4068 if (addr != NULL) {
4069 flags |= MAP_FIXED;
4070 }
4072 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4073 fd, file_offset);
4074 if (mapped_address == MAP_FAILED) {
4075 return NULL;
4076 }
4077 return mapped_address;
4078 }
4081 // Remap a block of memory.
4082 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4083 char *addr, size_t bytes, bool read_only,
4084 bool allow_exec) {
4085 // same as map_memory() on this OS
4086 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4087 allow_exec);
4088 }
4091 // Unmap a block of memory.
4092 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4093 return munmap(addr, bytes) == 0;
4094 }
4096 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4097 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4098 // of a thread.
4099 //
4100 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
4101 // the fast estimate available on the platform.
4103 jlong os::current_thread_cpu_time() {
4104 #ifdef __APPLE__
4105 return os::thread_cpu_time(Thread::current(), true /* user + sys */);
4106 #else
4107 Unimplemented();
4108 return 0;
4109 #endif
4110 }
4112 jlong os::thread_cpu_time(Thread* thread) {
4113 #ifdef __APPLE__
4114 return os::thread_cpu_time(thread, true /* user + sys */);
4115 #else
4116 Unimplemented();
4117 return 0;
4118 #endif
4119 }
4121 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
4122 #ifdef __APPLE__
4123 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
4124 #else
4125 Unimplemented();
4126 return 0;
4127 #endif
4128 }
4130 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
4131 #ifdef __APPLE__
4132 struct thread_basic_info tinfo;
4133 mach_msg_type_number_t tcount = THREAD_INFO_MAX;
4134 kern_return_t kr;
4135 thread_t mach_thread;
4137 mach_thread = thread->osthread()->thread_id();
4138 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
4139 if (kr != KERN_SUCCESS)
4140 return -1;
4142 if (user_sys_cpu_time) {
4143 jlong nanos;
4144 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
4145 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
4146 return nanos;
4147 } else {
4148 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
4149 }
4150 #else
4151 Unimplemented();
4152 return 0;
4153 #endif
4154 }
4157 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4158 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
4159 info_ptr->may_skip_backward = false; // elapsed time not wall time
4160 info_ptr->may_skip_forward = false; // elapsed time not wall time
4161 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
4162 }
4164 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4165 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
4166 info_ptr->may_skip_backward = false; // elapsed time not wall time
4167 info_ptr->may_skip_forward = false; // elapsed time not wall time
4168 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
4169 }
4171 bool os::is_thread_cpu_time_supported() {
4172 #ifdef __APPLE__
4173 return true;
4174 #else
4175 return false;
4176 #endif
4177 }
4179 // System loadavg support. Returns -1 if load average cannot be obtained.
4180 // Bsd doesn't yet have a (official) notion of processor sets,
4181 // so just return the system wide load average.
4182 int os::loadavg(double loadavg[], int nelem) {
4183 return ::getloadavg(loadavg, nelem);
4184 }
4186 void os::pause() {
4187 char filename[MAX_PATH];
4188 if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4189 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4190 } else {
4191 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4192 }
4194 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4195 if (fd != -1) {
4196 struct stat buf;
4197 ::close(fd);
4198 while (::stat(filename, &buf) == 0) {
4199 (void)::poll(NULL, 0, 100);
4200 }
4201 } else {
4202 jio_fprintf(stderr,
4203 "Could not open pause file '%s', continuing immediately.\n", filename);
4204 }
4205 }
4208 // Refer to the comments in os_solaris.cpp park-unpark.
4209 //
4210 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
4211 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
4212 // For specifics regarding the bug see GLIBC BUGID 261237 :
4213 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
4214 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
4215 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
4216 // is used. (The simple C test-case provided in the GLIBC bug report manifests the
4217 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
4218 // and monitorenter when we're using 1-0 locking. All those operations may result in
4219 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
4220 // of libpthread avoids the problem, but isn't practical.
4221 //
4222 // Possible remedies:
4223 //
4224 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
4225 // This is palliative and probabilistic, however. If the thread is preempted
4226 // between the call to compute_abstime() and pthread_cond_timedwait(), more
4227 // than the minimum period may have passed, and the abstime may be stale (in the
4228 // past) resultin in a hang. Using this technique reduces the odds of a hang
4229 // but the JVM is still vulnerable, particularly on heavily loaded systems.
4230 //
4231 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
4232 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set
4233 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
4234 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant
4235 // thread.
4236 //
4237 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
4238 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
4239 // a timeout request to the chron thread and then blocking via pthread_cond_wait().
4240 // This also works well. In fact it avoids kernel-level scalability impediments
4241 // on certain platforms that don't handle lots of active pthread_cond_timedwait()
4242 // timers in a graceful fashion.
4243 //
4244 // 4. When the abstime value is in the past it appears that control returns
4245 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
4246 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we
4247 // can avoid the problem by reinitializing the condvar -- by cond_destroy()
4248 // followed by cond_init() -- after all calls to pthread_cond_timedwait().
4249 // It may be possible to avoid reinitialization by checking the return
4250 // value from pthread_cond_timedwait(). In addition to reinitializing the
4251 // condvar we must establish the invariant that cond_signal() is only called
4252 // within critical sections protected by the adjunct mutex. This prevents
4253 // cond_signal() from "seeing" a condvar that's in the midst of being
4254 // reinitialized or that is corrupt. Sadly, this invariant obviates the
4255 // desirable signal-after-unlock optimization that avoids futile context switching.
4256 //
4257 // I'm also concerned that some versions of NTPL might allocate an auxilliary
4258 // structure when a condvar is used or initialized. cond_destroy() would
4259 // release the helper structure. Our reinitialize-after-timedwait fix
4260 // put excessive stress on malloc/free and locks protecting the c-heap.
4261 //
4262 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
4263 // It may be possible to refine (4) by checking the kernel and NTPL verisons
4264 // and only enabling the work-around for vulnerable environments.
4266 // utility to compute the abstime argument to timedwait:
4267 // millis is the relative timeout time
4268 // abstime will be the absolute timeout time
4269 // TODO: replace compute_abstime() with unpackTime()
4271 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
4272 if (millis < 0) millis = 0;
4273 struct timeval now;
4274 int status = gettimeofday(&now, NULL);
4275 assert(status == 0, "gettimeofday");
4276 jlong seconds = millis / 1000;
4277 millis %= 1000;
4278 if (seconds > 50000000) { // see man cond_timedwait(3T)
4279 seconds = 50000000;
4280 }
4281 abstime->tv_sec = now.tv_sec + seconds;
4282 long usec = now.tv_usec + millis * 1000;
4283 if (usec >= 1000000) {
4284 abstime->tv_sec += 1;
4285 usec -= 1000000;
4286 }
4287 abstime->tv_nsec = usec * 1000;
4288 return abstime;
4289 }
4292 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
4293 // Conceptually TryPark() should be equivalent to park(0).
4295 int os::PlatformEvent::TryPark() {
4296 for (;;) {
4297 const int v = _Event ;
4298 guarantee ((v == 0) || (v == 1), "invariant") ;
4299 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;
4300 }
4301 }
4303 void os::PlatformEvent::park() { // AKA "down()"
4304 // Invariant: Only the thread associated with the Event/PlatformEvent
4305 // may call park().
4306 // TODO: assert that _Assoc != NULL or _Assoc == Self
4307 int v ;
4308 for (;;) {
4309 v = _Event ;
4310 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4311 }
4312 guarantee (v >= 0, "invariant") ;
4313 if (v == 0) {
4314 // Do this the hard way by blocking ...
4315 int status = pthread_mutex_lock(_mutex);
4316 assert_status(status == 0, status, "mutex_lock");
4317 guarantee (_nParked == 0, "invariant") ;
4318 ++ _nParked ;
4319 while (_Event < 0) {
4320 status = pthread_cond_wait(_cond, _mutex);
4321 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
4322 // Treat this the same as if the wait was interrupted
4323 if (status == ETIMEDOUT) { status = EINTR; }
4324 assert_status(status == 0 || status == EINTR, status, "cond_wait");
4325 }
4326 -- _nParked ;
4328 _Event = 0 ;
4329 status = pthread_mutex_unlock(_mutex);
4330 assert_status(status == 0, status, "mutex_unlock");
4331 // Paranoia to ensure our locked and lock-free paths interact
4332 // correctly with each other.
4333 OrderAccess::fence();
4334 }
4335 guarantee (_Event >= 0, "invariant") ;
4336 }
4338 int os::PlatformEvent::park(jlong millis) {
4339 guarantee (_nParked == 0, "invariant") ;
4341 int v ;
4342 for (;;) {
4343 v = _Event ;
4344 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4345 }
4346 guarantee (v >= 0, "invariant") ;
4347 if (v != 0) return OS_OK ;
4349 // We do this the hard way, by blocking the thread.
4350 // Consider enforcing a minimum timeout value.
4351 struct timespec abst;
4352 compute_abstime(&abst, millis);
4354 int ret = OS_TIMEOUT;
4355 int status = pthread_mutex_lock(_mutex);
4356 assert_status(status == 0, status, "mutex_lock");
4357 guarantee (_nParked == 0, "invariant") ;
4358 ++_nParked ;
4360 // Object.wait(timo) will return because of
4361 // (a) notification
4362 // (b) timeout
4363 // (c) thread.interrupt
4364 //
4365 // Thread.interrupt and object.notify{All} both call Event::set.
4366 // That is, we treat thread.interrupt as a special case of notification.
4367 // The underlying Solaris implementation, cond_timedwait, admits
4368 // spurious/premature wakeups, but the JLS/JVM spec prevents the
4369 // JVM from making those visible to Java code. As such, we must
4370 // filter out spurious wakeups. We assume all ETIME returns are valid.
4371 //
4372 // TODO: properly differentiate simultaneous notify+interrupt.
4373 // In that case, we should propagate the notify to another waiter.
4375 while (_Event < 0) {
4376 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
4377 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4378 pthread_cond_destroy (_cond);
4379 pthread_cond_init (_cond, NULL) ;
4380 }
4381 assert_status(status == 0 || status == EINTR ||
4382 status == ETIMEDOUT,
4383 status, "cond_timedwait");
4384 if (!FilterSpuriousWakeups) break ; // previous semantics
4385 if (status == ETIMEDOUT) break ;
4386 // We consume and ignore EINTR and spurious wakeups.
4387 }
4388 --_nParked ;
4389 if (_Event >= 0) {
4390 ret = OS_OK;
4391 }
4392 _Event = 0 ;
4393 status = pthread_mutex_unlock(_mutex);
4394 assert_status(status == 0, status, "mutex_unlock");
4395 assert (_nParked == 0, "invariant") ;
4396 // Paranoia to ensure our locked and lock-free paths interact
4397 // correctly with each other.
4398 OrderAccess::fence();
4399 return ret;
4400 }
4402 void os::PlatformEvent::unpark() {
4403 // Transitions for _Event:
4404 // 0 :=> 1
4405 // 1 :=> 1
4406 // -1 :=> either 0 or 1; must signal target thread
4407 // That is, we can safely transition _Event from -1 to either
4408 // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
4409 // unpark() calls.
4410 // See also: "Semaphores in Plan 9" by Mullender & Cox
4411 //
4412 // Note: Forcing a transition from "-1" to "1" on an unpark() means
4413 // that it will take two back-to-back park() calls for the owning
4414 // thread to block. This has the benefit of forcing a spurious return
4415 // from the first park() call after an unpark() call which will help
4416 // shake out uses of park() and unpark() without condition variables.
4418 if (Atomic::xchg(1, &_Event) >= 0) return;
4420 // Wait for the thread associated with the event to vacate
4421 int status = pthread_mutex_lock(_mutex);
4422 assert_status(status == 0, status, "mutex_lock");
4423 int AnyWaiters = _nParked;
4424 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
4425 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
4426 AnyWaiters = 0;
4427 pthread_cond_signal(_cond);
4428 }
4429 status = pthread_mutex_unlock(_mutex);
4430 assert_status(status == 0, status, "mutex_unlock");
4431 if (AnyWaiters != 0) {
4432 status = pthread_cond_signal(_cond);
4433 assert_status(status == 0, status, "cond_signal");
4434 }
4436 // Note that we signal() _after dropping the lock for "immortal" Events.
4437 // This is safe and avoids a common class of futile wakeups. In rare
4438 // circumstances this can cause a thread to return prematurely from
4439 // cond_{timed}wait() but the spurious wakeup is benign and the victim will
4440 // simply re-test the condition and re-park itself.
4441 }
4444 // JSR166
4445 // -------------------------------------------------------
4447 /*
4448 * The solaris and bsd implementations of park/unpark are fairly
4449 * conservative for now, but can be improved. They currently use a
4450 * mutex/condvar pair, plus a a count.
4451 * Park decrements count if > 0, else does a condvar wait. Unpark
4452 * sets count to 1 and signals condvar. Only one thread ever waits
4453 * on the condvar. Contention seen when trying to park implies that someone
4454 * is unparking you, so don't wait. And spurious returns are fine, so there
4455 * is no need to track notifications.
4456 */
4458 #define MAX_SECS 100000000
4459 /*
4460 * This code is common to bsd and solaris and will be moved to a
4461 * common place in dolphin.
4462 *
4463 * The passed in time value is either a relative time in nanoseconds
4464 * or an absolute time in milliseconds. Either way it has to be unpacked
4465 * into suitable seconds and nanoseconds components and stored in the
4466 * given timespec structure.
4467 * Given time is a 64-bit value and the time_t used in the timespec is only
4468 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
4469 * overflow if times way in the future are given. Further on Solaris versions
4470 * prior to 10 there is a restriction (see cond_timedwait) that the specified
4471 * number of seconds, in abstime, is less than current_time + 100,000,000.
4472 * As it will be 28 years before "now + 100000000" will overflow we can
4473 * ignore overflow and just impose a hard-limit on seconds using the value
4474 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
4475 * years from "now".
4476 */
4478 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
4479 assert (time > 0, "convertTime");
4481 struct timeval now;
4482 int status = gettimeofday(&now, NULL);
4483 assert(status == 0, "gettimeofday");
4485 time_t max_secs = now.tv_sec + MAX_SECS;
4487 if (isAbsolute) {
4488 jlong secs = time / 1000;
4489 if (secs > max_secs) {
4490 absTime->tv_sec = max_secs;
4491 }
4492 else {
4493 absTime->tv_sec = secs;
4494 }
4495 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
4496 }
4497 else {
4498 jlong secs = time / NANOSECS_PER_SEC;
4499 if (secs >= MAX_SECS) {
4500 absTime->tv_sec = max_secs;
4501 absTime->tv_nsec = 0;
4502 }
4503 else {
4504 absTime->tv_sec = now.tv_sec + secs;
4505 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
4506 if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
4507 absTime->tv_nsec -= NANOSECS_PER_SEC;
4508 ++absTime->tv_sec; // note: this must be <= max_secs
4509 }
4510 }
4511 }
4512 assert(absTime->tv_sec >= 0, "tv_sec < 0");
4513 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
4514 assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
4515 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
4516 }
4518 void Parker::park(bool isAbsolute, jlong time) {
4519 // Ideally we'd do something useful while spinning, such
4520 // as calling unpackTime().
4522 // Optional fast-path check:
4523 // Return immediately if a permit is available.
4524 // We depend on Atomic::xchg() having full barrier semantics
4525 // since we are doing a lock-free update to _counter.
4526 if (Atomic::xchg(0, &_counter) > 0) return;
4528 Thread* thread = Thread::current();
4529 assert(thread->is_Java_thread(), "Must be JavaThread");
4530 JavaThread *jt = (JavaThread *)thread;
4532 // Optional optimization -- avoid state transitions if there's an interrupt pending.
4533 // Check interrupt before trying to wait
4534 if (Thread::is_interrupted(thread, false)) {
4535 return;
4536 }
4538 // Next, demultiplex/decode time arguments
4539 struct timespec absTime;
4540 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
4541 return;
4542 }
4543 if (time > 0) {
4544 unpackTime(&absTime, isAbsolute, time);
4545 }
4548 // Enter safepoint region
4549 // Beware of deadlocks such as 6317397.
4550 // The per-thread Parker:: mutex is a classic leaf-lock.
4551 // In particular a thread must never block on the Threads_lock while
4552 // holding the Parker:: mutex. If safepoints are pending both the
4553 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
4554 ThreadBlockInVM tbivm(jt);
4556 // Don't wait if cannot get lock since interference arises from
4557 // unblocking. Also. check interrupt before trying wait
4558 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
4559 return;
4560 }
4562 int status ;
4563 if (_counter > 0) { // no wait needed
4564 _counter = 0;
4565 status = pthread_mutex_unlock(_mutex);
4566 assert (status == 0, "invariant") ;
4567 // Paranoia to ensure our locked and lock-free paths interact
4568 // correctly with each other and Java-level accesses.
4569 OrderAccess::fence();
4570 return;
4571 }
4573 #ifdef ASSERT
4574 // Don't catch signals while blocked; let the running threads have the signals.
4575 // (This allows a debugger to break into the running thread.)
4576 sigset_t oldsigs;
4577 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
4578 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
4579 #endif
4581 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
4582 jt->set_suspend_equivalent();
4583 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
4585 if (time == 0) {
4586 status = pthread_cond_wait (_cond, _mutex) ;
4587 } else {
4588 status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
4589 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4590 pthread_cond_destroy (_cond) ;
4591 pthread_cond_init (_cond, NULL);
4592 }
4593 }
4594 assert_status(status == 0 || status == EINTR ||
4595 status == ETIMEDOUT,
4596 status, "cond_timedwait");
4598 #ifdef ASSERT
4599 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
4600 #endif
4602 _counter = 0 ;
4603 status = pthread_mutex_unlock(_mutex) ;
4604 assert_status(status == 0, status, "invariant") ;
4605 // Paranoia to ensure our locked and lock-free paths interact
4606 // correctly with each other and Java-level accesses.
4607 OrderAccess::fence();
4609 // If externally suspended while waiting, re-suspend
4610 if (jt->handle_special_suspend_equivalent_condition()) {
4611 jt->java_suspend_self();
4612 }
4613 }
4615 void Parker::unpark() {
4616 int s, status ;
4617 status = pthread_mutex_lock(_mutex);
4618 assert (status == 0, "invariant") ;
4619 s = _counter;
4620 _counter = 1;
4621 if (s < 1) {
4622 if (WorkAroundNPTLTimedWaitHang) {
4623 status = pthread_cond_signal (_cond) ;
4624 assert (status == 0, "invariant") ;
4625 status = pthread_mutex_unlock(_mutex);
4626 assert (status == 0, "invariant") ;
4627 } else {
4628 status = pthread_mutex_unlock(_mutex);
4629 assert (status == 0, "invariant") ;
4630 status = pthread_cond_signal (_cond) ;
4631 assert (status == 0, "invariant") ;
4632 }
4633 } else {
4634 pthread_mutex_unlock(_mutex);
4635 assert (status == 0, "invariant") ;
4636 }
4637 }
4640 /* Darwin has no "environ" in a dynamic library. */
4641 #ifdef __APPLE__
4642 #include <crt_externs.h>
4643 #define environ (*_NSGetEnviron())
4644 #else
4645 extern char** environ;
4646 #endif
4648 // Run the specified command in a separate process. Return its exit value,
4649 // or -1 on failure (e.g. can't fork a new process).
4650 // Unlike system(), this function can be called from signal handler. It
4651 // doesn't block SIGINT et al.
4652 int os::fork_and_exec(char* cmd) {
4653 const char * argv[4] = {"sh", "-c", cmd, NULL};
4655 // fork() in BsdThreads/NPTL is not async-safe. It needs to run
4656 // pthread_atfork handlers and reset pthread library. All we need is a
4657 // separate process to execve. Make a direct syscall to fork process.
4658 // On IA64 there's no fork syscall, we have to use fork() and hope for
4659 // the best...
4660 pid_t pid = fork();
4662 if (pid < 0) {
4663 // fork failed
4664 return -1;
4666 } else if (pid == 0) {
4667 // child process
4669 // execve() in BsdThreads will call pthread_kill_other_threads_np()
4670 // first to kill every thread on the thread list. Because this list is
4671 // not reset by fork() (see notes above), execve() will instead kill
4672 // every thread in the parent process. We know this is the only thread
4673 // in the new process, so make a system call directly.
4674 // IA64 should use normal execve() from glibc to match the glibc fork()
4675 // above.
4676 execve("/bin/sh", (char* const*)argv, environ);
4678 // execve failed
4679 _exit(-1);
4681 } else {
4682 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
4683 // care about the actual exit code, for now.
4685 int status;
4687 // Wait for the child process to exit. This returns immediately if
4688 // the child has already exited. */
4689 while (waitpid(pid, &status, 0) < 0) {
4690 switch (errno) {
4691 case ECHILD: return 0;
4692 case EINTR: break;
4693 default: return -1;
4694 }
4695 }
4697 if (WIFEXITED(status)) {
4698 // The child exited normally; get its exit code.
4699 return WEXITSTATUS(status);
4700 } else if (WIFSIGNALED(status)) {
4701 // The child exited because of a signal
4702 // The best value to return is 0x80 + signal number,
4703 // because that is what all Unix shells do, and because
4704 // it allows callers to distinguish between process exit and
4705 // process death by signal.
4706 return 0x80 + WTERMSIG(status);
4707 } else {
4708 // Unknown exit code; pass it through
4709 return status;
4710 }
4711 }
4712 }
4714 // is_headless_jre()
4715 //
4716 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
4717 // in order to report if we are running in a headless jre
4718 //
4719 // Since JDK8 xawt/libmawt.so was moved into the same directory
4720 // as libawt.so, and renamed libawt_xawt.so
4721 //
4722 bool os::is_headless_jre() {
4723 struct stat statbuf;
4724 char buf[MAXPATHLEN];
4725 char libmawtpath[MAXPATHLEN];
4726 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX;
4727 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
4728 char *p;
4730 // Get path to libjvm.so
4731 os::jvm_path(buf, sizeof(buf));
4733 // Get rid of libjvm.so
4734 p = strrchr(buf, '/');
4735 if (p == NULL) return false;
4736 else *p = '\0';
4738 // Get rid of client or server
4739 p = strrchr(buf, '/');
4740 if (p == NULL) return false;
4741 else *p = '\0';
4743 // check xawt/libmawt.so
4744 strcpy(libmawtpath, buf);
4745 strcat(libmawtpath, xawtstr);
4746 if (::stat(libmawtpath, &statbuf) == 0) return false;
4748 // check libawt_xawt.so
4749 strcpy(libmawtpath, buf);
4750 strcat(libmawtpath, new_xawtstr);
4751 if (::stat(libmawtpath, &statbuf) == 0) return false;
4753 return true;
4754 }
4756 // Get the default path to the core file
4757 // Returns the length of the string
4758 int os::get_core_path(char* buffer, size_t bufferSize) {
4759 int n = jio_snprintf(buffer, bufferSize, "/cores");
4761 // Truncate if theoretical string was longer than bufferSize
4762 n = MIN2(n, (int)bufferSize);
4764 return n;
4765 }
4767 #ifndef PRODUCT
4768 void TestReserveMemorySpecial_test() {
4769 // No tests available for this platform
4770 }
4771 #endif