Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/os/bsd/vm/os_bsd.cpp
48785 views
/*1* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324// no precompiled headers25#include "classfile/classLoader.hpp"26#include "classfile/systemDictionary.hpp"27#include "classfile/vmSymbols.hpp"28#include "code/icBuffer.hpp"29#include "code/vtableStubs.hpp"30#include "compiler/compileBroker.hpp"31#include "compiler/disassembler.hpp"32#include "interpreter/interpreter.hpp"33#include "jvm_bsd.h"34#include "memory/allocation.inline.hpp"35#include "memory/filemap.hpp"36#include "mutex_bsd.inline.hpp"37#include "oops/oop.inline.hpp"38#include "os_share_bsd.hpp"39#include "prims/jniFastGetField.hpp"40#include "prims/jvm.h"41#include "prims/jvm_misc.hpp"42#include "runtime/arguments.hpp"43#include "runtime/extendedPC.hpp"44#include "runtime/globals.hpp"45#include "runtime/interfaceSupport.hpp"46#include "runtime/java.hpp"47#include "runtime/javaCalls.hpp"48#include "runtime/mutexLocker.hpp"49#include "runtime/objectMonitor.hpp"50#include "runtime/orderAccess.inline.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"6768// put OS-includes here69# 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#endif100# include <stdint.h>101# include <inttypes.h>102# include <sys/ioctl.h>103# include <sys/syscall.h>104105#if defined(__FreeBSD__) || defined(__NetBSD__)106# include <elf.h>107#endif108109#ifdef __APPLE__110# include <mach/mach.h> // semaphore_* API111# include <mach-o/dyld.h>112# include <sys/proc_info.h>113# include <objc/objc-auto.h>114#endif115116#ifndef MAP_ANONYMOUS117#define MAP_ANONYMOUS MAP_ANON118#endif119120#define MAX_PATH (2 * K)121122// for timer info max values which include all bits123#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)124125#define LARGEPAGES_BIT (1 << 6)126127PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC128129////////////////////////////////////////////////////////////////////////////////130// global variables131julong os::Bsd::_physical_memory = 0;132133#ifdef __APPLE__134mach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0};135volatile uint64_t os::Bsd::_max_abstime = 0;136#else137int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;138#endif139pthread_t os::Bsd::_main_thread;140int os::Bsd::_page_size = -1;141142static jlong initial_time_count=0;143144static int clock_tics_per_sec = 100;145146// For diagnostics to print a message once. see run_periodic_checks147static sigset_t check_signal_done;148static bool check_signals = true;149150static pid_t _initial_pid = 0;151152/* Signal number used to suspend/resume a thread */153154/* do not use any signal number less than SIGSEGV, see 4355769 */155static int SR_signum = SIGUSR2;156sigset_t SR_sigset;157158159////////////////////////////////////////////////////////////////////////////////160// utility functions161162static int SR_initialize();163static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);164165julong os::available_memory() {166return Bsd::available_memory();167}168169// available here means free170julong os::Bsd::available_memory() {171uint64_t available = physical_memory() >> 2;172#ifdef __APPLE__173mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;174vm_statistics64_data_t vmstat;175kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64,176(host_info64_t)&vmstat, &count);177assert(kerr == KERN_SUCCESS,178"host_statistics64 failed - check mach_host_self() and count");179if (kerr == KERN_SUCCESS) {180available = vmstat.free_count * os::vm_page_size();181}182#endif183return available;184}185186julong os::physical_memory() {187return Bsd::physical_memory();188}189190////////////////////////////////////////////////////////////////////////////////191// environment support192193bool os::getenv(const char* name, char* buf, int len) {194const char* val = ::getenv(name);195if (val != NULL && strlen(val) < (size_t)len) {196strcpy(buf, val);197return true;198}199if (len > 0) buf[0] = 0; // return a null string200return false;201}202203204// Return true if user is running as root.205206bool os::have_special_privileges() {207static bool init = false;208static bool privileges = false;209if (!init) {210privileges = (getuid() != geteuid()) || (getgid() != getegid());211init = true;212}213return privileges;214}215216217218// Cpu architecture string219#if defined(ZERO)220static char cpu_arch[] = ZERO_LIBARCH;221#elif defined(IA64)222static char cpu_arch[] = "ia64";223#elif defined(IA32)224static char cpu_arch[] = "i386";225#elif defined(AMD64)226static char cpu_arch[] = "amd64";227#elif defined(ARM)228static char cpu_arch[] = "arm";229#elif defined(PPC32)230static char cpu_arch[] = "ppc";231#elif defined(SPARC)232# ifdef _LP64233static char cpu_arch[] = "sparcv9";234# else235static char cpu_arch[] = "sparc";236# endif237#else238#error Add appropriate cpu_arch setting239#endif240241// Compiler variant242#ifdef COMPILER2243#define COMPILER_VARIANT "server"244#else245#define COMPILER_VARIANT "client"246#endif247248249void os::Bsd::initialize_system_info() {250int mib[2];251size_t len;252int cpu_val;253julong mem_val;254255/* get processors count via hw.ncpus sysctl */256mib[0] = CTL_HW;257mib[1] = HW_NCPU;258len = sizeof(cpu_val);259if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {260assert(len == sizeof(cpu_val), "unexpected data size");261set_processor_count(cpu_val);262}263else {264set_processor_count(1); // fallback265}266267/* get physical memory via hw.memsize sysctl (hw.memsize is used268* since it returns a 64 bit value)269*/270mib[0] = CTL_HW;271272#if defined (HW_MEMSIZE) // Apple273mib[1] = HW_MEMSIZE;274#elif defined(HW_PHYSMEM) // Most of BSD275mib[1] = HW_PHYSMEM;276#elif defined(HW_REALMEM) // Old FreeBSD277mib[1] = HW_REALMEM;278#else279#error No ways to get physmem280#endif281282len = sizeof(mem_val);283if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {284assert(len == sizeof(mem_val), "unexpected data size");285_physical_memory = mem_val;286} else {287_physical_memory = 256*1024*1024; // fallback (XXXBSD?)288}289290#ifdef __OpenBSD__291{292// limit _physical_memory memory view on OpenBSD since293// datasize rlimit restricts us anyway.294struct rlimit limits;295getrlimit(RLIMIT_DATA, &limits);296_physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);297}298#endif299}300301#ifdef __APPLE__302static const char *get_home() {303const char *home_dir = ::getenv("HOME");304if ((home_dir == NULL) || (*home_dir == '\0')) {305struct passwd *passwd_info = getpwuid(geteuid());306if (passwd_info != NULL) {307home_dir = passwd_info->pw_dir;308}309}310311return home_dir;312}313#endif314315void os::init_system_properties_values() {316// The next steps are taken in the product version:317//318// Obtain the JAVA_HOME value from the location of libjvm.so.319// This library should be located at:320// <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.321//322// If "/jre/lib/" appears at the right place in the path, then we323// assume libjvm.so is installed in a JDK and we use this path.324//325// Otherwise exit with message: "Could not create the Java virtual machine."326//327// The following extra steps are taken in the debugging version:328//329// If "/jre/lib/" does NOT appear at the right place in the path330// instead of exit check for $JAVA_HOME environment variable.331//332// If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,333// then we append a fake suffix "hotspot/libjvm.so" to this path so334// it looks like libjvm.so is installed there335// <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.336//337// Otherwise exit.338//339// Important note: if the location of libjvm.so changes this340// code needs to be changed accordingly.341342// See ld(1):343// The linker uses the following search paths to locate required344// shared libraries:345// 1: ...346// ...347// 7: The default directories, normally /lib and /usr/lib.348#ifndef DEFAULT_LIBPATH349#define DEFAULT_LIBPATH "/lib:/usr/lib"350#endif351352// Base path of extensions installed on the system.353#define SYS_EXT_DIR "/usr/java/packages"354#define EXTENSIONS_DIR "/lib/ext"355#define ENDORSED_DIR "/lib/endorsed"356357#ifndef __APPLE__358359// Buffer that fits several sprintfs.360// Note that the space for the colon and the trailing null are provided361// by the nulls included by the sizeof operator.362const size_t bufsize =363MAX3((size_t)MAXPATHLEN, // For dll_dir & friends.364(size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir365(size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir366char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);367368// sysclasspath, java_home, dll_dir369{370char *pslash;371os::jvm_path(buf, bufsize);372373// Found the full path to libjvm.so.374// Now cut the path to <java_home>/jre if we can.375*(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.376pslash = strrchr(buf, '/');377if (pslash != NULL) {378*pslash = '\0'; // Get rid of /{client|server|hotspot}.379}380Arguments::set_dll_dir(buf);381382if (pslash != NULL) {383pslash = strrchr(buf, '/');384if (pslash != NULL) {385*pslash = '\0'; // Get rid of /<arch>.386pslash = strrchr(buf, '/');387if (pslash != NULL) {388*pslash = '\0'; // Get rid of /lib.389}390}391}392Arguments::set_java_home(buf);393set_boot_path('/', ':');394}395396// Where to look for native libraries.397//398// Note: Due to a legacy implementation, most of the library path399// is set in the launcher. This was to accomodate linking restrictions400// on legacy Bsd implementations (which are no longer supported).401// Eventually, all the library path setting will be done here.402//403// However, to prevent the proliferation of improperly built native404// libraries, the new path component /usr/java/packages is added here.405// Eventually, all the library path setting will be done here.406{407// Get the user setting of LD_LIBRARY_PATH, and prepended it. It408// should always exist (until the legacy problem cited above is409// addressed).410const char *v = ::getenv("LD_LIBRARY_PATH");411const char *v_colon = ":";412if (v == NULL) { v = ""; v_colon = ""; }413// That's +1 for the colon and +1 for the trailing '\0'.414char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,415strlen(v) + 1 +416sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,417mtInternal);418sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);419Arguments::set_library_path(ld_library_path);420FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);421}422423// Extensions directories.424sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());425Arguments::set_ext_dirs(buf);426427// Endorsed standards default directory.428sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());429Arguments::set_endorsed_dirs(buf);430431FREE_C_HEAP_ARRAY(char, buf, mtInternal);432433#else // __APPLE__434435#define SYS_EXTENSIONS_DIR "/Library/Java/Extensions"436#define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"437438const char *user_home_dir = get_home();439// The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.440size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +441sizeof(SYS_EXTENSIONS_DIRS);442443// Buffer that fits several sprintfs.444// Note that the space for the colon and the trailing null are provided445// by the nulls included by the sizeof operator.446const size_t bufsize =447MAX3((size_t)MAXPATHLEN, // for dll_dir & friends.448(size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size, // extensions dir449(size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir450char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);451452// sysclasspath, java_home, dll_dir453{454char *pslash;455os::jvm_path(buf, bufsize);456457// Found the full path to libjvm.so.458// Now cut the path to <java_home>/jre if we can.459*(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.460pslash = strrchr(buf, '/');461if (pslash != NULL) {462*pslash = '\0'; // Get rid of /{client|server|hotspot}.463}464Arguments::set_dll_dir(buf);465466if (pslash != NULL) {467pslash = strrchr(buf, '/');468if (pslash != NULL) {469*pslash = '\0'; // Get rid of /lib.470}471}472Arguments::set_java_home(buf);473set_boot_path('/', ':');474}475476// Where to look for native libraries.477//478// Note: Due to a legacy implementation, most of the library path479// is set in the launcher. This was to accomodate linking restrictions480// on legacy Bsd implementations (which are no longer supported).481// Eventually, all the library path setting will be done here.482//483// However, to prevent the proliferation of improperly built native484// libraries, the new path component /usr/java/packages is added here.485// Eventually, all the library path setting will be done here.486{487// Get the user setting of LD_LIBRARY_PATH, and prepended it. It488// should always exist (until the legacy problem cited above is489// addressed).490// Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code491// can specify a directory inside an app wrapper492const char *l = ::getenv("JAVA_LIBRARY_PATH");493const char *l_colon = ":";494if (l == NULL) { l = ""; l_colon = ""; }495496const char *v = ::getenv("DYLD_LIBRARY_PATH");497const char *v_colon = ":";498if (v == NULL) { v = ""; v_colon = ""; }499500// Apple's Java6 has "." at the beginning of java.library.path.501// OpenJDK on Windows has "." at the end of java.library.path.502// OpenJDK on Linux and Solaris don't have "." in java.library.path503// at all. To ease the transition from Apple's Java6 to OpenJDK7,504// "." is appended to the end of java.library.path. Yes, this505// could cause a change in behavior, but Apple's Java6 behavior506// can be achieved by putting "." at the beginning of the507// JAVA_LIBRARY_PATH environment variable.508char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,509strlen(v) + 1 + strlen(l) + 1 +510system_ext_size + 3,511mtInternal);512sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",513v, v_colon, l, l_colon, user_home_dir);514Arguments::set_library_path(ld_library_path);515FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);516}517518// Extensions directories.519//520// Note that the space for the colon and the trailing null are provided521// by the nulls included by the sizeof operator (so actually one byte more522// than necessary is allocated).523sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,524user_home_dir, Arguments::get_java_home());525Arguments::set_ext_dirs(buf);526527// Endorsed standards default directory.528sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());529Arguments::set_endorsed_dirs(buf);530531FREE_C_HEAP_ARRAY(char, buf, mtInternal);532533#undef SYS_EXTENSIONS_DIR534#undef SYS_EXTENSIONS_DIRS535536#endif // __APPLE__537538#undef SYS_EXT_DIR539#undef EXTENSIONS_DIR540#undef ENDORSED_DIR541}542543////////////////////////////////////////////////////////////////////////////////544// breakpoint support545546void os::breakpoint() {547BREAKPOINT;548}549550extern "C" void breakpoint() {551// use debugger to set breakpoint here552}553554////////////////////////////////////////////////////////////////////////////////555// signal support556557debug_only(static bool signal_sets_initialized = false);558static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;559560bool os::Bsd::is_sig_ignored(int sig) {561struct sigaction oact;562sigaction(sig, (struct sigaction*)NULL, &oact);563void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)564: CAST_FROM_FN_PTR(void*, oact.sa_handler);565if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))566return true;567else568return false;569}570571void os::Bsd::signal_sets_init() {572// Should also have an assertion stating we are still single-threaded.573assert(!signal_sets_initialized, "Already initialized");574// Fill in signals that are necessarily unblocked for all threads in575// the VM. Currently, we unblock the following signals:576// SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden577// by -Xrs (=ReduceSignalUsage));578// BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all579// other threads. The "ReduceSignalUsage" boolean tells us not to alter580// the dispositions or masks wrt these signals.581// Programs embedding the VM that want to use the above signals for their582// own purposes must, at this time, use the "-Xrs" option to prevent583// interference with shutdown hooks and BREAK_SIGNAL thread dumping.584// (See bug 4345157, and other related bugs).585// In reality, though, unblocking these signals is really a nop, since586// these signals are not blocked by default.587sigemptyset(&unblocked_sigs);588sigemptyset(&allowdebug_blocked_sigs);589sigaddset(&unblocked_sigs, SIGILL);590sigaddset(&unblocked_sigs, SIGSEGV);591sigaddset(&unblocked_sigs, SIGBUS);592sigaddset(&unblocked_sigs, SIGFPE);593sigaddset(&unblocked_sigs, SR_signum);594595if (!ReduceSignalUsage) {596if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {597sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);598sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);599}600if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {601sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);602sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);603}604if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {605sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);606sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);607}608}609// Fill in signals that are blocked by all but the VM thread.610sigemptyset(&vm_sigs);611if (!ReduceSignalUsage)612sigaddset(&vm_sigs, BREAK_SIGNAL);613debug_only(signal_sets_initialized = true);614615}616617// These are signals that are unblocked while a thread is running Java.618// (For some reason, they get blocked by default.)619sigset_t* os::Bsd::unblocked_signals() {620assert(signal_sets_initialized, "Not initialized");621return &unblocked_sigs;622}623624// These are the signals that are blocked while a (non-VM) thread is625// running Java. Only the VM thread handles these signals.626sigset_t* os::Bsd::vm_signals() {627assert(signal_sets_initialized, "Not initialized");628return &vm_sigs;629}630631// These are signals that are blocked during cond_wait to allow debugger in632sigset_t* os::Bsd::allowdebug_blocked_signals() {633assert(signal_sets_initialized, "Not initialized");634return &allowdebug_blocked_sigs;635}636637void os::Bsd::hotspot_sigmask(Thread* thread) {638639//Save caller's signal mask before setting VM signal mask640sigset_t caller_sigmask;641pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);642643OSThread* osthread = thread->osthread();644osthread->set_caller_sigmask(caller_sigmask);645646pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);647648if (!ReduceSignalUsage) {649if (thread->is_VM_thread()) {650// Only the VM thread handles BREAK_SIGNAL ...651pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);652} else {653// ... all other threads block BREAK_SIGNAL654pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);655}656}657}658659660//////////////////////////////////////////////////////////////////////////////661// create new thread662663// check if it's safe to start a new thread664static bool _thread_safety_check(Thread* thread) {665return true;666}667668#ifdef __APPLE__669// library handle for calling objc_registerThreadWithCollector()670// without static linking to the libobjc library671#define OBJC_LIB "/usr/lib/libobjc.dylib"672#define OBJC_GCREGISTER "objc_registerThreadWithCollector"673typedef void (*objc_registerThreadWithCollector_t)();674extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;675objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;676#endif677678#ifdef __APPLE__679static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {680// Additional thread_id used to correlate threads in SA681thread_identifier_info_data_t m_ident_info;682mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;683684thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,685(thread_info_t) &m_ident_info, &count);686687return m_ident_info.thread_id;688}689#endif690691// Thread start routine for all newly created threads692static void *java_start(Thread *thread) {693// Try to randomize the cache line index of hot stack frames.694// This helps when threads of the same stack traces evict each other's695// cache lines. The threads can be either from the same JVM instance, or696// from different JVM instances. The benefit is especially true for697// processors with hyperthreading technology.698static int counter = 0;699int pid = os::current_process_id();700alloca(((pid ^ counter++) & 7) * 128);701702ThreadLocalStorage::set_thread(thread);703704OSThread* osthread = thread->osthread();705Monitor* sync = osthread->startThread_lock();706707// non floating stack BsdThreads needs extra check, see above708if (!_thread_safety_check(thread)) {709// notify parent thread710MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);711osthread->set_state(ZOMBIE);712sync->notify_all();713return NULL;714}715716osthread->set_thread_id(os::Bsd::gettid());717718#ifdef __APPLE__719uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());720guarantee(unique_thread_id != 0, "unique thread id was not found");721osthread->set_unique_thread_id(unique_thread_id);722#endif723// initialize signal mask for this thread724os::Bsd::hotspot_sigmask(thread);725726// initialize floating point control register727os::Bsd::init_thread_fpu_state();728729#ifdef __APPLE__730// register thread with objc gc731if (objc_registerThreadWithCollectorFunction != NULL) {732objc_registerThreadWithCollectorFunction();733}734#endif735736// handshaking with parent thread737{738MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);739740// notify parent thread741osthread->set_state(INITIALIZED);742sync->notify_all();743744// wait until os::start_thread()745while (osthread->get_state() == INITIALIZED) {746sync->wait(Mutex::_no_safepoint_check_flag);747}748}749750// call one more level start routine751thread->run();752753return 0;754}755756bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {757assert(thread->osthread() == NULL, "caller responsible");758759// Allocate the OSThread object760OSThread* osthread = new OSThread(NULL, NULL);761if (osthread == NULL) {762return false;763}764765// set the correct thread state766osthread->set_thread_type(thr_type);767768// Initial state is ALLOCATED but not INITIALIZED769osthread->set_state(ALLOCATED);770771thread->set_osthread(osthread);772773// init thread attributes774pthread_attr_t attr;775pthread_attr_init(&attr);776pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);777778// stack size779if (os::Bsd::supports_variable_stack_size()) {780// calculate stack size if it's not specified by caller781if (stack_size == 0) {782stack_size = os::Bsd::default_stack_size(thr_type);783784switch (thr_type) {785case os::java_thread:786// Java threads use ThreadStackSize which default value can be787// changed with the flag -Xss788assert (JavaThread::stack_size_at_create() > 0, "this should be set");789stack_size = JavaThread::stack_size_at_create();790break;791case os::compiler_thread:792if (CompilerThreadStackSize > 0) {793stack_size = (size_t)(CompilerThreadStackSize * K);794break;795} // else fall through:796// use VMThreadStackSize if CompilerThreadStackSize is not defined797case os::vm_thread:798case os::pgc_thread:799case os::cgc_thread:800case os::watcher_thread:801if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);802break;803}804}805806stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);807pthread_attr_setstacksize(&attr, stack_size);808} else {809// let pthread_create() pick the default value.810}811812ThreadState state;813814{815pthread_t tid;816int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);817818pthread_attr_destroy(&attr);819820if (ret != 0) {821if (PrintMiscellaneous && (Verbose || WizardMode)) {822perror("pthread_create()");823}824// Need to clean up stuff we've allocated so far825thread->set_osthread(NULL);826delete osthread;827return false;828}829830// Store pthread info into the OSThread831osthread->set_pthread_id(tid);832833// Wait until child thread is either initialized or aborted834{835Monitor* sync_with_child = osthread->startThread_lock();836MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);837while ((state = osthread->get_state()) == ALLOCATED) {838sync_with_child->wait(Mutex::_no_safepoint_check_flag);839}840}841842}843844// Aborted due to thread limit being reached845if (state == ZOMBIE) {846thread->set_osthread(NULL);847delete osthread;848return false;849}850851// The thread is returned suspended (in state INITIALIZED),852// and is started higher up in the call chain853assert(state == INITIALIZED, "race condition");854return true;855}856857/////////////////////////////////////////////////////////////////////////////858// attach existing thread859860// bootstrap the main thread861bool os::create_main_thread(JavaThread* thread) {862assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");863return create_attached_thread(thread);864}865866bool os::create_attached_thread(JavaThread* thread) {867#ifdef ASSERT868thread->verify_not_published();869#endif870871// Allocate the OSThread object872OSThread* osthread = new OSThread(NULL, NULL);873874if (osthread == NULL) {875return false;876}877878osthread->set_thread_id(os::Bsd::gettid());879880// Store pthread info into the OSThread881#ifdef __APPLE__882uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());883guarantee(unique_thread_id != 0, "just checking");884osthread->set_unique_thread_id(unique_thread_id);885#endif886osthread->set_pthread_id(::pthread_self());887888// initialize floating point control register889os::Bsd::init_thread_fpu_state();890891// Initial thread state is RUNNABLE892osthread->set_state(RUNNABLE);893894thread->set_osthread(osthread);895896// initialize signal mask for this thread897// and save the caller's signal mask898os::Bsd::hotspot_sigmask(thread);899900return true;901}902903void os::pd_start_thread(Thread* thread) {904OSThread * osthread = thread->osthread();905assert(osthread->get_state() != INITIALIZED, "just checking");906Monitor* sync_with_child = osthread->startThread_lock();907MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);908sync_with_child->notify();909}910911// Free Bsd resources related to the OSThread912void os::free_thread(OSThread* osthread) {913assert(osthread != NULL, "osthread not set");914915if (Thread::current()->osthread() == osthread) {916// Restore caller's signal mask917sigset_t sigmask = osthread->caller_sigmask();918pthread_sigmask(SIG_SETMASK, &sigmask, NULL);919}920921delete osthread;922}923924//////////////////////////////////////////////////////////////////////////////925// thread local storage926927// Restore the thread pointer if the destructor is called. This is in case928// someone from JNI code sets up a destructor with pthread_key_create to run929// detachCurrentThread on thread death. Unless we restore the thread pointer we930// will hang or crash. When detachCurrentThread is called the key will be set931// to null and we will not be called again. If detachCurrentThread is never932// called we could loop forever depending on the pthread implementation.933static void restore_thread_pointer(void* p) {934Thread* thread = (Thread*) p;935os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread);936}937938int os::allocate_thread_local_storage() {939pthread_key_t key;940int rslt = pthread_key_create(&key, restore_thread_pointer);941assert(rslt == 0, "cannot allocate thread local storage");942return (int)key;943}944945// Note: This is currently not used by VM, as we don't destroy TLS key946// on VM exit.947void os::free_thread_local_storage(int index) {948int rslt = pthread_key_delete((pthread_key_t)index);949assert(rslt == 0, "invalid index");950}951952void os::thread_local_storage_at_put(int index, void* value) {953int rslt = pthread_setspecific((pthread_key_t)index, value);954assert(rslt == 0, "pthread_setspecific failed");955}956957extern "C" Thread* get_thread() {958return ThreadLocalStorage::thread();959}960961962////////////////////////////////////////////////////////////////////////////////963// time support964965// Time since start-up in seconds to a fine granularity.966// Used by VMSelfDestructTimer and the MemProfiler.967double os::elapsedTime() {968969return ((double)os::elapsed_counter()) / os::elapsed_frequency();970}971972jlong os::elapsed_counter() {973return javaTimeNanos() - initial_time_count;974}975976jlong os::elapsed_frequency() {977return NANOSECS_PER_SEC; // nanosecond resolution978}979980bool os::supports_vtime() { return true; }981bool os::enable_vtime() { return false; }982bool os::vtime_enabled() { return false; }983984double os::elapsedVTime() {985// better than nothing, but not much986return elapsedTime();987}988989jlong os::javaTimeMillis() {990timeval time;991int status = gettimeofday(&time, NULL);992assert(status != -1, "bsd error");993return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);994}995996#ifndef __APPLE__997#ifndef CLOCK_MONOTONIC998#define CLOCK_MONOTONIC (1)999#endif1000#endif10011002#ifdef __APPLE__1003void os::Bsd::clock_init() {1004mach_timebase_info(&_timebase_info);1005}1006#else1007void os::Bsd::clock_init() {1008struct timespec res;1009struct timespec tp;1010if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&1011::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {1012// yes, monotonic clock is supported1013_clock_gettime = ::clock_gettime;1014}1015}1016#endif101710181019#ifdef __APPLE__10201021jlong os::javaTimeNanos() {1022const uint64_t tm = mach_absolute_time();1023const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;1024const uint64_t prev = Bsd::_max_abstime;1025if (now <= prev) {1026return prev; // same or retrograde time;1027}1028const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev);1029assert(obsv >= prev, "invariant"); // Monotonicity1030// If the CAS succeeded then we're done and return "now".1031// If the CAS failed and the observed value "obsv" is >= now then1032// we should return "obsv". If the CAS failed and now > obsv > prv then1033// some other thread raced this thread and installed a new value, in which case1034// we could either (a) retry the entire operation, (b) retry trying to install now1035// or (c) just return obsv. We use (c). No loop is required although in some cases1036// we might discard a higher "now" value in deference to a slightly lower but freshly1037// installed obsv value. That's entirely benign -- it admits no new orderings compared1038// to (a) or (b) -- and greatly reduces coherence traffic.1039// We might also condition (c) on the magnitude of the delta between obsv and now.1040// Avoiding excessive CAS operations to hot RW locations is critical.1041// See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate1042return (prev == obsv) ? now : obsv;1043}10441045#else // __APPLE__10461047jlong os::javaTimeNanos() {1048if (Bsd::supports_monotonic_clock()) {1049struct timespec tp;1050int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp);1051assert(status == 0, "gettime error");1052jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);1053return result;1054} else {1055timeval time;1056int status = gettimeofday(&time, NULL);1057assert(status != -1, "bsd error");1058jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);1059return 1000 * usecs;1060}1061}10621063#endif // __APPLE__10641065void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {1066if (Bsd::supports_monotonic_clock()) {1067info_ptr->max_value = ALL_64_BITS;10681069// CLOCK_MONOTONIC - amount of time since some arbitrary point in the past1070info_ptr->may_skip_backward = false; // not subject to resetting or drifting1071info_ptr->may_skip_forward = false; // not subject to resetting or drifting1072} else {1073// gettimeofday - based on time in seconds since the Epoch thus does not wrap1074info_ptr->max_value = ALL_64_BITS;10751076// gettimeofday is a real time clock so it skips1077info_ptr->may_skip_backward = true;1078info_ptr->may_skip_forward = true;1079}10801081info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time1082}10831084// Return the real, user, and system times in seconds from an1085// arbitrary fixed point in the past.1086bool os::getTimesSecs(double* process_real_time,1087double* process_user_time,1088double* process_system_time) {1089struct tms ticks;1090clock_t real_ticks = times(&ticks);10911092if (real_ticks == (clock_t) (-1)) {1093return false;1094} else {1095double ticks_per_second = (double) clock_tics_per_sec;1096*process_user_time = ((double) ticks.tms_utime) / ticks_per_second;1097*process_system_time = ((double) ticks.tms_stime) / ticks_per_second;1098*process_real_time = ((double) real_ticks) / ticks_per_second;10991100return true;1101}1102}110311041105char * os::local_time_string(char *buf, size_t buflen) {1106struct tm t;1107time_t long_time;1108time(&long_time);1109localtime_r(&long_time, &t);1110jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",1111t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,1112t.tm_hour, t.tm_min, t.tm_sec);1113return buf;1114}11151116struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {1117return localtime_r(clock, res);1118}11191120////////////////////////////////////////////////////////////////////////////////1121// runtime exit support11221123// Note: os::shutdown() might be called very early during initialization, or1124// called from signal handler. Before adding something to os::shutdown(), make1125// sure it is async-safe and can handle partially initialized VM.1126void os::shutdown() {11271128// allow PerfMemory to attempt cleanup of any persistent resources1129perfMemory_exit();11301131// needs to remove object in file system1132AttachListener::abort();11331134// flush buffered output, finish log files1135ostream_abort();11361137// Check for abort hook1138abort_hook_t abort_hook = Arguments::abort_hook();1139if (abort_hook != NULL) {1140abort_hook();1141}11421143}11441145// Note: os::abort() might be called very early during initialization, or1146// called from signal handler. Before adding something to os::abort(), make1147// sure it is async-safe and can handle partially initialized VM.1148void os::abort(bool dump_core) {1149os::shutdown();1150if (dump_core) {1151#ifndef PRODUCT1152fdStream out(defaultStream::output_fd());1153out.print_raw("Current thread is ");1154char buf[16];1155jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());1156out.print_raw_cr(buf);1157out.print_raw_cr("Dumping core ...");1158#endif1159::abort(); // dump core1160}11611162::exit(1);1163}11641165// Die immediately, no exit hook, no abort hook, no cleanup.1166void os::die() {1167// _exit() on BsdThreads only kills current thread1168::abort();1169}11701171// This method is a copy of JDK's sysGetLastErrorString1172// from src/solaris/hpi/src/system_md.c11731174size_t os::lasterror(char *buf, size_t len) {11751176if (errno == 0) return 0;11771178const char *s = ::strerror(errno);1179size_t n = ::strlen(s);1180if (n >= len) {1181n = len - 1;1182}1183::strncpy(buf, s, n);1184buf[n] = '\0';1185return n;1186}11871188// Information of current thread in variety of formats1189pid_t os::Bsd::gettid() {1190int retval = -1;11911192#ifdef __APPLE__ //XNU kernel1193// despite the fact mach port is actually not a thread id use it1194// instead of syscall(SYS_thread_selfid) as it certainly fits to u41195retval = ::pthread_mach_thread_np(::pthread_self());1196guarantee(retval != 0, "just checking");1197return retval;11981199#else1200#ifdef __FreeBSD__1201retval = syscall(SYS_thr_self);1202#else1203#ifdef __OpenBSD__1204retval = syscall(SYS_getthrid);1205#else1206#ifdef __NetBSD__1207retval = (pid_t) syscall(SYS__lwp_self);1208#endif1209#endif1210#endif1211#endif12121213if (retval == -1) {1214return getpid();1215}1216}12171218intx os::current_thread_id() {1219#ifdef __APPLE__1220return (intx)::pthread_mach_thread_np(::pthread_self());1221#else1222return (intx)::pthread_self();1223#endif1224}12251226int os::current_process_id() {12271228// Under the old bsd thread library, bsd gives each thread1229// its own process id. Because of this each thread will return1230// a different pid if this method were to return the result1231// of getpid(2). Bsd provides no api that returns the pid1232// of the launcher thread for the vm. This implementation1233// returns a unique pid, the pid of the launcher thread1234// that starts the vm 'process'.12351236// Under the NPTL, getpid() returns the same pid as the1237// launcher thread rather than a unique pid per thread.1238// Use gettid() if you want the old pre NPTL behaviour.12391240// if you are looking for the result of a call to getpid() that1241// returns a unique pid for the calling thread, then look at the1242// OSThread::thread_id() method in osThread_bsd.hpp file12431244return (int)(_initial_pid ? _initial_pid : getpid());1245}12461247// DLL functions12481249#define JNI_LIB_PREFIX "lib"1250#ifdef __APPLE__1251#define JNI_LIB_SUFFIX ".dylib"1252#else1253#define JNI_LIB_SUFFIX ".so"1254#endif12551256const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }12571258// This must be hard coded because it's the system's temporary1259// directory not the java application's temp directory, ala java.io.tmpdir.1260#ifdef __APPLE__1261// macosx has a secure per-user temporary directory1262char temp_path_storage[PATH_MAX];1263const char* os::get_temp_directory() {1264static char *temp_path = NULL;1265if (temp_path == NULL) {1266int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);1267if (pathSize == 0 || pathSize > PATH_MAX) {1268strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));1269}1270temp_path = temp_path_storage;1271}1272return temp_path;1273}1274#else /* __APPLE__ */1275const char* os::get_temp_directory() { return "/tmp"; }1276#endif /* __APPLE__ */12771278static bool file_exists(const char* filename) {1279struct stat statbuf;1280if (filename == NULL || strlen(filename) == 0) {1281return false;1282}1283return os::stat(filename, &statbuf) == 0;1284}12851286bool os::dll_build_name(char* buffer, size_t buflen,1287const char* pname, const char* fname) {1288bool retval = false;1289// Copied from libhpi1290const size_t pnamelen = pname ? strlen(pname) : 0;12911292// Return error on buffer overflow.1293if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {1294return retval;1295}12961297if (pnamelen == 0) {1298snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);1299retval = true;1300} else if (strchr(pname, *os::path_separator()) != NULL) {1301int n;1302char** pelements = split_path(pname, &n);1303if (pelements == NULL) {1304return false;1305}1306for (int i = 0 ; i < n ; i++) {1307// Really shouldn't be NULL, but check can't hurt1308if (pelements[i] == NULL || strlen(pelements[i]) == 0) {1309continue; // skip the empty path values1310}1311snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,1312pelements[i], fname);1313if (file_exists(buffer)) {1314retval = true;1315break;1316}1317}1318// release the storage1319for (int i = 0 ; i < n ; i++) {1320if (pelements[i] != NULL) {1321FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);1322}1323}1324if (pelements != NULL) {1325FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);1326}1327} else {1328snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);1329retval = true;1330}1331return retval;1332}13331334// check if addr is inside libjvm.so1335bool os::address_is_in_vm(address addr) {1336static address libjvm_base_addr;1337Dl_info dlinfo;13381339if (libjvm_base_addr == NULL) {1340if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {1341libjvm_base_addr = (address)dlinfo.dli_fbase;1342}1343assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");1344}13451346if (dladdr((void *)addr, &dlinfo) != 0) {1347if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;1348}13491350return false;1351}135213531354#define MACH_MAXSYMLEN 25613551356bool os::dll_address_to_function_name(address addr, char *buf,1357int buflen, int *offset) {1358// buf is not optional, but offset is optional1359assert(buf != NULL, "sanity check");13601361Dl_info dlinfo;1362char localbuf[MACH_MAXSYMLEN];13631364if (dladdr((void*)addr, &dlinfo) != 0) {1365// see if we have a matching symbol1366if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {1367if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {1368jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);1369}1370if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;1371return true;1372}1373// no matching symbol so try for just file info1374if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {1375if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),1376buf, buflen, offset, dlinfo.dli_fname)) {1377return true;1378}1379}13801381// Handle non-dynamic manually:1382if (dlinfo.dli_fbase != NULL &&1383Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,1384dlinfo.dli_fbase)) {1385if (!Decoder::demangle(localbuf, buf, buflen)) {1386jio_snprintf(buf, buflen, "%s", localbuf);1387}1388return true;1389}1390}1391buf[0] = '\0';1392if (offset != NULL) *offset = -1;1393return false;1394}13951396// ported from solaris version1397bool os::dll_address_to_library_name(address addr, char* buf,1398int buflen, int* offset) {1399// buf is not optional, but offset is optional1400assert(buf != NULL, "sanity check");14011402Dl_info dlinfo;14031404if (dladdr((void*)addr, &dlinfo) != 0) {1405if (dlinfo.dli_fname != NULL) {1406jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);1407}1408if (dlinfo.dli_fbase != NULL && offset != NULL) {1409*offset = addr - (address)dlinfo.dli_fbase;1410}1411return true;1412}14131414buf[0] = '\0';1415if (offset) *offset = -1;1416return false;1417}14181419// Loads .dll/.so and1420// in case of error it checks if .dll/.so was built for the1421// same architecture as Hotspot is running on14221423#ifdef __APPLE__1424void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {1425void * result= ::dlopen(filename, RTLD_LAZY);1426if (result != NULL) {1427// Successful loading1428return result;1429}14301431// Read system error message into ebuf1432::strncpy(ebuf, ::dlerror(), ebuflen-1);1433ebuf[ebuflen-1]='\0';14341435return NULL;1436}1437#else1438void * os::dll_load(const char *filename, char *ebuf, int ebuflen)1439{1440void * result= ::dlopen(filename, RTLD_LAZY);1441if (result != NULL) {1442// Successful loading1443return result;1444}14451446Elf32_Ehdr elf_head;14471448// Read system error message into ebuf1449// It may or may not be overwritten below1450::strncpy(ebuf, ::dlerror(), ebuflen-1);1451ebuf[ebuflen-1]='\0';1452int diag_msg_max_length=ebuflen-strlen(ebuf);1453char* diag_msg_buf=ebuf+strlen(ebuf);14541455if (diag_msg_max_length==0) {1456// No more space in ebuf for additional diagnostics message1457return NULL;1458}145914601461int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);14621463if (file_descriptor < 0) {1464// Can't open library, report dlerror() message1465return NULL;1466}14671468bool failed_to_read_elf_head=1469(sizeof(elf_head)!=1470(::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;14711472::close(file_descriptor);1473if (failed_to_read_elf_head) {1474// file i/o error - report dlerror() msg1475return NULL;1476}14771478typedef struct {1479Elf32_Half code; // Actual value as defined in elf.h1480Elf32_Half compat_class; // Compatibility of archs at VM's sense1481char elf_class; // 32 or 64 bit1482char endianess; // MSB or LSB1483char* name; // String representation1484} arch_t;14851486#ifndef EM_4861487#define EM_486 6 /* Intel 80486 */1488#endif14891490#ifndef EM_MIPS_RS3_LE1491#define EM_MIPS_RS3_LE 10 /* MIPS */1492#endif14931494#ifndef EM_PPC641495#define EM_PPC64 21 /* PowerPC64 */1496#endif14971498#ifndef EM_S3901499#define EM_S390 22 /* IBM System/390 */1500#endif15011502#ifndef EM_IA_641503#define EM_IA_64 50 /* HP/Intel IA-64 */1504#endif15051506#ifndef EM_X86_641507#define EM_X86_64 62 /* AMD x86-64 */1508#endif15091510static const arch_t arch_array[]={1511{EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1512{EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1513{EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},1514{EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},1515{EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1516{EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1517{EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},1518{EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},1519{EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},1520{EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},1521{EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},1522{EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},1523{EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},1524{EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},1525{EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},1526{EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}1527};15281529#if (defined IA32)1530static Elf32_Half running_arch_code=EM_386;1531#elif (defined AMD64)1532static Elf32_Half running_arch_code=EM_X86_64;1533#elif (defined IA64)1534static Elf32_Half running_arch_code=EM_IA_64;1535#elif (defined __sparc) && (defined _LP64)1536static Elf32_Half running_arch_code=EM_SPARCV9;1537#elif (defined __sparc) && (!defined _LP64)1538static Elf32_Half running_arch_code=EM_SPARC;1539#elif (defined __powerpc64__)1540static Elf32_Half running_arch_code=EM_PPC64;1541#elif (defined __powerpc__)1542static Elf32_Half running_arch_code=EM_PPC;1543#elif (defined ARM)1544static Elf32_Half running_arch_code=EM_ARM;1545#elif (defined S390)1546static Elf32_Half running_arch_code=EM_S390;1547#elif (defined ALPHA)1548static Elf32_Half running_arch_code=EM_ALPHA;1549#elif (defined MIPSEL)1550static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;1551#elif (defined PARISC)1552static Elf32_Half running_arch_code=EM_PARISC;1553#elif (defined MIPS)1554static Elf32_Half running_arch_code=EM_MIPS;1555#elif (defined M68K)1556static Elf32_Half running_arch_code=EM_68K;1557#else1558#error Method os::dll_load requires that one of following is defined:\1559IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K1560#endif15611562// Identify compatability class for VM's architecture and library's architecture1563// Obtain string descriptions for architectures15641565arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};1566int running_arch_index=-1;15671568for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {1569if (running_arch_code == arch_array[i].code) {1570running_arch_index = i;1571}1572if (lib_arch.code == arch_array[i].code) {1573lib_arch.compat_class = arch_array[i].compat_class;1574lib_arch.name = arch_array[i].name;1575}1576}15771578assert(running_arch_index != -1,1579"Didn't find running architecture code (running_arch_code) in arch_array");1580if (running_arch_index == -1) {1581// Even though running architecture detection failed1582// we may still continue with reporting dlerror() message1583return NULL;1584}15851586if (lib_arch.endianess != arch_array[running_arch_index].endianess) {1587::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");1588return NULL;1589}15901591#ifndef S3901592if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {1593::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");1594return NULL;1595}1596#endif // !S39015971598if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {1599if ( lib_arch.name!=NULL ) {1600::snprintf(diag_msg_buf, diag_msg_max_length-1,1601" (Possible cause: can't load %s-bit .so on a %s-bit platform)",1602lib_arch.name, arch_array[running_arch_index].name);1603} else {1604::snprintf(diag_msg_buf, diag_msg_max_length-1,1605" (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",1606lib_arch.code,1607arch_array[running_arch_index].name);1608}1609}16101611return NULL;1612}1613#endif /* !__APPLE__ */16141615void* os::get_default_process_handle() {1616#ifdef __APPLE__1617// MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY1618// to avoid finding unexpected symbols on second (or later)1619// loads of a library.1620return (void*)::dlopen(NULL, RTLD_FIRST);1621#else1622return (void*)::dlopen(NULL, RTLD_LAZY);1623#endif1624}16251626// XXX: Do we need a lock around this as per Linux?1627void* os::dll_lookup(void* handle, const char* name) {1628return dlsym(handle, name);1629}163016311632static bool _print_ascii_file(const char* filename, outputStream* st) {1633int fd = ::open(filename, O_RDONLY);1634if (fd == -1) {1635return false;1636}16371638char buf[32];1639int bytes;1640while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {1641st->print_raw(buf, bytes);1642}16431644::close(fd);16451646return true;1647}16481649void os::print_dll_info(outputStream *st) {1650st->print_cr("Dynamic libraries:");1651#ifdef RTLD_DI_LINKMAP1652Dl_info dli;1653void *handle;1654Link_map *map;1655Link_map *p;16561657if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||1658dli.dli_fname == NULL) {1659st->print_cr("Error: Cannot print dynamic libraries.");1660return;1661}1662handle = dlopen(dli.dli_fname, RTLD_LAZY);1663if (handle == NULL) {1664st->print_cr("Error: Cannot print dynamic libraries.");1665return;1666}1667dlinfo(handle, RTLD_DI_LINKMAP, &map);1668if (map == NULL) {1669st->print_cr("Error: Cannot print dynamic libraries.");1670return;1671}16721673while (map->l_prev != NULL)1674map = map->l_prev;16751676while (map != NULL) {1677st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);1678map = map->l_next;1679}16801681dlclose(handle);1682#elif defined(__APPLE__)1683for (uint32_t i = 1; i < _dyld_image_count(); i++) {1684st->print_cr(PTR_FORMAT " \t%s", _dyld_get_image_header(i),1685_dyld_get_image_name(i));1686}1687#else1688st->print_cr("Error: Cannot print dynamic libraries.");1689#endif1690}16911692int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {1693#ifdef RTLD_DI_LINKMAP1694Dl_info dli;1695void *handle;1696Link_map *map;1697Link_map *p;16981699if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||1700dli.dli_fname == NULL) {1701return 1;1702}1703handle = dlopen(dli.dli_fname, RTLD_LAZY);1704if (handle == NULL) {1705return 1;1706}1707dlinfo(handle, RTLD_DI_LINKMAP, &map);1708if (map == NULL) {1709dlclose(handle);1710return 1;1711}17121713while (map->l_prev != NULL)1714map = map->l_prev;17151716while (map != NULL) {1717// Value for top_address is returned as 0 since we don't have any information about module size1718if (callback(map->l_name, (address)map->l_addr, (address)0, param)) {1719dlclose(handle);1720return 1;1721}1722map = map->l_next;1723}17241725dlclose(handle);1726#elif defined(__APPLE__)1727for (uint32_t i = 1; i < _dyld_image_count(); i++) {1728// Value for top_address is returned as 0 since we don't have any information about module size1729if (callback(_dyld_get_image_name(i), (address)_dyld_get_image_header(i), (address)0, param)) {1730return 1;1731}1732}1733return 0;1734#else1735return 1;1736#endif1737}17381739void os::print_os_info_brief(outputStream* st) {1740st->print("Bsd");17411742os::Posix::print_uname_info(st);1743}17441745void os::print_os_info(outputStream* st) {1746st->print("OS:");1747st->print("Bsd");17481749os::Posix::print_uname_info(st);17501751os::Posix::print_rlimit_info(st);17521753os::Posix::print_load_average(st);1754}17551756void os::pd_print_cpu_info(outputStream* st) {1757// Nothing to do for now.1758}17591760void os::print_memory_info(outputStream* st) {17611762st->print("Memory:");1763st->print(" %dk page", os::vm_page_size()>>10);17641765st->print(", physical " UINT64_FORMAT "k",1766os::physical_memory() >> 10);1767st->print("(" UINT64_FORMAT "k free)",1768os::available_memory() >> 10);1769st->cr();17701771// meminfo1772st->print("\n/proc/meminfo:\n");1773_print_ascii_file("/proc/meminfo", st);1774st->cr();1775}17761777void os::print_siginfo(outputStream* st, void* siginfo) {1778const siginfo_t* si = (const siginfo_t*)siginfo;17791780os::Posix::print_siginfo_brief(st, si);17811782if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&1783UseSharedSpaces) {1784FileMapInfo* mapinfo = FileMapInfo::current_info();1785if (mapinfo->is_in_shared_space(si->si_addr)) {1786st->print("\n\nError accessing class data sharing archive." \1787" Mapped file inaccessible during execution, " \1788" possible disk/network problem.");1789}1790}1791st->cr();1792}179317941795static void print_signal_handler(outputStream* st, int sig,1796char* buf, size_t buflen);17971798void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {1799st->print_cr("Signal Handlers:");1800print_signal_handler(st, SIGSEGV, buf, buflen);1801print_signal_handler(st, SIGBUS , buf, buflen);1802print_signal_handler(st, SIGFPE , buf, buflen);1803print_signal_handler(st, SIGPIPE, buf, buflen);1804print_signal_handler(st, SIGXFSZ, buf, buflen);1805print_signal_handler(st, SIGILL , buf, buflen);1806print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);1807print_signal_handler(st, SR_signum, buf, buflen);1808print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);1809print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);1810print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);1811print_signal_handler(st, BREAK_SIGNAL, buf, buflen);1812}18131814static char saved_jvm_path[MAXPATHLEN] = {0};18151816// Find the full path to the current module, libjvm1817void os::jvm_path(char *buf, jint buflen) {1818// Error checking.1819if (buflen < MAXPATHLEN) {1820assert(false, "must use a large-enough buffer");1821buf[0] = '\0';1822return;1823}1824// Lazy resolve the path to current module.1825if (saved_jvm_path[0] != 0) {1826strcpy(buf, saved_jvm_path);1827return;1828}18291830char dli_fname[MAXPATHLEN];1831bool ret = dll_address_to_library_name(1832CAST_FROM_FN_PTR(address, os::jvm_path),1833dli_fname, sizeof(dli_fname), NULL);1834assert(ret, "cannot locate libjvm");1835char *rp = NULL;1836if (ret && dli_fname[0] != '\0') {1837rp = realpath(dli_fname, buf);1838}1839if (rp == NULL)1840return;18411842if (Arguments::created_by_gamma_launcher()) {1843// Support for the gamma launcher. Typical value for buf is1844// "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at1845// the right place in the string, then assume we are installed in a JDK and1846// we're done. Otherwise, check for a JAVA_HOME environment variable and1847// construct a path to the JVM being overridden.18481849const char *p = buf + strlen(buf) - 1;1850for (int count = 0; p > buf && count < 5; ++count) {1851for (--p; p > buf && *p != '/'; --p)1852/* empty */ ;1853}18541855if (strncmp(p, "/jre/lib/", 9) != 0) {1856// Look for JAVA_HOME in the environment.1857char* java_home_var = ::getenv("JAVA_HOME");1858if (java_home_var != NULL && java_home_var[0] != 0) {1859char* jrelib_p;1860int len;18611862// Check the current module name "libjvm"1863p = strrchr(buf, '/');1864assert(strstr(p, "/libjvm") == p, "invalid library name");18651866rp = realpath(java_home_var, buf);1867if (rp == NULL)1868return;18691870// determine if this is a legacy image or modules image1871// modules image doesn't have "jre" subdirectory1872len = strlen(buf);1873assert(len < buflen, "Ran out of buffer space");1874jrelib_p = buf + len;18751876// Add the appropriate library subdir1877snprintf(jrelib_p, buflen-len, "/jre/lib");1878if (0 != access(buf, F_OK)) {1879snprintf(jrelib_p, buflen-len, "/lib");1880}18811882// Add the appropriate client or server subdir1883len = strlen(buf);1884jrelib_p = buf + len;1885snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);1886if (0 != access(buf, F_OK)) {1887snprintf(jrelib_p, buflen-len, "%s", "");1888}18891890// If the path exists within JAVA_HOME, add the JVM library name1891// to complete the path to JVM being overridden. Otherwise fallback1892// to the path to the current library.1893if (0 == access(buf, F_OK)) {1894// Use current module name "libjvm"1895len = strlen(buf);1896snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);1897} else {1898// Fall back to path of current library1899rp = realpath(dli_fname, buf);1900if (rp == NULL)1901return;1902}1903}1904}1905}19061907strncpy(saved_jvm_path, buf, MAXPATHLEN);1908}19091910void os::print_jni_name_prefix_on(outputStream* st, int args_size) {1911// no prefix required, not even "_"1912}19131914void os::print_jni_name_suffix_on(outputStream* st, int args_size) {1915// no suffix required1916}19171918////////////////////////////////////////////////////////////////////////////////1919// sun.misc.Signal support19201921static volatile jint sigint_count = 0;19221923static void1924UserHandler(int sig, void *siginfo, void *context) {1925// 4511530 - sem_post is serialized and handled by the manager thread. When1926// the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We1927// don't want to flood the manager thread with sem_post requests.1928if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)1929return;19301931// Ctrl-C is pressed during error reporting, likely because the error1932// handler fails to abort. Let VM die immediately.1933if (sig == SIGINT && is_error_reported()) {1934os::die();1935}19361937os::signal_notify(sig);1938}19391940void* os::user_handler() {1941return CAST_FROM_FN_PTR(void*, UserHandler);1942}19431944extern "C" {1945typedef void (*sa_handler_t)(int);1946typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);1947}19481949void* os::signal(int signal_number, void* handler) {1950struct sigaction sigAct, oldSigAct;19511952sigfillset(&(sigAct.sa_mask));1953sigAct.sa_flags = SA_RESTART|SA_SIGINFO;1954sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);19551956if (sigaction(signal_number, &sigAct, &oldSigAct)) {1957// -1 means registration failed1958return (void *)-1;1959}19601961return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);1962}19631964void os::signal_raise(int signal_number) {1965::raise(signal_number);1966}19671968/*1969* The following code is moved from os.cpp for making this1970* code platform specific, which it is by its very nature.1971*/19721973// Will be modified when max signal is changed to be dynamic1974int os::sigexitnum_pd() {1975return NSIG;1976}19771978// a counter for each possible signal value1979static volatile jint pending_signals[NSIG+1] = { 0 };19801981// Bsd(POSIX) specific hand shaking semaphore.1982#ifdef __APPLE__1983typedef semaphore_t os_semaphore_t;1984#define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)1985#define SEM_WAIT(sem) semaphore_wait(sem)1986#define SEM_POST(sem) semaphore_signal(sem)1987#define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem)1988#else1989typedef sem_t os_semaphore_t;1990#define SEM_INIT(sem, value) sem_init(&sem, 0, value)1991#define SEM_WAIT(sem) sem_wait(&sem)1992#define SEM_POST(sem) sem_post(&sem)1993#define SEM_DESTROY(sem) sem_destroy(&sem)1994#endif19951996class Semaphore : public StackObj {1997public:1998Semaphore();1999~Semaphore();2000void signal();2001void wait();2002bool trywait();2003bool timedwait(unsigned int sec, int nsec);2004private:2005jlong currenttime() const;2006os_semaphore_t _semaphore;2007};20082009Semaphore::Semaphore() : _semaphore(0) {2010SEM_INIT(_semaphore, 0);2011}20122013Semaphore::~Semaphore() {2014SEM_DESTROY(_semaphore);2015}20162017void Semaphore::signal() {2018SEM_POST(_semaphore);2019}20202021void Semaphore::wait() {2022SEM_WAIT(_semaphore);2023}20242025jlong Semaphore::currenttime() const {2026struct timeval tv;2027gettimeofday(&tv, NULL);2028return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);2029}20302031#ifdef __APPLE__2032bool Semaphore::trywait() {2033return timedwait(0, 0);2034}20352036bool Semaphore::timedwait(unsigned int sec, int nsec) {2037kern_return_t kr = KERN_ABORTED;2038mach_timespec_t waitspec;2039waitspec.tv_sec = sec;2040waitspec.tv_nsec = nsec;20412042jlong starttime = currenttime();20432044kr = semaphore_timedwait(_semaphore, waitspec);2045while (kr == KERN_ABORTED) {2046jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;20472048jlong current = currenttime();2049jlong passedtime = current - starttime;20502051if (passedtime >= totalwait) {2052waitspec.tv_sec = 0;2053waitspec.tv_nsec = 0;2054} else {2055jlong waittime = totalwait - (current - starttime);2056waitspec.tv_sec = waittime / NANOSECS_PER_SEC;2057waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;2058}20592060kr = semaphore_timedwait(_semaphore, waitspec);2061}20622063return kr == KERN_SUCCESS;2064}20652066#else20672068bool Semaphore::trywait() {2069return sem_trywait(&_semaphore) == 0;2070}20712072bool Semaphore::timedwait(unsigned int sec, int nsec) {2073struct timespec ts;2074unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);20752076while (1) {2077int result = sem_timedwait(&_semaphore, &ts);2078if (result == 0) {2079return true;2080} else if (errno == EINTR) {2081continue;2082} else if (errno == ETIMEDOUT) {2083return false;2084} else {2085return false;2086}2087}2088}20892090#endif // __APPLE__20912092static os_semaphore_t sig_sem;2093static Semaphore sr_semaphore;20942095void os::signal_init_pd() {2096// Initialize signal structures2097::memset((void*)pending_signals, 0, sizeof(pending_signals));20982099// Initialize signal semaphore2100::SEM_INIT(sig_sem, 0);2101}21022103void os::signal_notify(int sig) {2104Atomic::inc(&pending_signals[sig]);2105::SEM_POST(sig_sem);2106}21072108static int check_pending_signals(bool wait) {2109Atomic::store(0, &sigint_count);2110for (;;) {2111for (int i = 0; i < NSIG + 1; i++) {2112jint n = pending_signals[i];2113if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {2114return i;2115}2116}2117if (!wait) {2118return -1;2119}2120JavaThread *thread = JavaThread::current();2121ThreadBlockInVM tbivm(thread);21222123bool threadIsSuspended;2124do {2125thread->set_suspend_equivalent();2126// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()2127::SEM_WAIT(sig_sem);21282129// were we externally suspended while we were waiting?2130threadIsSuspended = thread->handle_special_suspend_equivalent_condition();2131if (threadIsSuspended) {2132//2133// The semaphore has been incremented, but while we were waiting2134// another thread suspended us. We don't want to continue running2135// while suspended because that would surprise the thread that2136// suspended us.2137//2138::SEM_POST(sig_sem);21392140thread->java_suspend_self();2141}2142} while (threadIsSuspended);2143}2144}21452146int os::signal_lookup() {2147return check_pending_signals(false);2148}21492150int os::signal_wait() {2151return check_pending_signals(true);2152}21532154////////////////////////////////////////////////////////////////////////////////2155// Virtual Memory21562157int os::vm_page_size() {2158// Seems redundant as all get out2159assert(os::Bsd::page_size() != -1, "must call os::init");2160return os::Bsd::page_size();2161}21622163// Solaris allocates memory by pages.2164int os::vm_allocation_granularity() {2165assert(os::Bsd::page_size() != -1, "must call os::init");2166return os::Bsd::page_size();2167}21682169// Rationale behind this function:2170// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable2171// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get2172// samples for JITted code. Here we create private executable mapping over the code cache2173// and then we can use standard (well, almost, as mapping can change) way to provide2174// info for the reporting script by storing timestamp and location of symbol2175void bsd_wrap_code(char* base, size_t size) {2176static volatile jint cnt = 0;21772178if (!UseOprofile) {2179return;2180}21812182char buf[PATH_MAX + 1];2183int num = Atomic::add(1, &cnt);21842185snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",2186os::get_temp_directory(), os::current_process_id(), num);2187unlink(buf);21882189int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);21902191if (fd != -1) {2192off_t rv = ::lseek(fd, size-2, SEEK_SET);2193if (rv != (off_t)-1) {2194if (::write(fd, "", 1) == 1) {2195mmap(base, size,2196PROT_READ|PROT_WRITE|PROT_EXEC,2197MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);2198}2199}2200::close(fd);2201unlink(buf);2202}2203}22042205static void warn_fail_commit_memory(char* addr, size_t size, bool exec,2206int err) {2207warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT2208", %d) failed; error='%s' (errno=%d)", addr, size, exec,2209strerror(err), err);2210}22112212// NOTE: Bsd kernel does not really reserve the pages for us.2213// All it does is to check if there are enough free pages2214// left at the time of mmap(). This could be a potential2215// problem.2216bool os::pd_commit_memory(char* addr, size_t size, bool exec) {2217int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;2218#ifdef __OpenBSD__2219// XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD2220if (::mprotect(addr, size, prot) == 0) {2221return true;2222}2223#else2224uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,2225MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);2226if (res != (uintptr_t) MAP_FAILED) {2227return true;2228}2229#endif22302231// Warn about any commit errors we see in non-product builds just2232// in case mmap() doesn't work as described on the man page.2233NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)22342235return false;2236}22372238bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,2239bool exec) {2240// alignment_hint is ignored on this OS2241return pd_commit_memory(addr, size, exec);2242}22432244void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,2245const char* mesg) {2246assert(mesg != NULL, "mesg must be specified");2247if (!pd_commit_memory(addr, size, exec)) {2248// add extra info in product mode for vm_exit_out_of_memory():2249PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)2250vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);2251}2252}22532254void os::pd_commit_memory_or_exit(char* addr, size_t size,2255size_t alignment_hint, bool exec,2256const char* mesg) {2257// alignment_hint is ignored on this OS2258pd_commit_memory_or_exit(addr, size, exec, mesg);2259}22602261void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {2262}22632264void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {2265::madvise(addr, bytes, MADV_DONTNEED);2266}22672268void os::numa_make_global(char *addr, size_t bytes) {2269}22702271void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {2272}22732274bool os::numa_topology_changed() { return false; }22752276size_t os::numa_get_groups_num() {2277return 1;2278}22792280int os::numa_get_group_id() {2281return 0;2282}22832284size_t os::numa_get_leaf_groups(int *ids, size_t size) {2285if (size > 0) {2286ids[0] = 0;2287return 1;2288}2289return 0;2290}22912292bool os::get_page_info(char *start, page_info* info) {2293return false;2294}22952296char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {2297return end;2298}229923002301bool os::pd_uncommit_memory(char* addr, size_t size) {2302#ifdef __OpenBSD__2303// XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD2304return ::mprotect(addr, size, PROT_NONE) == 0;2305#else2306uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,2307MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);2308return res != (uintptr_t) MAP_FAILED;2309#endif2310}23112312bool os::pd_create_stack_guard_pages(char* addr, size_t size) {2313return os::commit_memory(addr, size, !ExecMem);2314}23152316// If this is a growable mapping, remove the guard pages entirely by2317// munmap()ping them. If not, just call uncommit_memory().2318bool os::remove_stack_guard_pages(char* addr, size_t size) {2319return os::uncommit_memory(addr, size);2320}23212322static address _highest_vm_reserved_address = NULL;23232324// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory2325// at 'requested_addr'. If there are existing memory mappings at the same2326// location, however, they will be overwritten. If 'fixed' is false,2327// 'requested_addr' is only treated as a hint, the return value may or2328// may not start from the requested address. Unlike Bsd mmap(), this2329// function returns NULL to indicate failure.2330static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {2331char * addr;2332int flags;23332334flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;2335if (fixed) {2336assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");2337flags |= MAP_FIXED;2338}23392340// Map reserved/uncommitted pages PROT_NONE so we fail early if we2341// touch an uncommitted page. Otherwise, the read/write might2342// succeed if we have enough swap space to back the physical page.2343addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,2344flags, -1, 0);23452346if (addr != MAP_FAILED) {2347// anon_mmap() should only get called during VM initialization,2348// don't need lock (actually we can skip locking even it can be called2349// from multiple threads, because _highest_vm_reserved_address is just a2350// hint about the upper limit of non-stack memory regions.)2351if ((address)addr + bytes > _highest_vm_reserved_address) {2352_highest_vm_reserved_address = (address)addr + bytes;2353}2354}23552356return addr == MAP_FAILED ? NULL : addr;2357}23582359// Don't update _highest_vm_reserved_address, because there might be memory2360// regions above addr + size. If so, releasing a memory region only creates2361// a hole in the address space, it doesn't help prevent heap-stack collision.2362//2363static int anon_munmap(char * addr, size_t size) {2364return ::munmap(addr, size) == 0;2365}23662367char* os::pd_reserve_memory(size_t bytes, char* requested_addr,2368size_t alignment_hint) {2369return anon_mmap(requested_addr, bytes, (requested_addr != NULL));2370}23712372bool os::pd_release_memory(char* addr, size_t size) {2373return anon_munmap(addr, size);2374}23752376static bool bsd_mprotect(char* addr, size_t size, int prot) {2377// Bsd wants the mprotect address argument to be page aligned.2378char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());23792380// According to SUSv3, mprotect() should only be used with mappings2381// established by mmap(), and mmap() always maps whole pages. Unaligned2382// 'addr' likely indicates problem in the VM (e.g. trying to change2383// protection of malloc'ed or statically allocated memory). Check the2384// caller if you hit this assert.2385assert(addr == bottom, "sanity check");23862387size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());2388return ::mprotect(bottom, size, prot) == 0;2389}23902391// Set protections specified2392bool os::protect_memory(char* addr, size_t bytes, ProtType prot,2393bool is_committed) {2394unsigned int p = 0;2395switch (prot) {2396case MEM_PROT_NONE: p = PROT_NONE; break;2397case MEM_PROT_READ: p = PROT_READ; break;2398case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;2399case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;2400default:2401ShouldNotReachHere();2402}2403// is_committed is unused.2404return bsd_mprotect(addr, bytes, p);2405}24062407bool os::guard_memory(char* addr, size_t size) {2408return bsd_mprotect(addr, size, PROT_NONE);2409}24102411bool os::unguard_memory(char* addr, size_t size) {2412return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);2413}24142415bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {2416return false;2417}24182419// Large page support24202421static size_t _large_page_size = 0;24222423void os::large_page_init() {2424}242524262427char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {2428fatal("This code is not used or maintained.");24292430// "exec" is passed in but not used. Creating the shared image for2431// the code cache doesn't have an SHM_X executable permission to check.2432assert(UseLargePages && UseSHM, "only for SHM large pages");24332434key_t key = IPC_PRIVATE;2435char *addr;24362437bool warn_on_failure = UseLargePages &&2438(!FLAG_IS_DEFAULT(UseLargePages) ||2439!FLAG_IS_DEFAULT(LargePageSizeInBytes)2440);24412442// Create a large shared memory region to attach to based on size.2443// Currently, size is the total size of the heap2444int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);2445if (shmid == -1) {2446// Possible reasons for shmget failure:2447// 1. shmmax is too small for Java heap.2448// > check shmmax value: cat /proc/sys/kernel/shmmax2449// > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax2450// 2. not enough large page memory.2451// > check available large pages: cat /proc/meminfo2452// > increase amount of large pages:2453// echo new_value > /proc/sys/vm/nr_hugepages2454// Note 1: different Bsd may use different name for this property,2455// e.g. on Redhat AS-3 it is "hugetlb_pool".2456// Note 2: it's possible there's enough physical memory available but2457// they are so fragmented after a long run that they can't2458// coalesce into large pages. Try to reserve large pages when2459// the system is still "fresh".2460if (warn_on_failure) {2461warning("Failed to reserve shared memory (errno = %d).", errno);2462}2463return NULL;2464}24652466// attach to the region2467addr = (char*)shmat(shmid, req_addr, 0);2468int err = errno;24692470// Remove shmid. If shmat() is successful, the actual shared memory segment2471// will be deleted when it's detached by shmdt() or when the process2472// terminates. If shmat() is not successful this will remove the shared2473// segment immediately.2474shmctl(shmid, IPC_RMID, NULL);24752476if ((intptr_t)addr == -1) {2477if (warn_on_failure) {2478warning("Failed to attach shared memory (errno = %d).", err);2479}2480return NULL;2481}24822483// The memory is committed2484MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);24852486return addr;2487}24882489bool os::release_memory_special(char* base, size_t bytes) {2490if (MemTracker::tracking_level() > NMT_minimal) {2491Tracker tkr = MemTracker::get_virtual_memory_release_tracker();2492// detaching the SHM segment will also delete it, see reserve_memory_special()2493int rslt = shmdt(base);2494if (rslt == 0) {2495tkr.record((address)base, bytes);2496return true;2497} else {2498return false;2499}2500} else {2501return shmdt(base) == 0;2502}2503}25042505size_t os::large_page_size() {2506return _large_page_size;2507}25082509// HugeTLBFS allows application to commit large page memory on demand;2510// with SysV SHM the entire memory region must be allocated as shared2511// memory.2512bool os::can_commit_large_page_memory() {2513return UseHugeTLBFS;2514}25152516bool os::can_execute_large_page_memory() {2517return UseHugeTLBFS;2518}25192520// Reserve memory at an arbitrary address, only if that area is2521// available (and not reserved for something else).25222523char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {2524const int max_tries = 10;2525char* base[max_tries];2526size_t size[max_tries];2527const size_t gap = 0x000000;25282529// Assert only that the size is a multiple of the page size, since2530// that's all that mmap requires, and since that's all we really know2531// about at this low abstraction level. If we need higher alignment,2532// we can either pass an alignment to this method or verify alignment2533// in one of the methods further up the call chain. See bug 5044738.2534assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");25352536// Repeatedly allocate blocks until the block is allocated at the2537// right spot. Give up after max_tries. Note that reserve_memory() will2538// automatically update _highest_vm_reserved_address if the call is2539// successful. The variable tracks the highest memory address every reserved2540// by JVM. It is used to detect heap-stack collision if running with2541// fixed-stack BsdThreads. Because here we may attempt to reserve more2542// space than needed, it could confuse the collision detecting code. To2543// solve the problem, save current _highest_vm_reserved_address and2544// calculate the correct value before return.2545address old_highest = _highest_vm_reserved_address;25462547// Bsd mmap allows caller to pass an address as hint; give it a try first,2548// if kernel honors the hint then we can return immediately.2549char * addr = anon_mmap(requested_addr, bytes, false);2550if (addr == requested_addr) {2551return requested_addr;2552}25532554if (addr != NULL) {2555// mmap() is successful but it fails to reserve at the requested address2556anon_munmap(addr, bytes);2557}25582559int i;2560for (i = 0; i < max_tries; ++i) {2561base[i] = reserve_memory(bytes);25622563if (base[i] != NULL) {2564// Is this the block we wanted?2565if (base[i] == requested_addr) {2566size[i] = bytes;2567break;2568}25692570// Does this overlap the block we wanted? Give back the overlapped2571// parts and try again.25722573size_t top_overlap = requested_addr + (bytes + gap) - base[i];2574if (top_overlap >= 0 && top_overlap < bytes) {2575unmap_memory(base[i], top_overlap);2576base[i] += top_overlap;2577size[i] = bytes - top_overlap;2578} else {2579size_t bottom_overlap = base[i] + bytes - requested_addr;2580if (bottom_overlap >= 0 && bottom_overlap < bytes) {2581unmap_memory(requested_addr, bottom_overlap);2582size[i] = bytes - bottom_overlap;2583} else {2584size[i] = bytes;2585}2586}2587}2588}25892590// Give back the unused reserved pieces.25912592for (int j = 0; j < i; ++j) {2593if (base[j] != NULL) {2594unmap_memory(base[j], size[j]);2595}2596}25972598if (i < max_tries) {2599_highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);2600return requested_addr;2601} else {2602_highest_vm_reserved_address = old_highest;2603return NULL;2604}2605}26062607size_t os::read(int fd, void *buf, unsigned int nBytes) {2608RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));2609}26102611size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {2612RESTARTABLE_RETURN_INT(::pread(fd, buf, nBytes, offset));2613}26142615// TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.2616// Solaris uses poll(), bsd uses park().2617// Poll() is likely a better choice, assuming that Thread.interrupt()2618// generates a SIGUSRx signal. Note that SIGUSR1 can interfere with2619// SIGSEGV, see 4355769.26202621int os::sleep(Thread* thread, jlong millis, bool interruptible) {2622assert(thread == Thread::current(), "thread consistency check");26232624ParkEvent * const slp = thread->_SleepEvent ;2625slp->reset() ;2626OrderAccess::fence() ;26272628if (interruptible) {2629jlong prevtime = javaTimeNanos();26302631for (;;) {2632if (os::is_interrupted(thread, true)) {2633return OS_INTRPT;2634}26352636jlong newtime = javaTimeNanos();26372638if (newtime - prevtime < 0) {2639// time moving backwards, should only happen if no monotonic clock2640// not a guarantee() because JVM should not abort on kernel/glibc bugs2641assert(!Bsd::supports_monotonic_clock(), "time moving backwards");2642} else {2643millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;2644}26452646if(millis <= 0) {2647return OS_OK;2648}26492650prevtime = newtime;26512652{2653assert(thread->is_Java_thread(), "sanity check");2654JavaThread *jt = (JavaThread *) thread;2655ThreadBlockInVM tbivm(jt);2656OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);26572658jt->set_suspend_equivalent();2659// cleared by handle_special_suspend_equivalent_condition() or2660// java_suspend_self() via check_and_wait_while_suspended()26612662slp->park(millis);26632664// were we externally suspended while we were waiting?2665jt->check_and_wait_while_suspended();2666}2667}2668} else {2669OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);2670jlong prevtime = javaTimeNanos();26712672for (;;) {2673// It'd be nice to avoid the back-to-back javaTimeNanos() calls on2674// the 1st iteration ...2675jlong newtime = javaTimeNanos();26762677if (newtime - prevtime < 0) {2678// time moving backwards, should only happen if no monotonic clock2679// not a guarantee() because JVM should not abort on kernel/glibc bugs2680assert(!Bsd::supports_monotonic_clock(), "time moving backwards");2681} else {2682millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;2683}26842685if(millis <= 0) break ;26862687prevtime = newtime;2688slp->park(millis);2689}2690return OS_OK ;2691}2692}26932694void os::naked_short_sleep(jlong ms) {2695struct timespec req;26962697assert(ms < 1000, "Un-interruptable sleep, short time use only");2698req.tv_sec = 0;2699if (ms > 0) {2700req.tv_nsec = (ms % 1000) * 1000000;2701}2702else {2703req.tv_nsec = 1;2704}27052706nanosleep(&req, NULL);27072708return;2709}27102711// Sleep forever; naked call to OS-specific sleep; use with CAUTION2712void os::infinite_sleep() {2713while (true) { // sleep forever ...2714::sleep(100); // ... 100 seconds at a time2715}2716}27172718// Used to convert frequent JVM_Yield() to nops2719bool os::dont_yield() {2720return DontYieldALot;2721}27222723void os::yield() {2724sched_yield();2725}27262727os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}27282729void os::yield_all(int attempts) {2730// Yields to all threads, including threads with lower priorities2731// Threads on Bsd are all with same priority. The Solaris style2732// os::yield_all() with nanosleep(1ms) is not necessary.2733sched_yield();2734}27352736// Called from the tight loops to possibly influence time-sharing heuristics2737void os::loop_breaker(int attempts) {2738os::yield_all(attempts);2739}27402741////////////////////////////////////////////////////////////////////////////////2742// thread priority support27432744// Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER2745// only supports dynamic priority, static priority must be zero. For real-time2746// applications, Bsd supports SCHED_RR which allows static priority (1-99).2747// However, for large multi-threaded applications, SCHED_RR is not only slower2748// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out2749// of 5 runs - Sep 2005).2750//2751// The following code actually changes the niceness of kernel-thread/LWP. It2752// has an assumption that setpriority() only modifies one kernel-thread/LWP,2753// not the entire user process, and user level threads are 1:1 mapped to kernel2754// threads. It has always been the case, but could change in the future. For2755// this reason, the code should not be used as default (ThreadPriorityPolicy=0).2756// It is only used when ThreadPriorityPolicy=1 and requires root privilege.27572758#if !defined(__APPLE__)2759int os::java_to_os_priority[CriticalPriority + 1] = {276019, // 0 Entry should never be used276127620, // 1 MinPriority27633, // 227646, // 32765276610, // 4276715, // 5 NormPriority276818, // 62769277021, // 7277125, // 8277228, // 9 NearMaxPriority2773277431, // 10 MaxPriority2775277631 // 11 CriticalPriority2777};2778#else2779/* Using Mach high-level priority assignments */2780int os::java_to_os_priority[CriticalPriority + 1] = {27810, // 0 Entry should never be used (MINPRI_USER)2782278327, // 1 MinPriority278428, // 2278529, // 32786278730, // 4278831, // 5 NormPriority (BASEPRI_DEFAULT)278932, // 62790279133, // 7279234, // 8279335, // 9 NearMaxPriority2794279536, // 10 MaxPriority2796279736 // 11 CriticalPriority2798};2799#endif28002801static int prio_init() {2802if (ThreadPriorityPolicy == 1) {2803// Only root can raise thread priority. Don't allow ThreadPriorityPolicy=12804// if effective uid is not root. Perhaps, a more elegant way of doing2805// this is to test CAP_SYS_NICE capability, but that will require libcap.so2806if (geteuid() != 0) {2807if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {2808warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");2809}2810ThreadPriorityPolicy = 0;2811}2812}2813if (UseCriticalJavaThreadPriority) {2814os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];2815}2816return 0;2817}28182819OSReturn os::set_native_priority(Thread* thread, int newpri) {2820if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;28212822#ifdef __OpenBSD__2823// OpenBSD pthread_setprio starves low priority threads2824return OS_OK;2825#elif defined(__FreeBSD__)2826int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);2827#elif defined(__APPLE__) || defined(__NetBSD__)2828struct sched_param sp;2829int policy;2830pthread_t self = pthread_self();28312832if (pthread_getschedparam(self, &policy, &sp) != 0)2833return OS_ERR;28342835sp.sched_priority = newpri;2836if (pthread_setschedparam(self, policy, &sp) != 0)2837return OS_ERR;28382839return OS_OK;2840#else2841int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);2842return (ret == 0) ? OS_OK : OS_ERR;2843#endif2844}28452846OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {2847if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {2848*priority_ptr = java_to_os_priority[NormPriority];2849return OS_OK;2850}28512852errno = 0;2853#if defined(__OpenBSD__) || defined(__FreeBSD__)2854*priority_ptr = pthread_getprio(thread->osthread()->pthread_id());2855#elif defined(__APPLE__) || defined(__NetBSD__)2856int policy;2857struct sched_param sp;28582859pthread_getschedparam(pthread_self(), &policy, &sp);2860*priority_ptr = sp.sched_priority;2861#else2862*priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());2863#endif2864return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);2865}28662867// Hint to the underlying OS that a task switch would not be good.2868// Void return because it's a hint and can fail.2869void os::hint_no_preempt() {}28702871////////////////////////////////////////////////////////////////////////////////2872// suspend/resume support28732874// the low-level signal-based suspend/resume support is a remnant from the2875// old VM-suspension that used to be for java-suspension, safepoints etc,2876// within hotspot. Now there is a single use-case for this:2877// - calling get_thread_pc() on the VMThread by the flat-profiler task2878// that runs in the watcher thread.2879// The remaining code is greatly simplified from the more general suspension2880// code that used to be used.2881//2882// The protocol is quite simple:2883// - suspend:2884// - sends a signal to the target thread2885// - polls the suspend state of the osthread using a yield loop2886// - target thread signal handler (SR_handler) sets suspend state2887// and blocks in sigsuspend until continued2888// - resume:2889// - sets target osthread state to continue2890// - sends signal to end the sigsuspend loop in the SR_handler2891//2892// Note that the SR_lock plays no role in this suspend/resume protocol.2893//28942895static void resume_clear_context(OSThread *osthread) {2896osthread->set_ucontext(NULL);2897osthread->set_siginfo(NULL);2898}28992900static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {2901osthread->set_ucontext(context);2902osthread->set_siginfo(siginfo);2903}29042905//2906// Handler function invoked when a thread's execution is suspended or2907// resumed. We have to be careful that only async-safe functions are2908// called here (Note: most pthread functions are not async safe and2909// should be avoided.)2910//2911// Note: sigwait() is a more natural fit than sigsuspend() from an2912// interface point of view, but sigwait() prevents the signal hander2913// from being run. libpthread would get very confused by not having2914// its signal handlers run and prevents sigwait()'s use with the2915// mutex granting granting signal.2916//2917// Currently only ever called on the VMThread or JavaThread2918//2919static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {2920// Save and restore errno to avoid confusing native code with EINTR2921// after sigsuspend.2922int old_errno = errno;29232924Thread* thread = Thread::current();2925OSThread* osthread = thread->osthread();2926assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");29272928os::SuspendResume::State current = osthread->sr.state();2929if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {2930suspend_save_context(osthread, siginfo, context);29312932// attempt to switch the state, we assume we had a SUSPEND_REQUEST2933os::SuspendResume::State state = osthread->sr.suspended();2934if (state == os::SuspendResume::SR_SUSPENDED) {2935sigset_t suspend_set; // signals for sigsuspend()29362937// get current set of blocked signals and unblock resume signal2938pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);2939sigdelset(&suspend_set, SR_signum);29402941sr_semaphore.signal();2942// wait here until we are resumed2943while (1) {2944sigsuspend(&suspend_set);29452946os::SuspendResume::State result = osthread->sr.running();2947if (result == os::SuspendResume::SR_RUNNING) {2948sr_semaphore.signal();2949break;2950} else if (result != os::SuspendResume::SR_SUSPENDED) {2951ShouldNotReachHere();2952}2953}29542955} else if (state == os::SuspendResume::SR_RUNNING) {2956// request was cancelled, continue2957} else {2958ShouldNotReachHere();2959}29602961resume_clear_context(osthread);2962} else if (current == os::SuspendResume::SR_RUNNING) {2963// request was cancelled, continue2964} else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {2965// ignore2966} else {2967// ignore2968}29692970errno = old_errno;2971}297229732974static int SR_initialize() {2975struct sigaction act;2976char *s;2977/* Get signal number to use for suspend/resume */2978if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {2979int sig = ::strtol(s, 0, 10);2980if (sig > 0 || sig < NSIG) {2981SR_signum = sig;2982}2983}29842985assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,2986"SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");29872988sigemptyset(&SR_sigset);2989sigaddset(&SR_sigset, SR_signum);29902991/* Set up signal handler for suspend/resume */2992act.sa_flags = SA_RESTART|SA_SIGINFO;2993act.sa_handler = (void (*)(int)) SR_handler;29942995// SR_signum is blocked by default.2996// 4528190 - We also need to block pthread restart signal (32 on all2997// supported Bsd platforms). Note that BsdThreads need to block2998// this signal for all threads to work properly. So we don't have2999// to use hard-coded signal number when setting up the mask.3000pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);30013002if (sigaction(SR_signum, &act, 0) == -1) {3003return -1;3004}30053006// Save signal flag3007os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);3008return 0;3009}30103011static int sr_notify(OSThread* osthread) {3012int status = pthread_kill(osthread->pthread_id(), SR_signum);3013assert_status(status == 0, status, "pthread_kill");3014return status;3015}30163017// "Randomly" selected value for how long we want to spin3018// before bailing out on suspending a thread, also how often3019// we send a signal to a thread we want to resume3020static const int RANDOMLY_LARGE_INTEGER = 1000000;3021static const int RANDOMLY_LARGE_INTEGER2 = 100;30223023// returns true on success and false on error - really an error is fatal3024// but this seems the normal response to library errors3025static bool do_suspend(OSThread* osthread) {3026assert(osthread->sr.is_running(), "thread should be running");3027assert(!sr_semaphore.trywait(), "semaphore has invalid state");30283029// mark as suspended and send signal3030if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {3031// failed to switch, state wasn't running?3032ShouldNotReachHere();3033return false;3034}30353036if (sr_notify(osthread) != 0) {3037ShouldNotReachHere();3038}30393040// managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED3041while (true) {3042if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {3043break;3044} else {3045// timeout3046os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();3047if (cancelled == os::SuspendResume::SR_RUNNING) {3048return false;3049} else if (cancelled == os::SuspendResume::SR_SUSPENDED) {3050// make sure that we consume the signal on the semaphore as well3051sr_semaphore.wait();3052break;3053} else {3054ShouldNotReachHere();3055return false;3056}3057}3058}30593060guarantee(osthread->sr.is_suspended(), "Must be suspended");3061return true;3062}30633064static void do_resume(OSThread* osthread) {3065assert(osthread->sr.is_suspended(), "thread should be suspended");3066assert(!sr_semaphore.trywait(), "invalid semaphore state");30673068if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {3069// failed to switch to WAKEUP_REQUEST3070ShouldNotReachHere();3071return;3072}30733074while (true) {3075if (sr_notify(osthread) == 0) {3076if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {3077if (osthread->sr.is_running()) {3078return;3079}3080}3081} else {3082ShouldNotReachHere();3083}3084}30853086guarantee(osthread->sr.is_running(), "Must be running!");3087}30883089////////////////////////////////////////////////////////////////////////////////3090// interrupt support30913092void os::interrupt(Thread* thread) {3093assert(Thread::current() == thread || Threads_lock->owned_by_self(),3094"possibility of dangling Thread pointer");30953096OSThread* osthread = thread->osthread();30973098if (!osthread->interrupted()) {3099osthread->set_interrupted(true);3100// More than one thread can get here with the same value of osthread,3101// resulting in multiple notifications. We do, however, want the store3102// to interrupted() to be visible to other threads before we execute unpark().3103OrderAccess::fence();3104ParkEvent * const slp = thread->_SleepEvent ;3105if (slp != NULL) slp->unpark() ;3106}31073108// For JSR166. Unpark even if interrupt status already was set3109if (thread->is_Java_thread())3110((JavaThread*)thread)->parker()->unpark();31113112ParkEvent * ev = thread->_ParkEvent ;3113if (ev != NULL) ev->unpark() ;31143115}31163117bool os::is_interrupted(Thread* thread, bool clear_interrupted) {3118assert(Thread::current() == thread || Threads_lock->owned_by_self(),3119"possibility of dangling Thread pointer");31203121OSThread* osthread = thread->osthread();31223123bool interrupted = osthread->interrupted();31243125if (interrupted && clear_interrupted) {3126osthread->set_interrupted(false);3127// consider thread->_SleepEvent->reset() ... optional optimization3128}31293130return interrupted;3131}31323133///////////////////////////////////////////////////////////////////////////////////3134// signal handling (except suspend/resume)31353136// This routine may be used by user applications as a "hook" to catch signals.3137// The user-defined signal handler must pass unrecognized signals to this3138// routine, and if it returns true (non-zero), then the signal handler must3139// return immediately. If the flag "abort_if_unrecognized" is true, then this3140// routine will never retun false (zero), but instead will execute a VM panic3141// routine kill the process.3142//3143// If this routine returns false, it is OK to call it again. This allows3144// the user-defined signal handler to perform checks either before or after3145// the VM performs its own checks. Naturally, the user code would be making3146// a serious error if it tried to handle an exception (such as a null check3147// or breakpoint) that the VM was generating for its own correct operation.3148//3149// This routine may recognize any of the following kinds of signals:3150// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.3151// It should be consulted by handlers for any of those signals.3152//3153// The caller of this routine must pass in the three arguments supplied3154// to the function referred to in the "sa_sigaction" (not the "sa_handler")3155// field of the structure passed to sigaction(). This routine assumes that3156// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.3157//3158// Note that the VM will print warnings if it detects conflicting signal3159// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".3160//3161extern "C" JNIEXPORT int3162JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,3163void* ucontext, int abort_if_unrecognized);31643165void signalHandler(int sig, siginfo_t* info, void* uc) {3166assert(info != NULL && uc != NULL, "it must be old kernel");3167int orig_errno = errno; // Preserve errno value over signal handler.3168JVM_handle_bsd_signal(sig, info, uc, true);3169errno = orig_errno;3170}317131723173// This boolean allows users to forward their own non-matching signals3174// to JVM_handle_bsd_signal, harmlessly.3175bool os::Bsd::signal_handlers_are_installed = false;31763177// For signal-chaining3178struct sigaction os::Bsd::sigact[MAXSIGNUM];3179unsigned int os::Bsd::sigs = 0;3180bool os::Bsd::libjsig_is_loaded = false;3181typedef struct sigaction *(*get_signal_t)(int);3182get_signal_t os::Bsd::get_signal_action = NULL;31833184struct sigaction* os::Bsd::get_chained_signal_action(int sig) {3185struct sigaction *actp = NULL;31863187if (libjsig_is_loaded) {3188// Retrieve the old signal handler from libjsig3189actp = (*get_signal_action)(sig);3190}3191if (actp == NULL) {3192// Retrieve the preinstalled signal handler from jvm3193actp = get_preinstalled_handler(sig);3194}31953196return actp;3197}31983199static bool call_chained_handler(struct sigaction *actp, int sig,3200siginfo_t *siginfo, void *context) {3201// Call the old signal handler3202if (actp->sa_handler == SIG_DFL) {3203// It's more reasonable to let jvm treat it as an unexpected exception3204// instead of taking the default action.3205return false;3206} else if (actp->sa_handler != SIG_IGN) {3207if ((actp->sa_flags & SA_NODEFER) == 0) {3208// automaticlly block the signal3209sigaddset(&(actp->sa_mask), sig);3210}32113212sa_handler_t hand;3213sa_sigaction_t sa;3214bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;3215// retrieve the chained handler3216if (siginfo_flag_set) {3217sa = actp->sa_sigaction;3218} else {3219hand = actp->sa_handler;3220}32213222if ((actp->sa_flags & SA_RESETHAND) != 0) {3223actp->sa_handler = SIG_DFL;3224}32253226// try to honor the signal mask3227sigset_t oset;3228pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);32293230// call into the chained handler3231if (siginfo_flag_set) {3232(*sa)(sig, siginfo, context);3233} else {3234(*hand)(sig);3235}32363237// restore the signal mask3238pthread_sigmask(SIG_SETMASK, &oset, 0);3239}3240// Tell jvm's signal handler the signal is taken care of.3241return true;3242}32433244bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {3245bool chained = false;3246// signal-chaining3247if (UseSignalChaining) {3248struct sigaction *actp = get_chained_signal_action(sig);3249if (actp != NULL) {3250chained = call_chained_handler(actp, sig, siginfo, context);3251}3252}3253return chained;3254}32553256struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {3257if ((( (unsigned int)1 << sig ) & sigs) != 0) {3258return &sigact[sig];3259}3260return NULL;3261}32623263void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {3264assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3265sigact[sig] = oldAct;3266sigs |= (unsigned int)1 << sig;3267}32683269// for diagnostic3270int os::Bsd::sigflags[MAXSIGNUM];32713272int os::Bsd::get_our_sigflags(int sig) {3273assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3274return sigflags[sig];3275}32763277void os::Bsd::set_our_sigflags(int sig, int flags) {3278assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3279sigflags[sig] = flags;3280}32813282void os::Bsd::set_signal_handler(int sig, bool set_installed) {3283// Check for overwrite.3284struct sigaction oldAct;3285sigaction(sig, (struct sigaction*)NULL, &oldAct);32863287void* oldhand = oldAct.sa_sigaction3288? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)3289: CAST_FROM_FN_PTR(void*, oldAct.sa_handler);3290if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&3291oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&3292oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {3293if (AllowUserSignalHandlers || !set_installed) {3294// Do not overwrite; user takes responsibility to forward to us.3295return;3296} else if (UseSignalChaining) {3297// save the old handler in jvm3298save_preinstalled_handler(sig, oldAct);3299// libjsig also interposes the sigaction() call below and saves the3300// old sigaction on it own.3301} else {3302fatal(err_msg("Encountered unexpected pre-existing sigaction handler "3303"%#lx for signal %d.", (long)oldhand, sig));3304}3305}33063307struct sigaction sigAct;3308sigfillset(&(sigAct.sa_mask));3309sigAct.sa_handler = SIG_DFL;3310if (!set_installed) {3311sigAct.sa_flags = SA_SIGINFO|SA_RESTART;3312} else {3313sigAct.sa_sigaction = signalHandler;3314sigAct.sa_flags = SA_SIGINFO|SA_RESTART;3315}3316#ifdef __APPLE__3317// Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV3318// (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"3319// if the signal handler declares it will handle it on alternate stack.3320// Notice we only declare we will handle it on alt stack, but we are not3321// actually going to use real alt stack - this is just a workaround.3322// Please see ux_exception.c, method catch_mach_exception_raise for details3323// link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c3324if (sig == SIGSEGV) {3325sigAct.sa_flags |= SA_ONSTACK;3326}3327#endif33283329// Save flags, which are set by ours3330assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3331sigflags[sig] = sigAct.sa_flags;33323333int ret = sigaction(sig, &sigAct, &oldAct);3334assert(ret == 0, "check");33353336void* oldhand2 = oldAct.sa_sigaction3337? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)3338: CAST_FROM_FN_PTR(void*, oldAct.sa_handler);3339assert(oldhand2 == oldhand, "no concurrent signal handler installation");3340}33413342// install signal handlers for signals that HotSpot needs to3343// handle in order to support Java-level exception handling.33443345void os::Bsd::install_signal_handlers() {3346if (!signal_handlers_are_installed) {3347signal_handlers_are_installed = true;33483349// signal-chaining3350typedef void (*signal_setting_t)();3351signal_setting_t begin_signal_setting = NULL;3352signal_setting_t end_signal_setting = NULL;3353begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,3354dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));3355if (begin_signal_setting != NULL) {3356end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,3357dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));3358get_signal_action = CAST_TO_FN_PTR(get_signal_t,3359dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));3360libjsig_is_loaded = true;3361assert(UseSignalChaining, "should enable signal-chaining");3362}3363if (libjsig_is_loaded) {3364// Tell libjsig jvm is setting signal handlers3365(*begin_signal_setting)();3366}33673368set_signal_handler(SIGSEGV, true);3369set_signal_handler(SIGPIPE, true);3370set_signal_handler(SIGBUS, true);3371set_signal_handler(SIGILL, true);3372set_signal_handler(SIGFPE, true);3373set_signal_handler(SIGXFSZ, true);33743375#if defined(__APPLE__)3376// In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including3377// signals caught and handled by the JVM. To work around this, we reset the mach task3378// signal handler that's placed on our process by CrashReporter. This disables3379// CrashReporter-based reporting.3380//3381// This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes3382// on caught fatal signals.3383//3384// Additionally, gdb installs both standard BSD signal handlers, and mach exception3385// handlers. By replacing the existing task exception handler, we disable gdb's mach3386// exception handling, while leaving the standard BSD signal handlers functional.3387kern_return_t kr;3388kr = task_set_exception_ports(mach_task_self(),3389EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,3390MACH_PORT_NULL,3391EXCEPTION_STATE_IDENTITY,3392MACHINE_THREAD_STATE);33933394assert(kr == KERN_SUCCESS, "could not set mach task signal handler");3395#endif33963397if (libjsig_is_loaded) {3398// Tell libjsig jvm finishes setting signal handlers3399(*end_signal_setting)();3400}34013402// We don't activate signal checker if libjsig is in place, we trust ourselves3403// and if UserSignalHandler is installed all bets are off3404if (CheckJNICalls) {3405if (libjsig_is_loaded) {3406if (PrintJNIResolving) {3407tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");3408}3409check_signals = false;3410}3411if (AllowUserSignalHandlers) {3412if (PrintJNIResolving) {3413tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");3414}3415check_signals = false;3416}3417}3418}3419}342034213422/////3423// glibc on Bsd platform uses non-documented flag3424// to indicate, that some special sort of signal3425// trampoline is used.3426// We will never set this flag, and we should3427// ignore this flag in our diagnostic3428#ifdef SIGNIFICANT_SIGNAL_MASK3429#undef SIGNIFICANT_SIGNAL_MASK3430#endif3431#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)34323433static const char* get_signal_handler_name(address handler,3434char* buf, int buflen) {3435int offset;3436bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);3437if (found) {3438// skip directory names3439const char *p1, *p2;3440p1 = buf;3441size_t len = strlen(os::file_separator());3442while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;3443jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);3444} else {3445jio_snprintf(buf, buflen, PTR_FORMAT, handler);3446}3447return buf;3448}34493450static void print_signal_handler(outputStream* st, int sig,3451char* buf, size_t buflen) {3452struct sigaction sa;34533454sigaction(sig, NULL, &sa);34553456// See comment for SIGNIFICANT_SIGNAL_MASK define3457sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;34583459st->print("%s: ", os::exception_name(sig, buf, buflen));34603461address handler = (sa.sa_flags & SA_SIGINFO)3462? CAST_FROM_FN_PTR(address, sa.sa_sigaction)3463: CAST_FROM_FN_PTR(address, sa.sa_handler);34643465if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {3466st->print("SIG_DFL");3467} else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {3468st->print("SIG_IGN");3469} else {3470st->print("[%s]", get_signal_handler_name(handler, buf, buflen));3471}34723473st->print(", sa_mask[0]=");3474os::Posix::print_signal_set_short(st, &sa.sa_mask);34753476address rh = VMError::get_resetted_sighandler(sig);3477// May be, handler was resetted by VMError?3478if(rh != NULL) {3479handler = rh;3480sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;3481}34823483st->print(", sa_flags=");3484os::Posix::print_sa_flags(st, sa.sa_flags);34853486// Check: is it our handler?3487if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||3488handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {3489// It is our signal handler3490// check for flags, reset system-used one!3491if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {3492st->print(3493", flags was changed from " PTR32_FORMAT ", consider using jsig library",3494os::Bsd::get_our_sigflags(sig));3495}3496}3497st->cr();3498}349935003501#define DO_SIGNAL_CHECK(sig) \3502if (!sigismember(&check_signal_done, sig)) \3503os::Bsd::check_signal_handler(sig)35043505// This method is a periodic task to check for misbehaving JNI applications3506// under CheckJNI, we can add any periodic checks here35073508void os::run_periodic_checks() {35093510if (check_signals == false) return;35113512// SEGV and BUS if overridden could potentially prevent3513// generation of hs*.log in the event of a crash, debugging3514// such a case can be very challenging, so we absolutely3515// check the following for a good measure:3516DO_SIGNAL_CHECK(SIGSEGV);3517DO_SIGNAL_CHECK(SIGILL);3518DO_SIGNAL_CHECK(SIGFPE);3519DO_SIGNAL_CHECK(SIGBUS);3520DO_SIGNAL_CHECK(SIGPIPE);3521DO_SIGNAL_CHECK(SIGXFSZ);352235233524// ReduceSignalUsage allows the user to override these handlers3525// see comments at the very top and jvm_solaris.h3526if (!ReduceSignalUsage) {3527DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);3528DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);3529DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);3530DO_SIGNAL_CHECK(BREAK_SIGNAL);3531}35323533DO_SIGNAL_CHECK(SR_signum);3534DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);3535}35363537typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);35383539static os_sigaction_t os_sigaction = NULL;35403541void os::Bsd::check_signal_handler(int sig) {3542char buf[O_BUFLEN];3543address jvmHandler = NULL;354435453546struct sigaction act;3547if (os_sigaction == NULL) {3548// only trust the default sigaction, in case it has been interposed3549os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");3550if (os_sigaction == NULL) return;3551}35523553os_sigaction(sig, (struct sigaction*)NULL, &act);355435553556act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;35573558address thisHandler = (act.sa_flags & SA_SIGINFO)3559? CAST_FROM_FN_PTR(address, act.sa_sigaction)3560: CAST_FROM_FN_PTR(address, act.sa_handler) ;356135623563switch(sig) {3564case SIGSEGV:3565case SIGBUS:3566case SIGFPE:3567case SIGPIPE:3568case SIGILL:3569case SIGXFSZ:3570jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);3571break;35723573case SHUTDOWN1_SIGNAL:3574case SHUTDOWN2_SIGNAL:3575case SHUTDOWN3_SIGNAL:3576case BREAK_SIGNAL:3577jvmHandler = (address)user_handler();3578break;35793580case INTERRUPT_SIGNAL:3581jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);3582break;35833584default:3585if (sig == SR_signum) {3586jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);3587} else {3588return;3589}3590break;3591}35923593if (thisHandler != jvmHandler) {3594tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));3595tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));3596tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));3597// No need to check this sig any longer3598sigaddset(&check_signal_done, sig);3599// Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN3600if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {3601tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",3602exception_name(sig, buf, O_BUFLEN));3603}3604} else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {3605tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));3606tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));3607tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);3608// No need to check this sig any longer3609sigaddset(&check_signal_done, sig);3610}36113612// Dump all the signal3613if (sigismember(&check_signal_done, sig)) {3614print_signal_handlers(tty, buf, O_BUFLEN);3615}3616}36173618extern void report_error(char* file_name, int line_no, char* title, char* format, ...);36193620extern bool signal_name(int signo, char* buf, size_t len);36213622const char* os::exception_name(int exception_code, char* buf, size_t size) {3623if (0 < exception_code && exception_code <= SIGRTMAX) {3624// signal3625if (!signal_name(exception_code, buf, size)) {3626jio_snprintf(buf, size, "SIG%d", exception_code);3627}3628return buf;3629} else {3630return NULL;3631}3632}36333634// this is called _before_ the most of global arguments have been parsed3635void os::init(void) {3636char dummy; /* used to get a guess on initial stack address */3637// first_hrtime = gethrtime();36383639// With BsdThreads the JavaMain thread pid (primordial thread)3640// is different than the pid of the java launcher thread.3641// So, on Bsd, the launcher thread pid is passed to the VM3642// via the sun.java.launcher.pid property.3643// Use this property instead of getpid() if it was correctly passed.3644// See bug 6351349.3645pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();36463647_initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();36483649clock_tics_per_sec = CLK_TCK;36503651init_random(1234567);36523653ThreadCritical::initialize();36543655Bsd::set_page_size(getpagesize());3656if (Bsd::page_size() == -1) {3657fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",3658strerror(errno)));3659}3660init_page_sizes((size_t) Bsd::page_size());36613662Bsd::initialize_system_info();36633664// _main_thread points to the thread that created/loaded the JVM.3665Bsd::_main_thread = pthread_self();36663667Bsd::clock_init();3668initial_time_count = javaTimeNanos();36693670#ifdef __APPLE__3671// XXXDARWIN3672// Work around the unaligned VM callbacks in hotspot's3673// sharedRuntime. The callbacks don't use SSE2 instructions, and work on3674// Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces3675// alignment when doing symbol lookup. To work around this, we force early3676// binding of all symbols now, thus binding when alignment is known-good.3677_dyld_bind_fully_image_containing_address((const void *) &os::init);3678#endif3679}36803681// To install functions for atexit system call3682extern "C" {3683static void perfMemory_exit_helper() {3684perfMemory_exit();3685}3686}36873688// this is called _after_ the global arguments have been parsed3689jint os::init_2(void)3690{3691// Allocate a single page and mark it as readable for safepoint polling3692address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);3693guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );36943695os::set_polling_page( polling_page );36963697#ifndef PRODUCT3698if(Verbose && PrintMiscellaneous)3699tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);3700#endif37013702if (!UseMembar) {3703address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);3704guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");3705os::set_memory_serialize_page( mem_serialize_page );37063707#ifndef PRODUCT3708if(Verbose && PrintMiscellaneous)3709tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);3710#endif3711}37123713// initialize suspend/resume support - must do this before signal_sets_init()3714if (SR_initialize() != 0) {3715perror("SR_initialize failed");3716return JNI_ERR;3717}37183719Bsd::signal_sets_init();3720Bsd::install_signal_handlers();37213722// Check minimum allowable stack size for thread creation and to initialize3723// the java system classes, including StackOverflowError - depends on page3724// size. Add a page for compiler2 recursion in main thread.3725// Add in 2*BytesPerWord times page size to account for VM stack during3726// class initialization depending on 32 or 64 bit VM.3727os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,3728(size_t)(StackYellowPages+StackRedPages+StackShadowPages+37292*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());37303731size_t threadStackSizeInBytes = ThreadStackSize * K;3732if (threadStackSizeInBytes != 0 &&3733threadStackSizeInBytes < os::Bsd::min_stack_allowed) {3734tty->print_cr("\nThe stack size specified is too small, "3735"Specify at least %dk",3736os::Bsd::min_stack_allowed/ K);3737return JNI_ERR;3738}37393740// Make the stack size a multiple of the page size so that3741// the yellow/red zones can be guarded.3742JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,3743vm_page_size()));37443745if (MaxFDLimit) {3746// set the number of file descriptors to max. print out error3747// if getrlimit/setrlimit fails but continue regardless.3748struct rlimit nbr_files;3749int status = getrlimit(RLIMIT_NOFILE, &nbr_files);3750if (status != 0) {3751if (PrintMiscellaneous && (Verbose || WizardMode))3752perror("os::init_2 getrlimit failed");3753} else {3754nbr_files.rlim_cur = nbr_files.rlim_max;37553756#ifdef __APPLE__3757// Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if3758// you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must3759// be used instead3760nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);3761#endif37623763status = setrlimit(RLIMIT_NOFILE, &nbr_files);3764if (status != 0) {3765if (PrintMiscellaneous && (Verbose || WizardMode))3766perror("os::init_2 setrlimit failed");3767}3768}3769}37703771// at-exit methods are called in the reverse order of their registration.3772// atexit functions are called on return from main or as a result of a3773// call to exit(3C). There can be only 32 of these functions registered3774// and atexit() does not set errno.37753776if (PerfAllowAtExitRegistration) {3777// only register atexit functions if PerfAllowAtExitRegistration is set.3778// atexit functions can be delayed until process exit time, which3779// can be problematic for embedded VM situations. Embedded VMs should3780// call DestroyJavaVM() to assure that VM resources are released.37813782// note: perfMemory_exit_helper atexit function may be removed in3783// the future if the appropriate cleanup code can be added to the3784// VM_Exit VMOperation's doit method.3785if (atexit(perfMemory_exit_helper) != 0) {3786warning("os::init2 atexit(perfMemory_exit_helper) failed");3787}3788}37893790// initialize thread priority policy3791prio_init();37923793#ifdef __APPLE__3794// dynamically link to objective c gc registration3795void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);3796if (handleLibObjc != NULL) {3797objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);3798}3799#endif38003801return JNI_OK;3802}38033804// Mark the polling page as unreadable3805void os::make_polling_page_unreadable(void) {3806if( !guard_memory((char*)_polling_page, Bsd::page_size()) )3807fatal("Could not disable polling page");3808};38093810// Mark the polling page as readable3811void os::make_polling_page_readable(void) {3812if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {3813fatal("Could not enable polling page");3814}3815};38163817int os::active_processor_count() {3818// User has overridden the number of active processors3819if (ActiveProcessorCount > 0) {3820if (PrintActiveCpus) {3821tty->print_cr("active_processor_count: "3822"active processor count set by user : %d",3823ActiveProcessorCount);3824}3825return ActiveProcessorCount;3826}38273828return _processor_count;3829}38303831void os::set_native_thread_name(const char *name) {3832#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_53833// This is only supported in Snow Leopard and beyond3834if (name != NULL) {3835// Add a "Java: " prefix to the name3836char buf[MAXTHREADNAMESIZE];3837snprintf(buf, sizeof(buf), "Java: %s", name);3838pthread_setname_np(buf);3839}3840#endif3841}38423843bool os::distribute_processes(uint length, uint* distribution) {3844// Not yet implemented.3845return false;3846}38473848bool os::bind_to_processor(uint processor_id) {3849// Not yet implemented.3850return false;3851}38523853void os::SuspendedThreadTask::internal_do_task() {3854if (do_suspend(_thread->osthread())) {3855SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());3856do_task(context);3857do_resume(_thread->osthread());3858}3859}38603861///3862class PcFetcher : public os::SuspendedThreadTask {3863public:3864PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}3865ExtendedPC result();3866protected:3867void do_task(const os::SuspendedThreadTaskContext& context);3868private:3869ExtendedPC _epc;3870};38713872ExtendedPC PcFetcher::result() {3873guarantee(is_done(), "task is not done yet.");3874return _epc;3875}38763877void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {3878Thread* thread = context.thread();3879OSThread* osthread = thread->osthread();3880if (osthread->ucontext() != NULL) {3881_epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());3882} else {3883// NULL context is unexpected, double-check this is the VMThread3884guarantee(thread->is_VM_thread(), "can only be called for VMThread");3885}3886}38873888// Suspends the target using the signal mechanism and then grabs the PC before3889// resuming the target. Used by the flat-profiler only3890ExtendedPC os::get_thread_pc(Thread* thread) {3891// Make sure that it is called by the watcher for the VMThread3892assert(Thread::current()->is_Watcher_thread(), "Must be watcher");3893assert(thread->is_VM_thread(), "Can only be called for VMThread");38943895PcFetcher fetcher(thread);3896fetcher.run();3897return fetcher.result();3898}38993900int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)3901{3902return pthread_cond_timedwait(_cond, _mutex, _abstime);3903}39043905////////////////////////////////////////////////////////////////////////////////3906// debug support39073908bool os::find(address addr, outputStream* st) {3909Dl_info dlinfo;3910memset(&dlinfo, 0, sizeof(dlinfo));3911if (dladdr(addr, &dlinfo) != 0) {3912st->print(PTR_FORMAT ": ", addr);3913if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {3914st->print("%s+%#x", dlinfo.dli_sname,3915addr - (intptr_t)dlinfo.dli_saddr);3916} else if (dlinfo.dli_fbase != NULL) {3917st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);3918} else {3919st->print("<absolute address>");3920}3921if (dlinfo.dli_fname != NULL) {3922st->print(" in %s", dlinfo.dli_fname);3923}3924if (dlinfo.dli_fbase != NULL) {3925st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);3926}3927st->cr();39283929if (Verbose) {3930// decode some bytes around the PC3931address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());3932address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());3933address lowest = (address) dlinfo.dli_sname;3934if (!lowest) lowest = (address) dlinfo.dli_fbase;3935if (begin < lowest) begin = lowest;3936Dl_info dlinfo2;3937if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr3938&& end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)3939end = (address) dlinfo2.dli_saddr;3940Disassembler::decode(begin, end, st);3941}3942return true;3943}3944return false;3945}39463947////////////////////////////////////////////////////////////////////////////////3948// misc39493950// This does not do anything on Bsd. This is basically a hook for being3951// able to use structured exception handling (thread-local exception filters)3952// on, e.g., Win32.3953void3954os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,3955JavaCallArguments* args, Thread* thread) {3956f(value, method, args, thread);3957}39583959void os::print_statistics() {3960}39613962int os::message_box(const char* title, const char* message) {3963int i;3964fdStream err(defaultStream::error_fd());3965for (i = 0; i < 78; i++) err.print_raw("=");3966err.cr();3967err.print_raw_cr(title);3968for (i = 0; i < 78; i++) err.print_raw("-");3969err.cr();3970err.print_raw_cr(message);3971for (i = 0; i < 78; i++) err.print_raw("=");3972err.cr();39733974char buf[16];3975// Prevent process from exiting upon "read error" without consuming all CPU3976while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }39773978return buf[0] == 'y' || buf[0] == 'Y';3979}39803981int os::stat(const char *path, struct stat *sbuf) {3982char pathbuf[MAX_PATH];3983if (strlen(path) > MAX_PATH - 1) {3984errno = ENAMETOOLONG;3985return -1;3986}3987os::native_path(strcpy(pathbuf, path));3988return ::stat(pathbuf, sbuf);3989}39903991bool os::check_heap(bool force) {3992return true;3993}39943995ATTRIBUTE_PRINTF(3, 0)3996int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {3997return ::vsnprintf(buf, count, format, args);3998}39994000// Is a (classpath) directory empty?4001bool os::dir_is_empty(const char* path) {4002DIR *dir = NULL;4003struct dirent *ptr;40044005dir = opendir(path);4006if (dir == NULL) return true;40074008/* Scan the directory */4009bool result = true;4010while (result && (ptr = readdir(dir)) != NULL) {4011if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {4012result = false;4013}4014}4015closedir(dir);4016return result;4017}40184019// This code originates from JDK's sysOpen and open64_w4020// from src/solaris/hpi/src/system_md.c40214022#ifndef O_DELETE4023#define O_DELETE 0x100004024#endif40254026// Open a file. Unlink the file immediately after open returns4027// if the specified oflag has the O_DELETE flag set.4028// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c40294030int os::open(const char *path, int oflag, int mode) {40314032if (strlen(path) > MAX_PATH - 1) {4033errno = ENAMETOOLONG;4034return -1;4035}4036int fd;4037int o_delete = (oflag & O_DELETE);4038oflag = oflag & ~O_DELETE;40394040fd = ::open(path, oflag, mode);4041if (fd == -1) return -1;40424043//If the open succeeded, the file might still be a directory4044{4045struct stat buf;4046int ret = ::fstat(fd, &buf);4047int st_mode = buf.st_mode;40484049if (ret != -1) {4050if ((st_mode & S_IFMT) == S_IFDIR) {4051errno = EISDIR;4052::close(fd);4053return -1;4054}4055} else {4056::close(fd);4057return -1;4058}4059}40604061/*4062* All file descriptors that are opened in the JVM and not4063* specifically destined for a subprocess should have the4064* close-on-exec flag set. If we don't set it, then careless 3rd4065* party native code might fork and exec without closing all4066* appropriate file descriptors (e.g. as we do in closeDescriptors in4067* UNIXProcess.c), and this in turn might:4068*4069* - cause end-of-file to fail to be detected on some file4070* descriptors, resulting in mysterious hangs, or4071*4072* - might cause an fopen in the subprocess to fail on a system4073* suffering from bug 1085341.4074*4075* (Yes, the default setting of the close-on-exec flag is a Unix4076* design flaw)4077*4078* See:4079* 1085341: 32-bit stdio routines should support file descriptors >2554080* 4843136: (process) pipe file descriptor from Runtime.exec not being closed4081* 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 94082*/4083#ifdef FD_CLOEXEC4084{4085int flags = ::fcntl(fd, F_GETFD);4086if (flags != -1)4087::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);4088}4089#endif40904091if (o_delete != 0) {4092::unlink(path);4093}4094return fd;4095}409640974098// create binary file, rewriting existing file if required4099int os::create_binary_file(const char* path, bool rewrite_existing) {4100int oflags = O_WRONLY | O_CREAT;4101if (!rewrite_existing) {4102oflags |= O_EXCL;4103}4104return ::open(path, oflags, S_IREAD | S_IWRITE);4105}41064107// return current position of file pointer4108jlong os::current_file_offset(int fd) {4109return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);4110}41114112// move file pointer to the specified offset4113jlong os::seek_to_file_offset(int fd, jlong offset) {4114return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);4115}41164117// This code originates from JDK's sysAvailable4118// from src/solaris/hpi/src/native_threads/src/sys_api_td.c41194120int os::available(int fd, jlong *bytes) {4121jlong cur, end;4122int mode;4123struct stat buf;41244125if (::fstat(fd, &buf) >= 0) {4126mode = buf.st_mode;4127if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {4128/*4129* XXX: is the following call interruptible? If so, this might4130* need to go through the INTERRUPT_IO() wrapper as for other4131* blocking, interruptible calls in this file.4132*/4133int n;4134if (::ioctl(fd, FIONREAD, &n) >= 0) {4135*bytes = n;4136return 1;4137}4138}4139}4140if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {4141return 0;4142} else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {4143return 0;4144} else if (::lseek(fd, cur, SEEK_SET) == -1) {4145return 0;4146}4147*bytes = end - cur;4148return 1;4149}41504151int os::socket_available(int fd, jint *pbytes) {4152if (fd < 0)4153return OS_OK;41544155int ret;41564157RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);41584159//%% note ioctl can return 0 when successful, JVM_SocketAvailable4160// is expected to return 0 on failure and 1 on success to the jdk.41614162return (ret == OS_ERR) ? 0 : 1;4163}41644165// Map a block of memory.4166char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,4167char *addr, size_t bytes, bool read_only,4168bool allow_exec) {4169int prot;4170int flags;41714172if (read_only) {4173prot = PROT_READ;4174flags = MAP_SHARED;4175} else {4176prot = PROT_READ | PROT_WRITE;4177flags = MAP_PRIVATE;4178}41794180if (allow_exec) {4181prot |= PROT_EXEC;4182}41834184if (addr != NULL) {4185flags |= MAP_FIXED;4186}41874188char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,4189fd, file_offset);4190if (mapped_address == MAP_FAILED) {4191return NULL;4192}4193return mapped_address;4194}419541964197// Remap a block of memory.4198char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,4199char *addr, size_t bytes, bool read_only,4200bool allow_exec) {4201// same as map_memory() on this OS4202return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,4203allow_exec);4204}420542064207// Unmap a block of memory.4208bool os::pd_unmap_memory(char* addr, size_t bytes) {4209return munmap(addr, bytes) == 0;4210}42114212// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)4213// are used by JVM M&M and JVMTI to get user+sys or user CPU time4214// of a thread.4215//4216// current_thread_cpu_time() and thread_cpu_time(Thread*) returns4217// the fast estimate available on the platform.42184219jlong os::current_thread_cpu_time() {4220#ifdef __APPLE__4221return os::thread_cpu_time(Thread::current(), true /* user + sys */);4222#else4223Unimplemented();4224return 0;4225#endif4226}42274228jlong os::thread_cpu_time(Thread* thread) {4229#ifdef __APPLE__4230return os::thread_cpu_time(thread, true /* user + sys */);4231#else4232Unimplemented();4233return 0;4234#endif4235}42364237jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {4238#ifdef __APPLE__4239return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);4240#else4241Unimplemented();4242return 0;4243#endif4244}42454246jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {4247#ifdef __APPLE__4248struct thread_basic_info tinfo;4249mach_msg_type_number_t tcount = THREAD_INFO_MAX;4250kern_return_t kr;4251thread_t mach_thread;42524253mach_thread = thread->osthread()->thread_id();4254kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);4255if (kr != KERN_SUCCESS)4256return -1;42574258if (user_sys_cpu_time) {4259jlong nanos;4260nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;4261nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;4262return nanos;4263} else {4264return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);4265}4266#else4267Unimplemented();4268return 0;4269#endif4270}427142724273void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {4274info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits4275info_ptr->may_skip_backward = false; // elapsed time not wall time4276info_ptr->may_skip_forward = false; // elapsed time not wall time4277info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned4278}42794280void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {4281info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits4282info_ptr->may_skip_backward = false; // elapsed time not wall time4283info_ptr->may_skip_forward = false; // elapsed time not wall time4284info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned4285}42864287bool os::is_thread_cpu_time_supported() {4288#ifdef __APPLE__4289return true;4290#else4291return false;4292#endif4293}42944295// System loadavg support. Returns -1 if load average cannot be obtained.4296// Bsd doesn't yet have a (official) notion of processor sets,4297// so just return the system wide load average.4298int os::loadavg(double loadavg[], int nelem) {4299return ::getloadavg(loadavg, nelem);4300}43014302void os::pause() {4303char filename[MAX_PATH];4304if (PauseAtStartupFile && PauseAtStartupFile[0]) {4305jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);4306} else {4307jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());4308}43094310int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);4311if (fd != -1) {4312struct stat buf;4313::close(fd);4314while (::stat(filename, &buf) == 0) {4315(void)::poll(NULL, 0, 100);4316}4317} else {4318jio_fprintf(stderr,4319"Could not open pause file '%s', continuing immediately.\n", filename);4320}4321}432243234324// Refer to the comments in os_solaris.cpp park-unpark.4325//4326// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can4327// hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.4328// For specifics regarding the bug see GLIBC BUGID 261237 :4329// http://www.mail-archive.com/[email protected]/msg10837.html.4330// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future4331// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar4332// is used. (The simple C test-case provided in the GLIBC bug report manifests the4333// hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()4334// and monitorenter when we're using 1-0 locking. All those operations may result in4335// calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version4336// of libpthread avoids the problem, but isn't practical.4337//4338// Possible remedies:4339//4340// 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.4341// This is palliative and probabilistic, however. If the thread is preempted4342// between the call to compute_abstime() and pthread_cond_timedwait(), more4343// than the minimum period may have passed, and the abstime may be stale (in the4344// past) resultin in a hang. Using this technique reduces the odds of a hang4345// but the JVM is still vulnerable, particularly on heavily loaded systems.4346//4347// 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead4348// of the usual flag-condvar-mutex idiom. The write side of the pipe is set4349// NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)4350// reduces to poll()+read(). This works well, but consumes 2 FDs per extant4351// thread.4352//4353// 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread4354// that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing4355// a timeout request to the chron thread and then blocking via pthread_cond_wait().4356// This also works well. In fact it avoids kernel-level scalability impediments4357// on certain platforms that don't handle lots of active pthread_cond_timedwait()4358// timers in a graceful fashion.4359//4360// 4. When the abstime value is in the past it appears that control returns4361// correctly from pthread_cond_timedwait(), but the condvar is left corrupt.4362// Subsequent timedwait/wait calls may hang indefinitely. Given that, we4363// can avoid the problem by reinitializing the condvar -- by cond_destroy()4364// followed by cond_init() -- after all calls to pthread_cond_timedwait().4365// It may be possible to avoid reinitialization by checking the return4366// value from pthread_cond_timedwait(). In addition to reinitializing the4367// condvar we must establish the invariant that cond_signal() is only called4368// within critical sections protected by the adjunct mutex. This prevents4369// cond_signal() from "seeing" a condvar that's in the midst of being4370// reinitialized or that is corrupt. Sadly, this invariant obviates the4371// desirable signal-after-unlock optimization that avoids futile context switching.4372//4373// I'm also concerned that some versions of NTPL might allocate an auxilliary4374// structure when a condvar is used or initialized. cond_destroy() would4375// release the helper structure. Our reinitialize-after-timedwait fix4376// put excessive stress on malloc/free and locks protecting the c-heap.4377//4378// We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.4379// It may be possible to refine (4) by checking the kernel and NTPL verisons4380// and only enabling the work-around for vulnerable environments.43814382// utility to compute the abstime argument to timedwait:4383// millis is the relative timeout time4384// abstime will be the absolute timeout time4385// TODO: replace compute_abstime() with unpackTime()43864387static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {4388if (millis < 0) millis = 0;4389struct timeval now;4390int status = gettimeofday(&now, NULL);4391assert(status == 0, "gettimeofday");4392jlong seconds = millis / 1000;4393millis %= 1000;4394if (seconds > 50000000) { // see man cond_timedwait(3T)4395seconds = 50000000;4396}4397abstime->tv_sec = now.tv_sec + seconds;4398long usec = now.tv_usec + millis * 1000;4399if (usec >= 1000000) {4400abstime->tv_sec += 1;4401usec -= 1000000;4402}4403abstime->tv_nsec = usec * 1000;4404return abstime;4405}440644074408// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.4409// Conceptually TryPark() should be equivalent to park(0).44104411int os::PlatformEvent::TryPark() {4412for (;;) {4413const int v = _Event ;4414guarantee ((v == 0) || (v == 1), "invariant") ;4415if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;4416}4417}44184419void os::PlatformEvent::park() { // AKA "down()"4420// Invariant: Only the thread associated with the Event/PlatformEvent4421// may call park().4422// TODO: assert that _Assoc != NULL or _Assoc == Self4423int v ;4424for (;;) {4425v = _Event ;4426if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;4427}4428guarantee (v >= 0, "invariant") ;4429if (v == 0) {4430// Do this the hard way by blocking ...4431int status = pthread_mutex_lock(_mutex);4432assert_status(status == 0, status, "mutex_lock");4433guarantee (_nParked == 0, "invariant") ;4434++ _nParked ;4435while (_Event < 0) {4436status = pthread_cond_wait(_cond, _mutex);4437// for some reason, under 2.7 lwp_cond_wait() may return ETIME ...4438// Treat this the same as if the wait was interrupted4439if (status == ETIMEDOUT) { status = EINTR; }4440assert_status(status == 0 || status == EINTR, status, "cond_wait");4441}4442-- _nParked ;44434444_Event = 0 ;4445status = pthread_mutex_unlock(_mutex);4446assert_status(status == 0, status, "mutex_unlock");4447// Paranoia to ensure our locked and lock-free paths interact4448// correctly with each other.4449OrderAccess::fence();4450}4451guarantee (_Event >= 0, "invariant") ;4452}44534454int os::PlatformEvent::park(jlong millis) {4455guarantee (_nParked == 0, "invariant") ;44564457int v ;4458for (;;) {4459v = _Event ;4460if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;4461}4462guarantee (v >= 0, "invariant") ;4463if (v != 0) return OS_OK ;44644465// We do this the hard way, by blocking the thread.4466// Consider enforcing a minimum timeout value.4467struct timespec abst;4468compute_abstime(&abst, millis);44694470int ret = OS_TIMEOUT;4471int status = pthread_mutex_lock(_mutex);4472assert_status(status == 0, status, "mutex_lock");4473guarantee (_nParked == 0, "invariant") ;4474++_nParked ;44754476// Object.wait(timo) will return because of4477// (a) notification4478// (b) timeout4479// (c) thread.interrupt4480//4481// Thread.interrupt and object.notify{All} both call Event::set.4482// That is, we treat thread.interrupt as a special case of notification.4483// The underlying Solaris implementation, cond_timedwait, admits4484// spurious/premature wakeups, but the JLS/JVM spec prevents the4485// JVM from making those visible to Java code. As such, we must4486// filter out spurious wakeups. We assume all ETIME returns are valid.4487//4488// TODO: properly differentiate simultaneous notify+interrupt.4489// In that case, we should propagate the notify to another waiter.44904491while (_Event < 0) {4492status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);4493if (status != 0 && WorkAroundNPTLTimedWaitHang) {4494pthread_cond_destroy (_cond);4495pthread_cond_init (_cond, NULL) ;4496}4497assert_status(status == 0 || status == EINTR ||4498status == ETIMEDOUT,4499status, "cond_timedwait");4500if (!FilterSpuriousWakeups) break ; // previous semantics4501if (status == ETIMEDOUT) break ;4502// We consume and ignore EINTR and spurious wakeups.4503}4504--_nParked ;4505if (_Event >= 0) {4506ret = OS_OK;4507}4508_Event = 0 ;4509status = pthread_mutex_unlock(_mutex);4510assert_status(status == 0, status, "mutex_unlock");4511assert (_nParked == 0, "invariant") ;4512// Paranoia to ensure our locked and lock-free paths interact4513// correctly with each other.4514OrderAccess::fence();4515return ret;4516}45174518void os::PlatformEvent::unpark() {4519// Transitions for _Event:4520// 0 :=> 14521// 1 :=> 14522// -1 :=> either 0 or 1; must signal target thread4523// That is, we can safely transition _Event from -1 to either4524// 0 or 1. Forcing 1 is slightly more efficient for back-to-back4525// unpark() calls.4526// See also: "Semaphores in Plan 9" by Mullender & Cox4527//4528// Note: Forcing a transition from "-1" to "1" on an unpark() means4529// that it will take two back-to-back park() calls for the owning4530// thread to block. This has the benefit of forcing a spurious return4531// from the first park() call after an unpark() call which will help4532// shake out uses of park() and unpark() without condition variables.45334534if (Atomic::xchg(1, &_Event) >= 0) return;45354536// Wait for the thread associated with the event to vacate4537int status = pthread_mutex_lock(_mutex);4538assert_status(status == 0, status, "mutex_lock");4539int AnyWaiters = _nParked;4540assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");4541if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {4542AnyWaiters = 0;4543pthread_cond_signal(_cond);4544}4545status = pthread_mutex_unlock(_mutex);4546assert_status(status == 0, status, "mutex_unlock");4547if (AnyWaiters != 0) {4548status = pthread_cond_signal(_cond);4549assert_status(status == 0, status, "cond_signal");4550}45514552// Note that we signal() _after dropping the lock for "immortal" Events.4553// This is safe and avoids a common class of futile wakeups. In rare4554// circumstances this can cause a thread to return prematurely from4555// cond_{timed}wait() but the spurious wakeup is benign and the victim will4556// simply re-test the condition and re-park itself.4557}455845594560// JSR1664561// -------------------------------------------------------45624563/*4564* The solaris and bsd implementations of park/unpark are fairly4565* conservative for now, but can be improved. They currently use a4566* mutex/condvar pair, plus a a count.4567* Park decrements count if > 0, else does a condvar wait. Unpark4568* sets count to 1 and signals condvar. Only one thread ever waits4569* on the condvar. Contention seen when trying to park implies that someone4570* is unparking you, so don't wait. And spurious returns are fine, so there4571* is no need to track notifications.4572*/45734574#define MAX_SECS 1000000004575/*4576* This code is common to bsd and solaris and will be moved to a4577* common place in dolphin.4578*4579* The passed in time value is either a relative time in nanoseconds4580* or an absolute time in milliseconds. Either way it has to be unpacked4581* into suitable seconds and nanoseconds components and stored in the4582* given timespec structure.4583* Given time is a 64-bit value and the time_t used in the timespec is only4584* a signed-32-bit value (except on 64-bit Bsd) we have to watch for4585* overflow if times way in the future are given. Further on Solaris versions4586* prior to 10 there is a restriction (see cond_timedwait) that the specified4587* number of seconds, in abstime, is less than current_time + 100,000,000.4588* As it will be 28 years before "now + 100000000" will overflow we can4589* ignore overflow and just impose a hard-limit on seconds using the value4590* of "now + 100,000,000". This places a limit on the timeout of about 3.174591* years from "now".4592*/45934594static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {4595assert (time > 0, "convertTime");45964597struct timeval now;4598int status = gettimeofday(&now, NULL);4599assert(status == 0, "gettimeofday");46004601time_t max_secs = now.tv_sec + MAX_SECS;46024603if (isAbsolute) {4604jlong secs = time / 1000;4605if (secs > max_secs) {4606absTime->tv_sec = max_secs;4607}4608else {4609absTime->tv_sec = secs;4610}4611absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;4612}4613else {4614jlong secs = time / NANOSECS_PER_SEC;4615if (secs >= MAX_SECS) {4616absTime->tv_sec = max_secs;4617absTime->tv_nsec = 0;4618}4619else {4620absTime->tv_sec = now.tv_sec + secs;4621absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;4622if (absTime->tv_nsec >= NANOSECS_PER_SEC) {4623absTime->tv_nsec -= NANOSECS_PER_SEC;4624++absTime->tv_sec; // note: this must be <= max_secs4625}4626}4627}4628assert(absTime->tv_sec >= 0, "tv_sec < 0");4629assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");4630assert(absTime->tv_nsec >= 0, "tv_nsec < 0");4631assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");4632}46334634void Parker::park(bool isAbsolute, jlong time) {4635// Ideally we'd do something useful while spinning, such4636// as calling unpackTime().46374638// Optional fast-path check:4639// Return immediately if a permit is available.4640// We depend on Atomic::xchg() having full barrier semantics4641// since we are doing a lock-free update to _counter.4642if (Atomic::xchg(0, &_counter) > 0) return;46434644Thread* thread = Thread::current();4645assert(thread->is_Java_thread(), "Must be JavaThread");4646JavaThread *jt = (JavaThread *)thread;46474648// Optional optimization -- avoid state transitions if there's an interrupt pending.4649// Check interrupt before trying to wait4650if (Thread::is_interrupted(thread, false)) {4651return;4652}46534654// Next, demultiplex/decode time arguments4655struct timespec absTime;4656if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all4657return;4658}4659if (time > 0) {4660unpackTime(&absTime, isAbsolute, time);4661}466246634664// Enter safepoint region4665// Beware of deadlocks such as 6317397.4666// The per-thread Parker:: mutex is a classic leaf-lock.4667// In particular a thread must never block on the Threads_lock while4668// holding the Parker:: mutex. If safepoints are pending both the4669// the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.4670ThreadBlockInVM tbivm(jt);46714672// Don't wait if cannot get lock since interference arises from4673// unblocking. Also. check interrupt before trying wait4674if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {4675return;4676}46774678int status ;4679if (_counter > 0) { // no wait needed4680_counter = 0;4681status = pthread_mutex_unlock(_mutex);4682assert (status == 0, "invariant") ;4683// Paranoia to ensure our locked and lock-free paths interact4684// correctly with each other and Java-level accesses.4685OrderAccess::fence();4686return;4687}46884689#ifdef ASSERT4690// Don't catch signals while blocked; let the running threads have the signals.4691// (This allows a debugger to break into the running thread.)4692sigset_t oldsigs;4693sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();4694pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);4695#endif46964697OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);4698jt->set_suspend_equivalent();4699// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()47004701if (time == 0) {4702status = pthread_cond_wait (_cond, _mutex) ;4703} else {4704status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;4705if (status != 0 && WorkAroundNPTLTimedWaitHang) {4706pthread_cond_destroy (_cond) ;4707pthread_cond_init (_cond, NULL);4708}4709}4710assert_status(status == 0 || status == EINTR ||4711status == ETIMEDOUT,4712status, "cond_timedwait");47134714#ifdef ASSERT4715pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);4716#endif47174718_counter = 0 ;4719status = pthread_mutex_unlock(_mutex) ;4720assert_status(status == 0, status, "invariant") ;4721// Paranoia to ensure our locked and lock-free paths interact4722// correctly with each other and Java-level accesses.4723OrderAccess::fence();47244725// If externally suspended while waiting, re-suspend4726if (jt->handle_special_suspend_equivalent_condition()) {4727jt->java_suspend_self();4728}4729}47304731void Parker::unpark() {4732int s, status ;4733status = pthread_mutex_lock(_mutex);4734assert (status == 0, "invariant") ;4735s = _counter;4736_counter = 1;4737if (s < 1) {4738if (WorkAroundNPTLTimedWaitHang) {4739status = pthread_cond_signal (_cond) ;4740assert (status == 0, "invariant") ;4741status = pthread_mutex_unlock(_mutex);4742assert (status == 0, "invariant") ;4743} else {4744status = pthread_mutex_unlock(_mutex);4745assert (status == 0, "invariant") ;4746status = pthread_cond_signal (_cond) ;4747assert (status == 0, "invariant") ;4748}4749} else {4750pthread_mutex_unlock(_mutex);4751assert (status == 0, "invariant") ;4752}4753}475447554756/* Darwin has no "environ" in a dynamic library. */4757#ifdef __APPLE__4758#include <crt_externs.h>4759#define environ (*_NSGetEnviron())4760#else4761extern char** environ;4762#endif47634764// Run the specified command in a separate process. Return its exit value,4765// or -1 on failure (e.g. can't fork a new process).4766// Unlike system(), this function can be called from signal handler. It4767// doesn't block SIGINT et al.4768int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {4769const char * argv[4] = {"sh", "-c", cmd, NULL};47704771// fork() in BsdThreads/NPTL is not async-safe. It needs to run4772// pthread_atfork handlers and reset pthread library. All we need is a4773// separate process to execve. Make a direct syscall to fork process.4774// On IA64 there's no fork syscall, we have to use fork() and hope for4775// the best...4776pid_t pid = fork();47774778if (pid < 0) {4779// fork failed4780return -1;47814782} else if (pid == 0) {4783// child process47844785// execve() in BsdThreads will call pthread_kill_other_threads_np()4786// first to kill every thread on the thread list. Because this list is4787// not reset by fork() (see notes above), execve() will instead kill4788// every thread in the parent process. We know this is the only thread4789// in the new process, so make a system call directly.4790// IA64 should use normal execve() from glibc to match the glibc fork()4791// above.4792execve("/bin/sh", (char* const*)argv, environ);47934794// execve failed4795_exit(-1);47964797} else {4798// copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't4799// care about the actual exit code, for now.48004801int status;48024803// Wait for the child process to exit. This returns immediately if4804// the child has already exited. */4805while (waitpid(pid, &status, 0) < 0) {4806switch (errno) {4807case ECHILD: return 0;4808case EINTR: break;4809default: return -1;4810}4811}48124813if (WIFEXITED(status)) {4814// The child exited normally; get its exit code.4815return WEXITSTATUS(status);4816} else if (WIFSIGNALED(status)) {4817// The child exited because of a signal4818// The best value to return is 0x80 + signal number,4819// because that is what all Unix shells do, and because4820// it allows callers to distinguish between process exit and4821// process death by signal.4822return 0x80 + WTERMSIG(status);4823} else {4824// Unknown exit code; pass it through4825return status;4826}4827}4828}48294830// is_headless_jre()4831//4832// Test for the existence of xawt/libmawt.so or libawt_xawt.so4833// in order to report if we are running in a headless jre4834//4835// Since JDK8 xawt/libmawt.so was moved into the same directory4836// as libawt.so, and renamed libawt_xawt.so4837//4838bool os::is_headless_jre() {4839#ifdef __APPLE__4840// We no longer build headless-only on Mac OS X4841return false;4842#else4843struct stat statbuf;4844char buf[MAXPATHLEN];4845char libmawtpath[MAXPATHLEN];4846const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX;4847const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;4848char *p;48494850// Get path to libjvm.so4851os::jvm_path(buf, sizeof(buf));48524853// Get rid of libjvm.so4854p = strrchr(buf, '/');4855if (p == NULL) return false;4856else *p = '\0';48574858// Get rid of client or server4859p = strrchr(buf, '/');4860if (p == NULL) return false;4861else *p = '\0';48624863// check xawt/libmawt.so4864strcpy(libmawtpath, buf);4865strcat(libmawtpath, xawtstr);4866if (::stat(libmawtpath, &statbuf) == 0) return false;48674868// check libawt_xawt.so4869strcpy(libmawtpath, buf);4870strcat(libmawtpath, new_xawtstr);4871if (::stat(libmawtpath, &statbuf) == 0) return false;48724873return true;4874#endif4875}48764877// Get the default path to the core file4878// Returns the length of the string4879int os::get_core_path(char* buffer, size_t bufferSize) {4880int n = jio_snprintf(buffer, bufferSize, "/cores");48814882// Truncate if theoretical string was longer than bufferSize4883n = MIN2(n, (int)bufferSize);48844885return n;4886}48874888#ifndef PRODUCT4889void TestReserveMemorySpecial_test() {4890// No tests available for this platform4891}4892#endif489348944895