Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/bsd/vm/os_bsd.cpp
32285 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(AARCH64)230static char cpu_arch[] = "aarch64";231#elif defined(PPC32)232static char cpu_arch[] = "ppc";233#elif defined(SPARC)234# ifdef _LP64235static char cpu_arch[] = "sparcv9";236# else237static char cpu_arch[] = "sparc";238# endif239#else240#error Add appropriate cpu_arch setting241#endif242243// Compiler variant244#ifdef COMPILER2245#define COMPILER_VARIANT "server"246#else247#define COMPILER_VARIANT "client"248#endif249250251void os::Bsd::initialize_system_info() {252int mib[2];253size_t len;254int cpu_val;255julong mem_val;256257/* get processors count via hw.ncpus sysctl */258mib[0] = CTL_HW;259mib[1] = HW_NCPU;260len = sizeof(cpu_val);261if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {262assert(len == sizeof(cpu_val), "unexpected data size");263set_processor_count(cpu_val);264}265else {266set_processor_count(1); // fallback267}268269/* get physical memory via hw.memsize sysctl (hw.memsize is used270* since it returns a 64 bit value)271*/272mib[0] = CTL_HW;273274#if defined (HW_MEMSIZE) // Apple275mib[1] = HW_MEMSIZE;276#elif defined(HW_PHYSMEM) // Most of BSD277mib[1] = HW_PHYSMEM;278#elif defined(HW_REALMEM) // Old FreeBSD279mib[1] = HW_REALMEM;280#else281#error No ways to get physmem282#endif283284len = sizeof(mem_val);285if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {286assert(len == sizeof(mem_val), "unexpected data size");287_physical_memory = mem_val;288} else {289_physical_memory = 256*1024*1024; // fallback (XXXBSD?)290}291292#ifdef __OpenBSD__293{294// limit _physical_memory memory view on OpenBSD since295// datasize rlimit restricts us anyway.296struct rlimit limits;297getrlimit(RLIMIT_DATA, &limits);298_physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);299}300#endif301}302303#ifdef __APPLE__304static const char *get_home() {305const char *home_dir = ::getenv("HOME");306if ((home_dir == NULL) || (*home_dir == '\0')) {307struct passwd *passwd_info = getpwuid(geteuid());308if (passwd_info != NULL) {309home_dir = passwd_info->pw_dir;310}311}312313return home_dir;314}315#endif316317void os::init_system_properties_values() {318// The next steps are taken in the product version:319//320// Obtain the JAVA_HOME value from the location of libjvm.so.321// This library should be located at:322// <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.323//324// If "/jre/lib/" appears at the right place in the path, then we325// assume libjvm.so is installed in a JDK and we use this path.326//327// Otherwise exit with message: "Could not create the Java virtual machine."328//329// The following extra steps are taken in the debugging version:330//331// If "/jre/lib/" does NOT appear at the right place in the path332// instead of exit check for $JAVA_HOME environment variable.333//334// If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,335// then we append a fake suffix "hotspot/libjvm.so" to this path so336// it looks like libjvm.so is installed there337// <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.338//339// Otherwise exit.340//341// Important note: if the location of libjvm.so changes this342// code needs to be changed accordingly.343344// See ld(1):345// The linker uses the following search paths to locate required346// shared libraries:347// 1: ...348// ...349// 7: The default directories, normally /lib and /usr/lib.350#ifndef DEFAULT_LIBPATH351#define DEFAULT_LIBPATH "/lib:/usr/lib"352#endif353354// Base path of extensions installed on the system.355#define SYS_EXT_DIR "/usr/java/packages"356#define EXTENSIONS_DIR "/lib/ext"357#define ENDORSED_DIR "/lib/endorsed"358359#ifndef __APPLE__360361// Buffer that fits several sprintfs.362// Note that the space for the colon and the trailing null are provided363// by the nulls included by the sizeof operator.364const size_t bufsize =365MAX3((size_t)MAXPATHLEN, // For dll_dir & friends.366(size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir367(size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir368char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);369370// sysclasspath, java_home, dll_dir371{372char *pslash;373os::jvm_path(buf, bufsize);374375// Found the full path to libjvm.so.376// Now cut the path to <java_home>/jre if we can.377*(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.378pslash = strrchr(buf, '/');379if (pslash != NULL) {380*pslash = '\0'; // Get rid of /{client|server|hotspot}.381}382Arguments::set_dll_dir(buf);383384if (pslash != NULL) {385pslash = strrchr(buf, '/');386if (pslash != NULL) {387*pslash = '\0'; // Get rid of /<arch>.388pslash = strrchr(buf, '/');389if (pslash != NULL) {390*pslash = '\0'; // Get rid of /lib.391}392}393}394Arguments::set_java_home(buf);395set_boot_path('/', ':');396}397398// Where to look for native libraries.399//400// Note: Due to a legacy implementation, most of the library path401// is set in the launcher. This was to accomodate linking restrictions402// on legacy Bsd implementations (which are no longer supported).403// Eventually, all the library path setting will be done here.404//405// However, to prevent the proliferation of improperly built native406// libraries, the new path component /usr/java/packages is added here.407// Eventually, all the library path setting will be done here.408{409// Get the user setting of LD_LIBRARY_PATH, and prepended it. It410// should always exist (until the legacy problem cited above is411// addressed).412const char *v = ::getenv("LD_LIBRARY_PATH");413const char *v_colon = ":";414if (v == NULL) { v = ""; v_colon = ""; }415// That's +1 for the colon and +1 for the trailing '\0'.416char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,417strlen(v) + 1 +418sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,419mtInternal);420sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);421Arguments::set_library_path(ld_library_path);422FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);423}424425// Extensions directories.426sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());427Arguments::set_ext_dirs(buf);428429// Endorsed standards default directory.430sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());431Arguments::set_endorsed_dirs(buf);432433FREE_C_HEAP_ARRAY(char, buf, mtInternal);434435#else // __APPLE__436437#define SYS_EXTENSIONS_DIR "/Library/Java/Extensions"438#define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"439440const char *user_home_dir = get_home();441// The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.442size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +443sizeof(SYS_EXTENSIONS_DIRS);444445// Buffer that fits several sprintfs.446// Note that the space for the colon and the trailing null are provided447// by the nulls included by the sizeof operator.448const size_t bufsize =449MAX3((size_t)MAXPATHLEN, // for dll_dir & friends.450(size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size, // extensions dir451(size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir452char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);453454// sysclasspath, java_home, dll_dir455{456char *pslash;457os::jvm_path(buf, bufsize);458459// Found the full path to libjvm.so.460// Now cut the path to <java_home>/jre if we can.461*(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.462pslash = strrchr(buf, '/');463if (pslash != NULL) {464*pslash = '\0'; // Get rid of /{client|server|hotspot}.465}466Arguments::set_dll_dir(buf);467468if (pslash != NULL) {469pslash = strrchr(buf, '/');470if (pslash != NULL) {471*pslash = '\0'; // Get rid of /lib.472}473}474Arguments::set_java_home(buf);475set_boot_path('/', ':');476}477478// Where to look for native libraries.479//480// Note: Due to a legacy implementation, most of the library path481// is set in the launcher. This was to accomodate linking restrictions482// on legacy Bsd implementations (which are no longer supported).483// Eventually, all the library path setting will be done here.484//485// However, to prevent the proliferation of improperly built native486// libraries, the new path component /usr/java/packages is added here.487// Eventually, all the library path setting will be done here.488{489// Get the user setting of LD_LIBRARY_PATH, and prepended it. It490// should always exist (until the legacy problem cited above is491// addressed).492// Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code493// can specify a directory inside an app wrapper494const char *l = ::getenv("JAVA_LIBRARY_PATH");495const char *l_colon = ":";496if (l == NULL) { l = ""; l_colon = ""; }497498const char *v = ::getenv("DYLD_LIBRARY_PATH");499const char *v_colon = ":";500if (v == NULL) { v = ""; v_colon = ""; }501502// Apple's Java6 has "." at the beginning of java.library.path.503// OpenJDK on Windows has "." at the end of java.library.path.504// OpenJDK on Linux and Solaris don't have "." in java.library.path505// at all. To ease the transition from Apple's Java6 to OpenJDK7,506// "." is appended to the end of java.library.path. Yes, this507// could cause a change in behavior, but Apple's Java6 behavior508// can be achieved by putting "." at the beginning of the509// JAVA_LIBRARY_PATH environment variable.510char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,511strlen(v) + 1 + strlen(l) + 1 +512system_ext_size + 3,513mtInternal);514sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",515v, v_colon, l, l_colon, user_home_dir);516Arguments::set_library_path(ld_library_path);517FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);518}519520// Extensions directories.521//522// Note that the space for the colon and the trailing null are provided523// by the nulls included by the sizeof operator (so actually one byte more524// than necessary is allocated).525sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,526user_home_dir, Arguments::get_java_home());527Arguments::set_ext_dirs(buf);528529// Endorsed standards default directory.530sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());531Arguments::set_endorsed_dirs(buf);532533FREE_C_HEAP_ARRAY(char, buf, mtInternal);534535#undef SYS_EXTENSIONS_DIR536#undef SYS_EXTENSIONS_DIRS537538#endif // __APPLE__539540#undef SYS_EXT_DIR541#undef EXTENSIONS_DIR542#undef ENDORSED_DIR543}544545////////////////////////////////////////////////////////////////////////////////546// breakpoint support547548void os::breakpoint() {549BREAKPOINT;550}551552extern "C" void breakpoint() {553// use debugger to set breakpoint here554}555556////////////////////////////////////////////////////////////////////////////////557// signal support558559debug_only(static bool signal_sets_initialized = false);560static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;561562bool os::Bsd::is_sig_ignored(int sig) {563struct sigaction oact;564sigaction(sig, (struct sigaction*)NULL, &oact);565void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)566: CAST_FROM_FN_PTR(void*, oact.sa_handler);567if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))568return true;569else570return false;571}572573void os::Bsd::signal_sets_init() {574// Should also have an assertion stating we are still single-threaded.575assert(!signal_sets_initialized, "Already initialized");576// Fill in signals that are necessarily unblocked for all threads in577// the VM. Currently, we unblock the following signals:578// SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden579// by -Xrs (=ReduceSignalUsage));580// BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all581// other threads. The "ReduceSignalUsage" boolean tells us not to alter582// the dispositions or masks wrt these signals.583// Programs embedding the VM that want to use the above signals for their584// own purposes must, at this time, use the "-Xrs" option to prevent585// interference with shutdown hooks and BREAK_SIGNAL thread dumping.586// (See bug 4345157, and other related bugs).587// In reality, though, unblocking these signals is really a nop, since588// these signals are not blocked by default.589sigemptyset(&unblocked_sigs);590sigemptyset(&allowdebug_blocked_sigs);591sigaddset(&unblocked_sigs, SIGILL);592sigaddset(&unblocked_sigs, SIGSEGV);593sigaddset(&unblocked_sigs, SIGBUS);594sigaddset(&unblocked_sigs, SIGFPE);595sigaddset(&unblocked_sigs, SR_signum);596597if (!ReduceSignalUsage) {598if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {599sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);600sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);601}602if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {603sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);604sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);605}606if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {607sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);608sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);609}610}611// Fill in signals that are blocked by all but the VM thread.612sigemptyset(&vm_sigs);613if (!ReduceSignalUsage)614sigaddset(&vm_sigs, BREAK_SIGNAL);615debug_only(signal_sets_initialized = true);616617}618619// These are signals that are unblocked while a thread is running Java.620// (For some reason, they get blocked by default.)621sigset_t* os::Bsd::unblocked_signals() {622assert(signal_sets_initialized, "Not initialized");623return &unblocked_sigs;624}625626// These are the signals that are blocked while a (non-VM) thread is627// running Java. Only the VM thread handles these signals.628sigset_t* os::Bsd::vm_signals() {629assert(signal_sets_initialized, "Not initialized");630return &vm_sigs;631}632633// These are signals that are blocked during cond_wait to allow debugger in634sigset_t* os::Bsd::allowdebug_blocked_signals() {635assert(signal_sets_initialized, "Not initialized");636return &allowdebug_blocked_sigs;637}638639void os::Bsd::hotspot_sigmask(Thread* thread) {640641//Save caller's signal mask before setting VM signal mask642sigset_t caller_sigmask;643pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);644645OSThread* osthread = thread->osthread();646osthread->set_caller_sigmask(caller_sigmask);647648pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);649650if (!ReduceSignalUsage) {651if (thread->is_VM_thread()) {652// Only the VM thread handles BREAK_SIGNAL ...653pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);654} else {655// ... all other threads block BREAK_SIGNAL656pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);657}658}659}660661662//////////////////////////////////////////////////////////////////////////////663// create new thread664665// check if it's safe to start a new thread666static bool _thread_safety_check(Thread* thread) {667return true;668}669670#ifdef __APPLE__671// library handle for calling objc_registerThreadWithCollector()672// without static linking to the libobjc library673#define OBJC_LIB "/usr/lib/libobjc.dylib"674#define OBJC_GCREGISTER "objc_registerThreadWithCollector"675typedef void (*objc_registerThreadWithCollector_t)();676extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;677objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;678#endif679680#ifdef __APPLE__681static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {682// Additional thread_id used to correlate threads in SA683thread_identifier_info_data_t m_ident_info;684mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;685686thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,687(thread_info_t) &m_ident_info, &count);688689return m_ident_info.thread_id;690}691#endif692693// Thread start routine for all newly created threads694static void *java_start(Thread *thread) {695// Try to randomize the cache line index of hot stack frames.696// This helps when threads of the same stack traces evict each other's697// cache lines. The threads can be either from the same JVM instance, or698// from different JVM instances. The benefit is especially true for699// processors with hyperthreading technology.700static int counter = 0;701int pid = os::current_process_id();702alloca(((pid ^ counter++) & 7) * 128);703704ThreadLocalStorage::set_thread(thread);705706OSThread* osthread = thread->osthread();707Monitor* sync = osthread->startThread_lock();708709// non floating stack BsdThreads needs extra check, see above710if (!_thread_safety_check(thread)) {711// notify parent thread712MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);713osthread->set_state(ZOMBIE);714sync->notify_all();715return NULL;716}717718osthread->set_thread_id(os::Bsd::gettid());719720#ifdef __APPLE__721uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());722guarantee(unique_thread_id != 0, "unique thread id was not found");723osthread->set_unique_thread_id(unique_thread_id);724#endif725// initialize signal mask for this thread726os::Bsd::hotspot_sigmask(thread);727728// initialize floating point control register729os::Bsd::init_thread_fpu_state();730731#ifdef __APPLE__732// register thread with objc gc733if (objc_registerThreadWithCollectorFunction != NULL) {734objc_registerThreadWithCollectorFunction();735}736#endif737738// handshaking with parent thread739{740MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);741742// notify parent thread743osthread->set_state(INITIALIZED);744sync->notify_all();745746// wait until os::start_thread()747while (osthread->get_state() == INITIALIZED) {748sync->wait(Mutex::_no_safepoint_check_flag);749}750}751752// call one more level start routine753thread->run();754755return 0;756}757758bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {759assert(thread->osthread() == NULL, "caller responsible");760761// Allocate the OSThread object762OSThread* osthread = new OSThread(NULL, NULL);763if (osthread == NULL) {764return false;765}766767// set the correct thread state768osthread->set_thread_type(thr_type);769770// Initial state is ALLOCATED but not INITIALIZED771osthread->set_state(ALLOCATED);772773thread->set_osthread(osthread);774775// init thread attributes776pthread_attr_t attr;777pthread_attr_init(&attr);778pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);779780// stack size781if (os::Bsd::supports_variable_stack_size()) {782// calculate stack size if it's not specified by caller783if (stack_size == 0) {784stack_size = os::Bsd::default_stack_size(thr_type);785786switch (thr_type) {787case os::java_thread:788// Java threads use ThreadStackSize which default value can be789// changed with the flag -Xss790assert (JavaThread::stack_size_at_create() > 0, "this should be set");791stack_size = JavaThread::stack_size_at_create();792break;793case os::compiler_thread:794if (CompilerThreadStackSize > 0) {795stack_size = (size_t)(CompilerThreadStackSize * K);796break;797} // else fall through:798// use VMThreadStackSize if CompilerThreadStackSize is not defined799case os::vm_thread:800case os::pgc_thread:801case os::cgc_thread:802case os::watcher_thread:803if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);804break;805}806}807808stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);809pthread_attr_setstacksize(&attr, stack_size);810} else {811// let pthread_create() pick the default value.812}813814ThreadState state;815816{817pthread_t tid;818int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);819820pthread_attr_destroy(&attr);821822if (ret != 0) {823if (PrintMiscellaneous && (Verbose || WizardMode)) {824perror("pthread_create()");825}826// Need to clean up stuff we've allocated so far827thread->set_osthread(NULL);828delete osthread;829return false;830}831832// Store pthread info into the OSThread833osthread->set_pthread_id(tid);834835// Wait until child thread is either initialized or aborted836{837Monitor* sync_with_child = osthread->startThread_lock();838MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);839while ((state = osthread->get_state()) == ALLOCATED) {840sync_with_child->wait(Mutex::_no_safepoint_check_flag);841}842}843844}845846// Aborted due to thread limit being reached847if (state == ZOMBIE) {848thread->set_osthread(NULL);849delete osthread;850return false;851}852853// The thread is returned suspended (in state INITIALIZED),854// and is started higher up in the call chain855assert(state == INITIALIZED, "race condition");856return true;857}858859/////////////////////////////////////////////////////////////////////////////860// attach existing thread861862// bootstrap the main thread863bool os::create_main_thread(JavaThread* thread) {864assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");865return create_attached_thread(thread);866}867868bool os::create_attached_thread(JavaThread* thread) {869#ifdef ASSERT870thread->verify_not_published();871#endif872873// Allocate the OSThread object874OSThread* osthread = new OSThread(NULL, NULL);875876if (osthread == NULL) {877return false;878}879880osthread->set_thread_id(os::Bsd::gettid());881882// Store pthread info into the OSThread883#ifdef __APPLE__884uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());885guarantee(unique_thread_id != 0, "just checking");886osthread->set_unique_thread_id(unique_thread_id);887#endif888osthread->set_pthread_id(::pthread_self());889890// initialize floating point control register891os::Bsd::init_thread_fpu_state();892893// Initial thread state is RUNNABLE894osthread->set_state(RUNNABLE);895896thread->set_osthread(osthread);897898// initialize signal mask for this thread899// and save the caller's signal mask900os::Bsd::hotspot_sigmask(thread);901902return true;903}904905void os::pd_start_thread(Thread* thread) {906OSThread * osthread = thread->osthread();907assert(osthread->get_state() != INITIALIZED, "just checking");908Monitor* sync_with_child = osthread->startThread_lock();909MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);910sync_with_child->notify();911}912913// Free Bsd resources related to the OSThread914void os::free_thread(OSThread* osthread) {915assert(osthread != NULL, "osthread not set");916917if (Thread::current()->osthread() == osthread) {918// Restore caller's signal mask919sigset_t sigmask = osthread->caller_sigmask();920pthread_sigmask(SIG_SETMASK, &sigmask, NULL);921}922923delete osthread;924}925926//////////////////////////////////////////////////////////////////////////////927// thread local storage928929// Restore the thread pointer if the destructor is called. This is in case930// someone from JNI code sets up a destructor with pthread_key_create to run931// detachCurrentThread on thread death. Unless we restore the thread pointer we932// will hang or crash. When detachCurrentThread is called the key will be set933// to null and we will not be called again. If detachCurrentThread is never934// called we could loop forever depending on the pthread implementation.935static void restore_thread_pointer(void* p) {936Thread* thread = (Thread*) p;937os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread);938}939940int os::allocate_thread_local_storage() {941pthread_key_t key;942int rslt = pthread_key_create(&key, restore_thread_pointer);943assert(rslt == 0, "cannot allocate thread local storage");944return (int)key;945}946947// Note: This is currently not used by VM, as we don't destroy TLS key948// on VM exit.949void os::free_thread_local_storage(int index) {950int rslt = pthread_key_delete((pthread_key_t)index);951assert(rslt == 0, "invalid index");952}953954void os::thread_local_storage_at_put(int index, void* value) {955int rslt = pthread_setspecific((pthread_key_t)index, value);956assert(rslt == 0, "pthread_setspecific failed");957}958959extern "C" Thread* get_thread() {960return ThreadLocalStorage::thread();961}962963964////////////////////////////////////////////////////////////////////////////////965// time support966967// Time since start-up in seconds to a fine granularity.968// Used by VMSelfDestructTimer and the MemProfiler.969double os::elapsedTime() {970971return ((double)os::elapsed_counter()) / os::elapsed_frequency();972}973974jlong os::elapsed_counter() {975return javaTimeNanos() - initial_time_count;976}977978jlong os::elapsed_frequency() {979return NANOSECS_PER_SEC; // nanosecond resolution980}981982bool os::supports_vtime() { return true; }983bool os::enable_vtime() { return false; }984bool os::vtime_enabled() { return false; }985986double os::elapsedVTime() {987// better than nothing, but not much988return elapsedTime();989}990991jlong os::javaTimeMillis() {992timeval time;993int status = gettimeofday(&time, NULL);994assert(status != -1, "bsd error");995return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);996}997998#ifndef __APPLE__999#ifndef CLOCK_MONOTONIC1000#define CLOCK_MONOTONIC (1)1001#endif1002#endif10031004#ifdef __APPLE__1005void os::Bsd::clock_init() {1006mach_timebase_info(&_timebase_info);1007}1008#else1009void os::Bsd::clock_init() {1010struct timespec res;1011struct timespec tp;1012if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&1013::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {1014// yes, monotonic clock is supported1015_clock_gettime = ::clock_gettime;1016}1017}1018#endif101910201021#ifdef __APPLE__10221023jlong os::javaTimeNanos() {1024const uint64_t tm = mach_absolute_time();1025const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;1026const uint64_t prev = Bsd::_max_abstime;1027if (now <= prev) {1028return prev; // same or retrograde time;1029}1030const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev);1031assert(obsv >= prev, "invariant"); // Monotonicity1032// If the CAS succeeded then we're done and return "now".1033// If the CAS failed and the observed value "obsv" is >= now then1034// we should return "obsv". If the CAS failed and now > obsv > prv then1035// some other thread raced this thread and installed a new value, in which case1036// we could either (a) retry the entire operation, (b) retry trying to install now1037// or (c) just return obsv. We use (c). No loop is required although in some cases1038// we might discard a higher "now" value in deference to a slightly lower but freshly1039// installed obsv value. That's entirely benign -- it admits no new orderings compared1040// to (a) or (b) -- and greatly reduces coherence traffic.1041// We might also condition (c) on the magnitude of the delta between obsv and now.1042// Avoiding excessive CAS operations to hot RW locations is critical.1043// See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate1044return (prev == obsv) ? now : obsv;1045}10461047#else // __APPLE__10481049jlong os::javaTimeNanos() {1050if (Bsd::supports_monotonic_clock()) {1051struct timespec tp;1052int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp);1053assert(status == 0, "gettime error");1054jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);1055return result;1056} else {1057timeval time;1058int status = gettimeofday(&time, NULL);1059assert(status != -1, "bsd error");1060jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);1061return 1000 * usecs;1062}1063}10641065#endif // __APPLE__10661067void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {1068if (Bsd::supports_monotonic_clock()) {1069info_ptr->max_value = ALL_64_BITS;10701071// CLOCK_MONOTONIC - amount of time since some arbitrary point in the past1072info_ptr->may_skip_backward = false; // not subject to resetting or drifting1073info_ptr->may_skip_forward = false; // not subject to resetting or drifting1074} else {1075// gettimeofday - based on time in seconds since the Epoch thus does not wrap1076info_ptr->max_value = ALL_64_BITS;10771078// gettimeofday is a real time clock so it skips1079info_ptr->may_skip_backward = true;1080info_ptr->may_skip_forward = true;1081}10821083info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time1084}10851086// Return the real, user, and system times in seconds from an1087// arbitrary fixed point in the past.1088bool os::getTimesSecs(double* process_real_time,1089double* process_user_time,1090double* process_system_time) {1091struct tms ticks;1092clock_t real_ticks = times(&ticks);10931094if (real_ticks == (clock_t) (-1)) {1095return false;1096} else {1097double ticks_per_second = (double) clock_tics_per_sec;1098*process_user_time = ((double) ticks.tms_utime) / ticks_per_second;1099*process_system_time = ((double) ticks.tms_stime) / ticks_per_second;1100*process_real_time = ((double) real_ticks) / ticks_per_second;11011102return true;1103}1104}110511061107char * os::local_time_string(char *buf, size_t buflen) {1108struct tm t;1109time_t long_time;1110time(&long_time);1111localtime_r(&long_time, &t);1112jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",1113t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,1114t.tm_hour, t.tm_min, t.tm_sec);1115return buf;1116}11171118struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {1119return localtime_r(clock, res);1120}11211122////////////////////////////////////////////////////////////////////////////////1123// runtime exit support11241125// Note: os::shutdown() might be called very early during initialization, or1126// called from signal handler. Before adding something to os::shutdown(), make1127// sure it is async-safe and can handle partially initialized VM.1128void os::shutdown() {11291130// allow PerfMemory to attempt cleanup of any persistent resources1131perfMemory_exit();11321133// needs to remove object in file system1134AttachListener::abort();11351136// flush buffered output, finish log files1137ostream_abort();11381139// Check for abort hook1140abort_hook_t abort_hook = Arguments::abort_hook();1141if (abort_hook != NULL) {1142abort_hook();1143}11441145}11461147// Note: os::abort() might be called very early during initialization, or1148// called from signal handler. Before adding something to os::abort(), make1149// sure it is async-safe and can handle partially initialized VM.1150void os::abort(bool dump_core) {1151os::shutdown();1152if (dump_core) {1153#ifndef PRODUCT1154fdStream out(defaultStream::output_fd());1155out.print_raw("Current thread is ");1156char buf[16];1157jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());1158out.print_raw_cr(buf);1159out.print_raw_cr("Dumping core ...");1160#endif1161::abort(); // dump core1162}11631164::exit(1);1165}11661167// Die immediately, no exit hook, no abort hook, no cleanup.1168void os::die() {1169// _exit() on BsdThreads only kills current thread1170::abort();1171}11721173// This method is a copy of JDK's sysGetLastErrorString1174// from src/solaris/hpi/src/system_md.c11751176size_t os::lasterror(char *buf, size_t len) {11771178if (errno == 0) return 0;11791180const char *s = ::strerror(errno);1181size_t n = ::strlen(s);1182if (n >= len) {1183n = len - 1;1184}1185::strncpy(buf, s, n);1186buf[n] = '\0';1187return n;1188}11891190// Information of current thread in variety of formats1191pid_t os::Bsd::gettid() {1192int retval = -1;11931194#ifdef __APPLE__ //XNU kernel1195// despite the fact mach port is actually not a thread id use it1196// instead of syscall(SYS_thread_selfid) as it certainly fits to u41197retval = ::pthread_mach_thread_np(::pthread_self());1198guarantee(retval != 0, "just checking");1199return retval;12001201#else1202#ifdef __FreeBSD__1203retval = syscall(SYS_thr_self);1204#else1205#ifdef __OpenBSD__1206retval = syscall(SYS_getthrid);1207#else1208#ifdef __NetBSD__1209retval = (pid_t) syscall(SYS__lwp_self);1210#endif1211#endif1212#endif1213#endif12141215if (retval == -1) {1216return getpid();1217}1218}12191220intx os::current_thread_id() {1221#ifdef __APPLE__1222return (intx)::pthread_mach_thread_np(::pthread_self());1223#else1224return (intx)::pthread_self();1225#endif1226}12271228int os::current_process_id() {12291230// Under the old bsd thread library, bsd gives each thread1231// its own process id. Because of this each thread will return1232// a different pid if this method were to return the result1233// of getpid(2). Bsd provides no api that returns the pid1234// of the launcher thread for the vm. This implementation1235// returns a unique pid, the pid of the launcher thread1236// that starts the vm 'process'.12371238// Under the NPTL, getpid() returns the same pid as the1239// launcher thread rather than a unique pid per thread.1240// Use gettid() if you want the old pre NPTL behaviour.12411242// if you are looking for the result of a call to getpid() that1243// returns a unique pid for the calling thread, then look at the1244// OSThread::thread_id() method in osThread_bsd.hpp file12451246return (int)(_initial_pid ? _initial_pid : getpid());1247}12481249// DLL functions12501251#define JNI_LIB_PREFIX "lib"1252#ifdef __APPLE__1253#define JNI_LIB_SUFFIX ".dylib"1254#else1255#define JNI_LIB_SUFFIX ".so"1256#endif12571258const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }12591260// This must be hard coded because it's the system's temporary1261// directory not the java application's temp directory, ala java.io.tmpdir.1262#ifdef __APPLE__1263// macosx has a secure per-user temporary directory1264char temp_path_storage[PATH_MAX];1265const char* os::get_temp_directory() {1266static char *temp_path = NULL;1267if (temp_path == NULL) {1268int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);1269if (pathSize == 0 || pathSize > PATH_MAX) {1270strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));1271}1272temp_path = temp_path_storage;1273}1274return temp_path;1275}1276#else /* __APPLE__ */1277const char* os::get_temp_directory() { return "/tmp"; }1278#endif /* __APPLE__ */12791280static bool file_exists(const char* filename) {1281struct stat statbuf;1282if (filename == NULL || strlen(filename) == 0) {1283return false;1284}1285return os::stat(filename, &statbuf) == 0;1286}12871288bool os::dll_build_name(char* buffer, size_t buflen,1289const char* pname, const char* fname) {1290bool retval = false;1291// Copied from libhpi1292const size_t pnamelen = pname ? strlen(pname) : 0;12931294// Return error on buffer overflow.1295if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {1296return retval;1297}12981299if (pnamelen == 0) {1300snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);1301retval = true;1302} else if (strchr(pname, *os::path_separator()) != NULL) {1303int n;1304char** pelements = split_path(pname, &n);1305if (pelements == NULL) {1306return false;1307}1308for (int i = 0 ; i < n ; i++) {1309// Really shouldn't be NULL, but check can't hurt1310if (pelements[i] == NULL || strlen(pelements[i]) == 0) {1311continue; // skip the empty path values1312}1313snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,1314pelements[i], fname);1315if (file_exists(buffer)) {1316retval = true;1317break;1318}1319}1320// release the storage1321for (int i = 0 ; i < n ; i++) {1322if (pelements[i] != NULL) {1323FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);1324}1325}1326if (pelements != NULL) {1327FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);1328}1329} else {1330snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);1331retval = true;1332}1333return retval;1334}13351336// check if addr is inside libjvm.so1337bool os::address_is_in_vm(address addr) {1338static address libjvm_base_addr;1339Dl_info dlinfo;13401341if (libjvm_base_addr == NULL) {1342if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {1343libjvm_base_addr = (address)dlinfo.dli_fbase;1344}1345assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");1346}13471348if (dladdr((void *)addr, &dlinfo) != 0) {1349if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;1350}13511352return false;1353}135413551356#define MACH_MAXSYMLEN 25613571358bool os::dll_address_to_function_name(address addr, char *buf,1359int buflen, int *offset) {1360// buf is not optional, but offset is optional1361assert(buf != NULL, "sanity check");13621363Dl_info dlinfo;1364char localbuf[MACH_MAXSYMLEN];13651366if (dladdr((void*)addr, &dlinfo) != 0) {1367// see if we have a matching symbol1368if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {1369if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {1370jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);1371}1372if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;1373return true;1374}1375// no matching symbol so try for just file info1376if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {1377if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),1378buf, buflen, offset, dlinfo.dli_fname)) {1379return true;1380}1381}13821383// Handle non-dynamic manually:1384if (dlinfo.dli_fbase != NULL &&1385Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,1386dlinfo.dli_fbase)) {1387if (!Decoder::demangle(localbuf, buf, buflen)) {1388jio_snprintf(buf, buflen, "%s", localbuf);1389}1390return true;1391}1392}1393buf[0] = '\0';1394if (offset != NULL) *offset = -1;1395return false;1396}13971398// ported from solaris version1399bool os::dll_address_to_library_name(address addr, char* buf,1400int buflen, int* offset) {1401// buf is not optional, but offset is optional1402assert(buf != NULL, "sanity check");14031404Dl_info dlinfo;14051406if (dladdr((void*)addr, &dlinfo) != 0) {1407if (dlinfo.dli_fname != NULL) {1408jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);1409}1410if (dlinfo.dli_fbase != NULL && offset != NULL) {1411*offset = addr - (address)dlinfo.dli_fbase;1412}1413return true;1414}14151416buf[0] = '\0';1417if (offset) *offset = -1;1418return false;1419}14201421// Loads .dll/.so and1422// in case of error it checks if .dll/.so was built for the1423// same architecture as Hotspot is running on14241425#ifdef __APPLE__1426void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {1427void * result= ::dlopen(filename, RTLD_LAZY);1428if (result != NULL) {1429// Successful loading1430return result;1431}14321433// Read system error message into ebuf1434::strncpy(ebuf, ::dlerror(), ebuflen-1);1435ebuf[ebuflen-1]='\0';14361437return NULL;1438}1439#else1440void * os::dll_load(const char *filename, char *ebuf, int ebuflen)1441{1442void * result= ::dlopen(filename, RTLD_LAZY);1443if (result != NULL) {1444// Successful loading1445return result;1446}14471448Elf32_Ehdr elf_head;14491450// Read system error message into ebuf1451// It may or may not be overwritten below1452::strncpy(ebuf, ::dlerror(), ebuflen-1);1453ebuf[ebuflen-1]='\0';1454int diag_msg_max_length=ebuflen-strlen(ebuf);1455char* diag_msg_buf=ebuf+strlen(ebuf);14561457if (diag_msg_max_length==0) {1458// No more space in ebuf for additional diagnostics message1459return NULL;1460}146114621463int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);14641465if (file_descriptor < 0) {1466// Can't open library, report dlerror() message1467return NULL;1468}14691470bool failed_to_read_elf_head=1471(sizeof(elf_head)!=1472(::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;14731474::close(file_descriptor);1475if (failed_to_read_elf_head) {1476// file i/o error - report dlerror() msg1477return NULL;1478}14791480typedef struct {1481Elf32_Half code; // Actual value as defined in elf.h1482Elf32_Half compat_class; // Compatibility of archs at VM's sense1483char elf_class; // 32 or 64 bit1484char endianess; // MSB or LSB1485char* name; // String representation1486} arch_t;14871488#ifndef EM_4861489#define EM_486 6 /* Intel 80486 */1490#endif14911492#ifndef EM_MIPS_RS3_LE1493#define EM_MIPS_RS3_LE 10 /* MIPS */1494#endif14951496#ifndef EM_PPC641497#define EM_PPC64 21 /* PowerPC64 */1498#endif14991500#ifndef EM_S3901501#define EM_S390 22 /* IBM System/390 */1502#endif15031504#ifndef EM_IA_641505#define EM_IA_64 50 /* HP/Intel IA-64 */1506#endif15071508#ifndef EM_X86_641509#define EM_X86_64 62 /* AMD x86-64 */1510#endif15111512static const arch_t arch_array[]={1513{EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1514{EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1515{EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},1516{EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},1517{EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1518{EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1519{EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},1520{EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},1521{EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},1522{EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},1523{EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},1524{EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},1525{EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},1526{EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},1527{EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},1528{EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}1529};15301531#if (defined IA32)1532static Elf32_Half running_arch_code=EM_386;1533#elif (defined AMD64)1534static Elf32_Half running_arch_code=EM_X86_64;1535#elif (defined IA64)1536static Elf32_Half running_arch_code=EM_IA_64;1537#elif (defined __sparc) && (defined _LP64)1538static Elf32_Half running_arch_code=EM_SPARCV9;1539#elif (defined __sparc) && (!defined _LP64)1540static Elf32_Half running_arch_code=EM_SPARC;1541#elif (defined __powerpc64__)1542static Elf32_Half running_arch_code=EM_PPC64;1543#elif (defined __powerpc__)1544static Elf32_Half running_arch_code=EM_PPC;1545#elif (defined ARM)1546static Elf32_Half running_arch_code=EM_ARM;1547#elif (defined S390)1548static Elf32_Half running_arch_code=EM_S390;1549#elif (defined ALPHA)1550static Elf32_Half running_arch_code=EM_ALPHA;1551#elif (defined MIPSEL)1552static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;1553#elif (defined PARISC)1554static Elf32_Half running_arch_code=EM_PARISC;1555#elif (defined MIPS)1556static Elf32_Half running_arch_code=EM_MIPS;1557#elif (defined M68K)1558static Elf32_Half running_arch_code=EM_68K;1559#else1560#error Method os::dll_load requires that one of following is defined:\1561IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K1562#endif15631564// Identify compatability class for VM's architecture and library's architecture1565// Obtain string descriptions for architectures15661567arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};1568int running_arch_index=-1;15691570for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {1571if (running_arch_code == arch_array[i].code) {1572running_arch_index = i;1573}1574if (lib_arch.code == arch_array[i].code) {1575lib_arch.compat_class = arch_array[i].compat_class;1576lib_arch.name = arch_array[i].name;1577}1578}15791580assert(running_arch_index != -1,1581"Didn't find running architecture code (running_arch_code) in arch_array");1582if (running_arch_index == -1) {1583// Even though running architecture detection failed1584// we may still continue with reporting dlerror() message1585return NULL;1586}15871588if (lib_arch.endianess != arch_array[running_arch_index].endianess) {1589::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");1590return NULL;1591}15921593#ifndef S3901594if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {1595::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");1596return NULL;1597}1598#endif // !S39015991600if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {1601if ( lib_arch.name!=NULL ) {1602::snprintf(diag_msg_buf, diag_msg_max_length-1,1603" (Possible cause: can't load %s-bit .so on a %s-bit platform)",1604lib_arch.name, arch_array[running_arch_index].name);1605} else {1606::snprintf(diag_msg_buf, diag_msg_max_length-1,1607" (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",1608lib_arch.code,1609arch_array[running_arch_index].name);1610}1611}16121613return NULL;1614}1615#endif /* !__APPLE__ */16161617void* os::get_default_process_handle() {1618#ifdef __APPLE__1619// MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY1620// to avoid finding unexpected symbols on second (or later)1621// loads of a library.1622return (void*)::dlopen(NULL, RTLD_FIRST);1623#else1624return (void*)::dlopen(NULL, RTLD_LAZY);1625#endif1626}16271628// XXX: Do we need a lock around this as per Linux?1629void* os::dll_lookup(void* handle, const char* name) {1630return dlsym(handle, name);1631}163216331634static bool _print_ascii_file(const char* filename, outputStream* st) {1635int fd = ::open(filename, O_RDONLY);1636if (fd == -1) {1637return false;1638}16391640char buf[32];1641int bytes;1642while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {1643st->print_raw(buf, bytes);1644}16451646::close(fd);16471648return true;1649}16501651void os::print_dll_info(outputStream *st) {1652st->print_cr("Dynamic libraries:");1653#ifdef RTLD_DI_LINKMAP1654Dl_info dli;1655void *handle;1656Link_map *map;1657Link_map *p;16581659if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||1660dli.dli_fname == NULL) {1661st->print_cr("Error: Cannot print dynamic libraries.");1662return;1663}1664handle = dlopen(dli.dli_fname, RTLD_LAZY);1665if (handle == NULL) {1666st->print_cr("Error: Cannot print dynamic libraries.");1667return;1668}1669dlinfo(handle, RTLD_DI_LINKMAP, &map);1670if (map == NULL) {1671st->print_cr("Error: Cannot print dynamic libraries.");1672return;1673}16741675while (map->l_prev != NULL)1676map = map->l_prev;16771678while (map != NULL) {1679st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);1680map = map->l_next;1681}16821683dlclose(handle);1684#elif defined(__APPLE__)1685for (uint32_t i = 1; i < _dyld_image_count(); i++) {1686st->print_cr(PTR_FORMAT " \t%s", _dyld_get_image_header(i),1687_dyld_get_image_name(i));1688}1689#else1690st->print_cr("Error: Cannot print dynamic libraries.");1691#endif1692}16931694int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {1695#ifdef RTLD_DI_LINKMAP1696Dl_info dli;1697void *handle;1698Link_map *map;1699Link_map *p;17001701if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||1702dli.dli_fname == NULL) {1703return 1;1704}1705handle = dlopen(dli.dli_fname, RTLD_LAZY);1706if (handle == NULL) {1707return 1;1708}1709dlinfo(handle, RTLD_DI_LINKMAP, &map);1710if (map == NULL) {1711dlclose(handle);1712return 1;1713}17141715while (map->l_prev != NULL)1716map = map->l_prev;17171718while (map != NULL) {1719// Value for top_address is returned as 0 since we don't have any information about module size1720if (callback(map->l_name, (address)map->l_addr, (address)0, param)) {1721dlclose(handle);1722return 1;1723}1724map = map->l_next;1725}17261727dlclose(handle);1728#elif defined(__APPLE__)1729for (uint32_t i = 1; i < _dyld_image_count(); i++) {1730// Value for top_address is returned as 0 since we don't have any information about module size1731if (callback(_dyld_get_image_name(i), (address)_dyld_get_image_header(i), (address)0, param)) {1732return 1;1733}1734}1735return 0;1736#else1737return 1;1738#endif1739}17401741void os::print_os_info_brief(outputStream* st) {1742st->print("Bsd");17431744os::Posix::print_uname_info(st);1745}17461747void os::print_os_info(outputStream* st) {1748st->print("OS:");1749st->print("Bsd");17501751os::Posix::print_uname_info(st);17521753os::Posix::print_rlimit_info(st);17541755os::Posix::print_load_average(st);1756}17571758void os::pd_print_cpu_info(outputStream* st) {1759// Nothing to do for now.1760}17611762void os::print_memory_info(outputStream* st) {17631764st->print("Memory:");1765st->print(" %dk page", os::vm_page_size()>>10);17661767st->print(", physical " UINT64_FORMAT "k",1768os::physical_memory() >> 10);1769st->print("(" UINT64_FORMAT "k free)",1770os::available_memory() >> 10);1771st->cr();17721773// meminfo1774st->print("\n/proc/meminfo:\n");1775_print_ascii_file("/proc/meminfo", st);1776st->cr();1777}17781779void os::print_siginfo(outputStream* st, void* siginfo) {1780const siginfo_t* si = (const siginfo_t*)siginfo;17811782os::Posix::print_siginfo_brief(st, si);17831784if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&1785UseSharedSpaces) {1786FileMapInfo* mapinfo = FileMapInfo::current_info();1787if (mapinfo->is_in_shared_space(si->si_addr)) {1788st->print("\n\nError accessing class data sharing archive." \1789" Mapped file inaccessible during execution, " \1790" possible disk/network problem.");1791}1792}1793st->cr();1794}179517961797static void print_signal_handler(outputStream* st, int sig,1798char* buf, size_t buflen);17991800void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {1801st->print_cr("Signal Handlers:");1802print_signal_handler(st, SIGSEGV, buf, buflen);1803print_signal_handler(st, SIGBUS , buf, buflen);1804print_signal_handler(st, SIGFPE , buf, buflen);1805print_signal_handler(st, SIGPIPE, buf, buflen);1806print_signal_handler(st, SIGXFSZ, buf, buflen);1807print_signal_handler(st, SIGILL , buf, buflen);1808print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);1809print_signal_handler(st, SR_signum, buf, buflen);1810print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);1811print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);1812print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);1813print_signal_handler(st, BREAK_SIGNAL, buf, buflen);1814}18151816static char saved_jvm_path[MAXPATHLEN] = {0};18171818// Find the full path to the current module, libjvm1819void os::jvm_path(char *buf, jint buflen) {1820// Error checking.1821if (buflen < MAXPATHLEN) {1822assert(false, "must use a large-enough buffer");1823buf[0] = '\0';1824return;1825}1826// Lazy resolve the path to current module.1827if (saved_jvm_path[0] != 0) {1828strcpy(buf, saved_jvm_path);1829return;1830}18311832char dli_fname[MAXPATHLEN];1833bool ret = dll_address_to_library_name(1834CAST_FROM_FN_PTR(address, os::jvm_path),1835dli_fname, sizeof(dli_fname), NULL);1836assert(ret, "cannot locate libjvm");1837char *rp = NULL;1838if (ret && dli_fname[0] != '\0') {1839rp = realpath(dli_fname, buf);1840}1841if (rp == NULL)1842return;18431844if (Arguments::created_by_gamma_launcher()) {1845// Support for the gamma launcher. Typical value for buf is1846// "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at1847// the right place in the string, then assume we are installed in a JDK and1848// we're done. Otherwise, check for a JAVA_HOME environment variable and1849// construct a path to the JVM being overridden.18501851const char *p = buf + strlen(buf) - 1;1852for (int count = 0; p > buf && count < 5; ++count) {1853for (--p; p > buf && *p != '/'; --p)1854/* empty */ ;1855}18561857if (strncmp(p, "/jre/lib/", 9) != 0) {1858// Look for JAVA_HOME in the environment.1859char* java_home_var = ::getenv("JAVA_HOME");1860if (java_home_var != NULL && java_home_var[0] != 0) {1861char* jrelib_p;1862int len;18631864// Check the current module name "libjvm"1865p = strrchr(buf, '/');1866assert(strstr(p, "/libjvm") == p, "invalid library name");18671868rp = realpath(java_home_var, buf);1869if (rp == NULL)1870return;18711872// determine if this is a legacy image or modules image1873// modules image doesn't have "jre" subdirectory1874len = strlen(buf);1875assert(len < buflen, "Ran out of buffer space");1876jrelib_p = buf + len;18771878// Add the appropriate library subdir1879snprintf(jrelib_p, buflen-len, "/jre/lib");1880if (0 != access(buf, F_OK)) {1881snprintf(jrelib_p, buflen-len, "/lib");1882}18831884// Add the appropriate client or server subdir1885len = strlen(buf);1886jrelib_p = buf + len;1887snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);1888if (0 != access(buf, F_OK)) {1889snprintf(jrelib_p, buflen-len, "%s", "");1890}18911892// If the path exists within JAVA_HOME, add the JVM library name1893// to complete the path to JVM being overridden. Otherwise fallback1894// to the path to the current library.1895if (0 == access(buf, F_OK)) {1896// Use current module name "libjvm"1897len = strlen(buf);1898snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);1899} else {1900// Fall back to path of current library1901rp = realpath(dli_fname, buf);1902if (rp == NULL)1903return;1904}1905}1906}1907}19081909strncpy(saved_jvm_path, buf, MAXPATHLEN);1910}19111912void os::print_jni_name_prefix_on(outputStream* st, int args_size) {1913// no prefix required, not even "_"1914}19151916void os::print_jni_name_suffix_on(outputStream* st, int args_size) {1917// no suffix required1918}19191920////////////////////////////////////////////////////////////////////////////////1921// sun.misc.Signal support19221923static volatile jint sigint_count = 0;19241925static void1926UserHandler(int sig, void *siginfo, void *context) {1927// 4511530 - sem_post is serialized and handled by the manager thread. When1928// the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We1929// don't want to flood the manager thread with sem_post requests.1930if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)1931return;19321933// Ctrl-C is pressed during error reporting, likely because the error1934// handler fails to abort. Let VM die immediately.1935if (sig == SIGINT && is_error_reported()) {1936os::die();1937}19381939os::signal_notify(sig);1940}19411942void* os::user_handler() {1943return CAST_FROM_FN_PTR(void*, UserHandler);1944}19451946extern "C" {1947typedef void (*sa_handler_t)(int);1948typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);1949}19501951void* os::signal(int signal_number, void* handler) {1952struct sigaction sigAct, oldSigAct;19531954sigfillset(&(sigAct.sa_mask));1955sigAct.sa_flags = SA_RESTART|SA_SIGINFO;1956sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);19571958if (sigaction(signal_number, &sigAct, &oldSigAct)) {1959// -1 means registration failed1960return (void *)-1;1961}19621963return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);1964}19651966void os::signal_raise(int signal_number) {1967::raise(signal_number);1968}19691970/*1971* The following code is moved from os.cpp for making this1972* code platform specific, which it is by its very nature.1973*/19741975// Will be modified when max signal is changed to be dynamic1976int os::sigexitnum_pd() {1977return NSIG;1978}19791980// a counter for each possible signal value1981static volatile jint pending_signals[NSIG+1] = { 0 };19821983// Bsd(POSIX) specific hand shaking semaphore.1984#ifdef __APPLE__1985typedef semaphore_t os_semaphore_t;1986#define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)1987#define SEM_WAIT(sem) semaphore_wait(sem)1988#define SEM_POST(sem) semaphore_signal(sem)1989#define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem)1990#else1991typedef sem_t os_semaphore_t;1992#define SEM_INIT(sem, value) sem_init(&sem, 0, value)1993#define SEM_WAIT(sem) sem_wait(&sem)1994#define SEM_POST(sem) sem_post(&sem)1995#define SEM_DESTROY(sem) sem_destroy(&sem)1996#endif19971998class Semaphore : public StackObj {1999public:2000Semaphore();2001~Semaphore();2002void signal();2003void wait();2004bool trywait();2005bool timedwait(unsigned int sec, int nsec);2006private:2007jlong currenttime() const;2008os_semaphore_t _semaphore;2009};20102011Semaphore::Semaphore() : _semaphore(0) {2012SEM_INIT(_semaphore, 0);2013}20142015Semaphore::~Semaphore() {2016SEM_DESTROY(_semaphore);2017}20182019void Semaphore::signal() {2020SEM_POST(_semaphore);2021}20222023void Semaphore::wait() {2024SEM_WAIT(_semaphore);2025}20262027jlong Semaphore::currenttime() const {2028struct timeval tv;2029gettimeofday(&tv, NULL);2030return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);2031}20322033#ifdef __APPLE__2034bool Semaphore::trywait() {2035return timedwait(0, 0);2036}20372038bool Semaphore::timedwait(unsigned int sec, int nsec) {2039kern_return_t kr = KERN_ABORTED;2040mach_timespec_t waitspec;2041waitspec.tv_sec = sec;2042waitspec.tv_nsec = nsec;20432044jlong starttime = currenttime();20452046kr = semaphore_timedwait(_semaphore, waitspec);2047while (kr == KERN_ABORTED) {2048jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;20492050jlong current = currenttime();2051jlong passedtime = current - starttime;20522053if (passedtime >= totalwait) {2054waitspec.tv_sec = 0;2055waitspec.tv_nsec = 0;2056} else {2057jlong waittime = totalwait - (current - starttime);2058waitspec.tv_sec = waittime / NANOSECS_PER_SEC;2059waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;2060}20612062kr = semaphore_timedwait(_semaphore, waitspec);2063}20642065return kr == KERN_SUCCESS;2066}20672068#else20692070bool Semaphore::trywait() {2071return sem_trywait(&_semaphore) == 0;2072}20732074bool Semaphore::timedwait(unsigned int sec, int nsec) {2075struct timespec ts;2076unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);20772078while (1) {2079int result = sem_timedwait(&_semaphore, &ts);2080if (result == 0) {2081return true;2082} else if (errno == EINTR) {2083continue;2084} else if (errno == ETIMEDOUT) {2085return false;2086} else {2087return false;2088}2089}2090}20912092#endif // __APPLE__20932094static os_semaphore_t sig_sem;2095static Semaphore sr_semaphore;20962097void os::signal_init_pd() {2098// Initialize signal structures2099::memset((void*)pending_signals, 0, sizeof(pending_signals));21002101// Initialize signal semaphore2102::SEM_INIT(sig_sem, 0);2103}21042105void os::signal_notify(int sig) {2106Atomic::inc(&pending_signals[sig]);2107::SEM_POST(sig_sem);2108}21092110static int check_pending_signals(bool wait) {2111Atomic::store(0, &sigint_count);2112for (;;) {2113for (int i = 0; i < NSIG + 1; i++) {2114jint n = pending_signals[i];2115if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {2116return i;2117}2118}2119if (!wait) {2120return -1;2121}2122JavaThread *thread = JavaThread::current();2123ThreadBlockInVM tbivm(thread);21242125bool threadIsSuspended;2126do {2127thread->set_suspend_equivalent();2128// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()2129::SEM_WAIT(sig_sem);21302131// were we externally suspended while we were waiting?2132threadIsSuspended = thread->handle_special_suspend_equivalent_condition();2133if (threadIsSuspended) {2134//2135// The semaphore has been incremented, but while we were waiting2136// another thread suspended us. We don't want to continue running2137// while suspended because that would surprise the thread that2138// suspended us.2139//2140::SEM_POST(sig_sem);21412142thread->java_suspend_self();2143}2144} while (threadIsSuspended);2145}2146}21472148int os::signal_lookup() {2149return check_pending_signals(false);2150}21512152int os::signal_wait() {2153return check_pending_signals(true);2154}21552156////////////////////////////////////////////////////////////////////////////////2157// Virtual Memory21582159int os::vm_page_size() {2160// Seems redundant as all get out2161assert(os::Bsd::page_size() != -1, "must call os::init");2162return os::Bsd::page_size();2163}21642165// Solaris allocates memory by pages.2166int os::vm_allocation_granularity() {2167assert(os::Bsd::page_size() != -1, "must call os::init");2168return os::Bsd::page_size();2169}21702171// Rationale behind this function:2172// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable2173// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get2174// samples for JITted code. Here we create private executable mapping over the code cache2175// and then we can use standard (well, almost, as mapping can change) way to provide2176// info for the reporting script by storing timestamp and location of symbol2177void bsd_wrap_code(char* base, size_t size) {2178static volatile jint cnt = 0;21792180if (!UseOprofile) {2181return;2182}21832184char buf[PATH_MAX + 1];2185int num = Atomic::add(1, &cnt);21862187snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",2188os::get_temp_directory(), os::current_process_id(), num);2189unlink(buf);21902191int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);21922193if (fd != -1) {2194off_t rv = ::lseek(fd, size-2, SEEK_SET);2195if (rv != (off_t)-1) {2196if (::write(fd, "", 1) == 1) {2197mmap(base, size,2198PROT_READ|PROT_WRITE|PROT_EXEC,2199MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);2200}2201}2202::close(fd);2203unlink(buf);2204}2205}22062207static void warn_fail_commit_memory(char* addr, size_t size, bool exec,2208int err) {2209warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT2210", %d) failed; error='%s' (errno=%d)", addr, size, exec,2211strerror(err), err);2212}22132214// NOTE: Bsd kernel does not really reserve the pages for us.2215// All it does is to check if there are enough free pages2216// left at the time of mmap(). This could be a potential2217// problem.2218bool os::pd_commit_memory(char* addr, size_t size, bool exec) {2219int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;2220#ifdef __OpenBSD__2221// XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD2222if (::mprotect(addr, size, prot) == 0) {2223return true;2224}2225#elif defined(__APPLE__)2226if (exec) {2227// Do not replace MAP_JIT mappings, see JDK-82349302228if (::mprotect(addr, size, prot) == 0) {2229return true;2230}2231} else {2232uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,2233MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);2234if (res != (uintptr_t) MAP_FAILED) {2235return true;2236}2237}2238#else2239uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,2240MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);2241if (res != (uintptr_t) MAP_FAILED) {2242return true;2243}2244#endif22452246// Warn about any commit errors we see in non-product builds just2247// in case mmap() doesn't work as described on the man page.2248NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)22492250return false;2251}22522253bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,2254bool exec) {2255// alignment_hint is ignored on this OS2256return pd_commit_memory(addr, size, exec);2257}22582259void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,2260const char* mesg) {2261assert(mesg != NULL, "mesg must be specified");2262if (!pd_commit_memory(addr, size, exec)) {2263// add extra info in product mode for vm_exit_out_of_memory():2264PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)2265vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);2266}2267}22682269void os::pd_commit_memory_or_exit(char* addr, size_t size,2270size_t alignment_hint, bool exec,2271const char* mesg) {2272// alignment_hint is ignored on this OS2273pd_commit_memory_or_exit(addr, size, exec, mesg);2274}22752276void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {2277}22782279void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {2280::madvise(addr, bytes, MADV_DONTNEED);2281}22822283void os::numa_make_global(char *addr, size_t bytes) {2284}22852286void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {2287}22882289bool os::numa_topology_changed() { return false; }22902291size_t os::numa_get_groups_num() {2292return 1;2293}22942295int os::numa_get_group_id() {2296return 0;2297}22982299size_t os::numa_get_leaf_groups(int *ids, size_t size) {2300if (size > 0) {2301ids[0] = 0;2302return 1;2303}2304return 0;2305}23062307bool os::get_page_info(char *start, page_info* info) {2308return false;2309}23102311char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {2312return end;2313}231423152316bool os::pd_uncommit_memory(char* addr, size_t size, bool exec) {2317#ifdef __OpenBSD__2318// XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD2319return ::mprotect(addr, size, PROT_NONE) == 0;2320#elif defined(__APPLE__)2321if (exec) {2322if (::madvise(addr, size, MADV_FREE) != 0) {2323return false;2324}2325return ::mprotect(addr, size, PROT_NONE) == 0;2326} else {2327uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,2328MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);2329return res != (uintptr_t) MAP_FAILED;2330}2331#else2332uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,2333MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);2334return res != (uintptr_t) MAP_FAILED;2335#endif2336}23372338bool os::pd_create_stack_guard_pages(char* addr, size_t size) {2339return os::commit_memory(addr, size, !ExecMem);2340}23412342// If this is a growable mapping, remove the guard pages entirely by2343// munmap()ping them. If not, just call uncommit_memory().2344bool os::remove_stack_guard_pages(char* addr, size_t size) {2345return os::uncommit_memory(addr, size);2346}23472348static address _highest_vm_reserved_address = NULL;23492350// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory2351// at 'requested_addr'. If there are existing memory mappings at the same2352// location, however, they will be overwritten. If 'fixed' is false,2353// 'requested_addr' is only treated as a hint, the return value may or2354// may not start from the requested address. Unlike Bsd mmap(), this2355// function returns NULL to indicate failure.2356static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed MACOS_AARCH64_ONLY(, bool exec)) {2357char * addr;2358int flags;23592360flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS2361MACOS_AARCH64_ONLY(| (exec ? MAP_JIT : 0));2362if (fixed) {2363assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");2364flags |= MAP_FIXED;2365}23662367// Map reserved/uncommitted pages PROT_NONE so we fail early if we2368// touch an uncommitted page. Otherwise, the read/write might2369// succeed if we have enough swap space to back the physical page.2370addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,2371flags, -1, 0);23722373if (addr != MAP_FAILED) {2374// anon_mmap() should only get called during VM initialization,2375// don't need lock (actually we can skip locking even it can be called2376// from multiple threads, because _highest_vm_reserved_address is just a2377// hint about the upper limit of non-stack memory regions.)2378if ((address)addr + bytes > _highest_vm_reserved_address) {2379_highest_vm_reserved_address = (address)addr + bytes;2380}2381}23822383return addr == MAP_FAILED ? NULL : addr;2384}23852386// Don't update _highest_vm_reserved_address, because there might be memory2387// regions above addr + size. If so, releasing a memory region only creates2388// a hole in the address space, it doesn't help prevent heap-stack collision.2389//2390static int anon_munmap(char * addr, size_t size) {2391return ::munmap(addr, size) == 0;2392}23932394char* os::pd_reserve_memory(size_t bytes, char* requested_addr,2395size_t alignment_hint MACOS_AARCH64_ONLY(, bool executable)) {2396return anon_mmap(requested_addr, bytes, (requested_addr != NULL) MACOS_AARCH64_ONLY(, executable));2397}23982399bool os::pd_release_memory(char* addr, size_t size) {2400return anon_munmap(addr, size);2401}24022403static bool bsd_mprotect(char* addr, size_t size, int prot) {2404// Bsd wants the mprotect address argument to be page aligned.2405char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());24062407// According to SUSv3, mprotect() should only be used with mappings2408// established by mmap(), and mmap() always maps whole pages. Unaligned2409// 'addr' likely indicates problem in the VM (e.g. trying to change2410// protection of malloc'ed or statically allocated memory). Check the2411// caller if you hit this assert.2412assert(addr == bottom, "sanity check");24132414size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());2415return ::mprotect(bottom, size, prot) == 0;2416}24172418// Set protections specified2419bool os::protect_memory(char* addr, size_t bytes, ProtType prot,2420bool is_committed) {2421unsigned int p = 0;2422switch (prot) {2423case MEM_PROT_NONE: p = PROT_NONE; break;2424case MEM_PROT_READ: p = PROT_READ; break;2425case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;2426case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;2427default:2428ShouldNotReachHere();2429}2430// is_committed is unused.2431return bsd_mprotect(addr, bytes, p);2432}24332434bool os::guard_memory(char* addr, size_t size) {2435return bsd_mprotect(addr, size, PROT_NONE);2436}24372438bool os::unguard_memory(char* addr, size_t size) {2439return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);2440}24412442bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {2443return false;2444}24452446// Large page support24472448static size_t _large_page_size = 0;24492450void os::large_page_init() {2451}245224532454char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {2455fatal("This code is not used or maintained.");24562457// "exec" is passed in but not used. Creating the shared image for2458// the code cache doesn't have an SHM_X executable permission to check.2459assert(UseLargePages && UseSHM, "only for SHM large pages");24602461key_t key = IPC_PRIVATE;2462char *addr;24632464bool warn_on_failure = UseLargePages &&2465(!FLAG_IS_DEFAULT(UseLargePages) ||2466!FLAG_IS_DEFAULT(LargePageSizeInBytes)2467);24682469// Create a large shared memory region to attach to based on size.2470// Currently, size is the total size of the heap2471int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);2472if (shmid == -1) {2473// Possible reasons for shmget failure:2474// 1. shmmax is too small for Java heap.2475// > check shmmax value: cat /proc/sys/kernel/shmmax2476// > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax2477// 2. not enough large page memory.2478// > check available large pages: cat /proc/meminfo2479// > increase amount of large pages:2480// echo new_value > /proc/sys/vm/nr_hugepages2481// Note 1: different Bsd may use different name for this property,2482// e.g. on Redhat AS-3 it is "hugetlb_pool".2483// Note 2: it's possible there's enough physical memory available but2484// they are so fragmented after a long run that they can't2485// coalesce into large pages. Try to reserve large pages when2486// the system is still "fresh".2487if (warn_on_failure) {2488warning("Failed to reserve shared memory (errno = %d).", errno);2489}2490return NULL;2491}24922493// attach to the region2494addr = (char*)shmat(shmid, req_addr, 0);2495int err = errno;24962497// Remove shmid. If shmat() is successful, the actual shared memory segment2498// will be deleted when it's detached by shmdt() or when the process2499// terminates. If shmat() is not successful this will remove the shared2500// segment immediately.2501shmctl(shmid, IPC_RMID, NULL);25022503if ((intptr_t)addr == -1) {2504if (warn_on_failure) {2505warning("Failed to attach shared memory (errno = %d).", err);2506}2507return NULL;2508}25092510// The memory is committed2511MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);25122513return addr;2514}25152516bool os::release_memory_special(char* base, size_t bytes) {2517if (MemTracker::tracking_level() > NMT_minimal) {2518Tracker tkr = MemTracker::get_virtual_memory_release_tracker();2519// detaching the SHM segment will also delete it, see reserve_memory_special()2520int rslt = shmdt(base);2521if (rslt == 0) {2522tkr.record((address)base, bytes);2523return true;2524} else {2525return false;2526}2527} else {2528return shmdt(base) == 0;2529}2530}25312532size_t os::large_page_size() {2533return _large_page_size;2534}25352536// HugeTLBFS allows application to commit large page memory on demand;2537// with SysV SHM the entire memory region must be allocated as shared2538// memory.2539bool os::can_commit_large_page_memory() {2540return UseHugeTLBFS;2541}25422543bool os::can_execute_large_page_memory() {2544return UseHugeTLBFS;2545}25462547// Reserve memory at an arbitrary address, only if that area is2548// available (and not reserved for something else).25492550char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr MACOS_AARCH64_ONLY(, bool exec)) {2551const int max_tries = 10;2552char* base[max_tries];2553size_t size[max_tries];2554const size_t gap = 0x000000;25552556// Assert only that the size is a multiple of the page size, since2557// that's all that mmap requires, and since that's all we really know2558// about at this low abstraction level. If we need higher alignment,2559// we can either pass an alignment to this method or verify alignment2560// in one of the methods further up the call chain. See bug 5044738.2561assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");25622563// Repeatedly allocate blocks until the block is allocated at the2564// right spot. Give up after max_tries. Note that reserve_memory() will2565// automatically update _highest_vm_reserved_address if the call is2566// successful. The variable tracks the highest memory address every reserved2567// by JVM. It is used to detect heap-stack collision if running with2568// fixed-stack BsdThreads. Because here we may attempt to reserve more2569// space than needed, it could confuse the collision detecting code. To2570// solve the problem, save current _highest_vm_reserved_address and2571// calculate the correct value before return.2572address old_highest = _highest_vm_reserved_address;25732574// Bsd mmap allows caller to pass an address as hint; give it a try first,2575// if kernel honors the hint then we can return immediately.2576char * addr = anon_mmap(requested_addr, bytes, false MACOS_AARCH64_ONLY(, exec));2577if (addr == requested_addr) {2578return requested_addr;2579}25802581if (addr != NULL) {2582// mmap() is successful but it fails to reserve at the requested address2583anon_munmap(addr, bytes);2584}25852586int i;2587for (i = 0; i < max_tries; ++i) {2588base[i] = reserve_memory(bytes);25892590if (base[i] != NULL) {2591// Is this the block we wanted?2592if (base[i] == requested_addr) {2593size[i] = bytes;2594break;2595}25962597// Does this overlap the block we wanted? Give back the overlapped2598// parts and try again.25992600size_t top_overlap = requested_addr + (bytes + gap) - base[i];2601if (top_overlap >= 0 && top_overlap < bytes) {2602unmap_memory(base[i], top_overlap);2603base[i] += top_overlap;2604size[i] = bytes - top_overlap;2605} else {2606size_t bottom_overlap = base[i] + bytes - requested_addr;2607if (bottom_overlap >= 0 && bottom_overlap < bytes) {2608unmap_memory(requested_addr, bottom_overlap);2609size[i] = bytes - bottom_overlap;2610} else {2611size[i] = bytes;2612}2613}2614}2615}26162617// Give back the unused reserved pieces.26182619for (int j = 0; j < i; ++j) {2620if (base[j] != NULL) {2621unmap_memory(base[j], size[j]);2622}2623}26242625if (i < max_tries) {2626_highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);2627return requested_addr;2628} else {2629_highest_vm_reserved_address = old_highest;2630return NULL;2631}2632}26332634size_t os::read(int fd, void *buf, unsigned int nBytes) {2635RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));2636}26372638size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {2639RESTARTABLE_RETURN_INT(::pread(fd, buf, nBytes, offset));2640}26412642// TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.2643// Solaris uses poll(), bsd uses park().2644// Poll() is likely a better choice, assuming that Thread.interrupt()2645// generates a SIGUSRx signal. Note that SIGUSR1 can interfere with2646// SIGSEGV, see 4355769.26472648int os::sleep(Thread* thread, jlong millis, bool interruptible) {2649assert(thread == Thread::current(), "thread consistency check");26502651ParkEvent * const slp = thread->_SleepEvent ;2652slp->reset() ;2653OrderAccess::fence() ;26542655if (interruptible) {2656jlong prevtime = javaTimeNanos();26572658for (;;) {2659if (os::is_interrupted(thread, true)) {2660return OS_INTRPT;2661}26622663jlong newtime = javaTimeNanos();26642665if (newtime - prevtime < 0) {2666// time moving backwards, should only happen if no monotonic clock2667// not a guarantee() because JVM should not abort on kernel/glibc bugs2668assert(!Bsd::supports_monotonic_clock(), "time moving backwards");2669} else {2670millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;2671}26722673if(millis <= 0) {2674return OS_OK;2675}26762677prevtime = newtime;26782679{2680assert(thread->is_Java_thread(), "sanity check");2681JavaThread *jt = (JavaThread *) thread;2682ThreadBlockInVM tbivm(jt);2683OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);26842685jt->set_suspend_equivalent();2686// cleared by handle_special_suspend_equivalent_condition() or2687// java_suspend_self() via check_and_wait_while_suspended()26882689slp->park(millis);26902691// were we externally suspended while we were waiting?2692jt->check_and_wait_while_suspended();2693}2694}2695} else {2696OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);2697jlong prevtime = javaTimeNanos();26982699for (;;) {2700// It'd be nice to avoid the back-to-back javaTimeNanos() calls on2701// the 1st iteration ...2702jlong newtime = javaTimeNanos();27032704if (newtime - prevtime < 0) {2705// time moving backwards, should only happen if no monotonic clock2706// not a guarantee() because JVM should not abort on kernel/glibc bugs2707assert(!Bsd::supports_monotonic_clock(), "time moving backwards");2708} else {2709millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;2710}27112712if(millis <= 0) break ;27132714prevtime = newtime;2715slp->park(millis);2716}2717return OS_OK ;2718}2719}27202721void os::naked_short_sleep(jlong ms) {2722struct timespec req;27232724assert(ms < 1000, "Un-interruptable sleep, short time use only");2725req.tv_sec = 0;2726if (ms > 0) {2727req.tv_nsec = (ms % 1000) * 1000000;2728}2729else {2730req.tv_nsec = 1;2731}27322733nanosleep(&req, NULL);27342735return;2736}27372738// Sleep forever; naked call to OS-specific sleep; use with CAUTION2739void os::infinite_sleep() {2740while (true) { // sleep forever ...2741::sleep(100); // ... 100 seconds at a time2742}2743}27442745// Used to convert frequent JVM_Yield() to nops2746bool os::dont_yield() {2747return DontYieldALot;2748}27492750void os::yield() {2751sched_yield();2752}27532754os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}27552756void os::yield_all(int attempts) {2757// Yields to all threads, including threads with lower priorities2758// Threads on Bsd are all with same priority. The Solaris style2759// os::yield_all() with nanosleep(1ms) is not necessary.2760sched_yield();2761}27622763// Called from the tight loops to possibly influence time-sharing heuristics2764void os::loop_breaker(int attempts) {2765os::yield_all(attempts);2766}27672768////////////////////////////////////////////////////////////////////////////////2769// thread priority support27702771// Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER2772// only supports dynamic priority, static priority must be zero. For real-time2773// applications, Bsd supports SCHED_RR which allows static priority (1-99).2774// However, for large multi-threaded applications, SCHED_RR is not only slower2775// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out2776// of 5 runs - Sep 2005).2777//2778// The following code actually changes the niceness of kernel-thread/LWP. It2779// has an assumption that setpriority() only modifies one kernel-thread/LWP,2780// not the entire user process, and user level threads are 1:1 mapped to kernel2781// threads. It has always been the case, but could change in the future. For2782// this reason, the code should not be used as default (ThreadPriorityPolicy=0).2783// It is only used when ThreadPriorityPolicy=1 and requires root privilege.27842785#if !defined(__APPLE__)2786int os::java_to_os_priority[CriticalPriority + 1] = {278719, // 0 Entry should never be used278827890, // 1 MinPriority27903, // 227916, // 32792279310, // 4279415, // 5 NormPriority279518, // 62796279721, // 7279825, // 8279928, // 9 NearMaxPriority2800280131, // 10 MaxPriority2802280331 // 11 CriticalPriority2804};2805#else2806/* Using Mach high-level priority assignments */2807int os::java_to_os_priority[CriticalPriority + 1] = {28080, // 0 Entry should never be used (MINPRI_USER)2809281027, // 1 MinPriority281128, // 2281229, // 32813281430, // 4281531, // 5 NormPriority (BASEPRI_DEFAULT)281632, // 62817281833, // 7281934, // 8282035, // 9 NearMaxPriority2821282236, // 10 MaxPriority2823282436 // 11 CriticalPriority2825};2826#endif28272828static int prio_init() {2829if (ThreadPriorityPolicy == 1) {2830// Only root can raise thread priority. Don't allow ThreadPriorityPolicy=12831// if effective uid is not root. Perhaps, a more elegant way of doing2832// this is to test CAP_SYS_NICE capability, but that will require libcap.so2833if (geteuid() != 0) {2834if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {2835warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");2836}2837ThreadPriorityPolicy = 0;2838}2839}2840if (UseCriticalJavaThreadPriority) {2841os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];2842}2843return 0;2844}28452846OSReturn os::set_native_priority(Thread* thread, int newpri) {2847if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;28482849#ifdef __OpenBSD__2850// OpenBSD pthread_setprio starves low priority threads2851return OS_OK;2852#elif defined(__FreeBSD__)2853int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);2854#elif defined(__APPLE__) || defined(__NetBSD__)2855struct sched_param sp;2856int policy;2857pthread_t self = pthread_self();28582859if (pthread_getschedparam(self, &policy, &sp) != 0)2860return OS_ERR;28612862sp.sched_priority = newpri;2863if (pthread_setschedparam(self, policy, &sp) != 0)2864return OS_ERR;28652866return OS_OK;2867#else2868int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);2869return (ret == 0) ? OS_OK : OS_ERR;2870#endif2871}28722873OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {2874if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {2875*priority_ptr = java_to_os_priority[NormPriority];2876return OS_OK;2877}28782879errno = 0;2880#if defined(__OpenBSD__) || defined(__FreeBSD__)2881*priority_ptr = pthread_getprio(thread->osthread()->pthread_id());2882#elif defined(__APPLE__) || defined(__NetBSD__)2883int policy;2884struct sched_param sp;28852886pthread_getschedparam(pthread_self(), &policy, &sp);2887*priority_ptr = sp.sched_priority;2888#else2889*priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());2890#endif2891return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);2892}28932894// Hint to the underlying OS that a task switch would not be good.2895// Void return because it's a hint and can fail.2896void os::hint_no_preempt() {}28972898////////////////////////////////////////////////////////////////////////////////2899// suspend/resume support29002901// the low-level signal-based suspend/resume support is a remnant from the2902// old VM-suspension that used to be for java-suspension, safepoints etc,2903// within hotspot. Now there is a single use-case for this:2904// - calling get_thread_pc() on the VMThread by the flat-profiler task2905// that runs in the watcher thread.2906// The remaining code is greatly simplified from the more general suspension2907// code that used to be used.2908//2909// The protocol is quite simple:2910// - suspend:2911// - sends a signal to the target thread2912// - polls the suspend state of the osthread using a yield loop2913// - target thread signal handler (SR_handler) sets suspend state2914// and blocks in sigsuspend until continued2915// - resume:2916// - sets target osthread state to continue2917// - sends signal to end the sigsuspend loop in the SR_handler2918//2919// Note that the SR_lock plays no role in this suspend/resume protocol.2920//29212922static void resume_clear_context(OSThread *osthread) {2923osthread->set_ucontext(NULL);2924osthread->set_siginfo(NULL);2925}29262927static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {2928osthread->set_ucontext(context);2929osthread->set_siginfo(siginfo);2930}29312932//2933// Handler function invoked when a thread's execution is suspended or2934// resumed. We have to be careful that only async-safe functions are2935// called here (Note: most pthread functions are not async safe and2936// should be avoided.)2937//2938// Note: sigwait() is a more natural fit than sigsuspend() from an2939// interface point of view, but sigwait() prevents the signal hander2940// from being run. libpthread would get very confused by not having2941// its signal handlers run and prevents sigwait()'s use with the2942// mutex granting granting signal.2943//2944// Currently only ever called on the VMThread or JavaThread2945//2946static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {2947// Save and restore errno to avoid confusing native code with EINTR2948// after sigsuspend.2949int old_errno = errno;29502951Thread* thread = Thread::current();2952OSThread* osthread = thread->osthread();2953assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");29542955os::SuspendResume::State current = osthread->sr.state();2956if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {2957suspend_save_context(osthread, siginfo, context);29582959// attempt to switch the state, we assume we had a SUSPEND_REQUEST2960os::SuspendResume::State state = osthread->sr.suspended();2961if (state == os::SuspendResume::SR_SUSPENDED) {2962sigset_t suspend_set; // signals for sigsuspend()29632964// get current set of blocked signals and unblock resume signal2965pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);2966sigdelset(&suspend_set, SR_signum);29672968sr_semaphore.signal();2969// wait here until we are resumed2970while (1) {2971sigsuspend(&suspend_set);29722973os::SuspendResume::State result = osthread->sr.running();2974if (result == os::SuspendResume::SR_RUNNING) {2975sr_semaphore.signal();2976break;2977} else if (result != os::SuspendResume::SR_SUSPENDED) {2978ShouldNotReachHere();2979}2980}29812982} else if (state == os::SuspendResume::SR_RUNNING) {2983// request was cancelled, continue2984} else {2985ShouldNotReachHere();2986}29872988resume_clear_context(osthread);2989} else if (current == os::SuspendResume::SR_RUNNING) {2990// request was cancelled, continue2991} else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {2992// ignore2993} else {2994// ignore2995}29962997errno = old_errno;2998}299930003001static int SR_initialize() {3002struct sigaction act;3003char *s;3004/* Get signal number to use for suspend/resume */3005if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {3006int sig = ::strtol(s, 0, 10);3007if (sig > 0 || sig < NSIG) {3008SR_signum = sig;3009}3010}30113012assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,3013"SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");30143015sigemptyset(&SR_sigset);3016sigaddset(&SR_sigset, SR_signum);30173018/* Set up signal handler for suspend/resume */3019act.sa_flags = SA_RESTART|SA_SIGINFO;3020act.sa_handler = (void (*)(int)) SR_handler;30213022// SR_signum is blocked by default.3023// 4528190 - We also need to block pthread restart signal (32 on all3024// supported Bsd platforms). Note that BsdThreads need to block3025// this signal for all threads to work properly. So we don't have3026// to use hard-coded signal number when setting up the mask.3027pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);30283029if (sigaction(SR_signum, &act, 0) == -1) {3030return -1;3031}30323033// Save signal flag3034os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);3035return 0;3036}30373038static int sr_notify(OSThread* osthread) {3039int status = pthread_kill(osthread->pthread_id(), SR_signum);3040assert_status(status == 0, status, "pthread_kill");3041return status;3042}30433044// "Randomly" selected value for how long we want to spin3045// before bailing out on suspending a thread, also how often3046// we send a signal to a thread we want to resume3047static const int RANDOMLY_LARGE_INTEGER = 1000000;3048static const int RANDOMLY_LARGE_INTEGER2 = 100;30493050// returns true on success and false on error - really an error is fatal3051// but this seems the normal response to library errors3052static bool do_suspend(OSThread* osthread) {3053assert(osthread->sr.is_running(), "thread should be running");3054assert(!sr_semaphore.trywait(), "semaphore has invalid state");30553056// mark as suspended and send signal3057if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {3058// failed to switch, state wasn't running?3059ShouldNotReachHere();3060return false;3061}30623063if (sr_notify(osthread) != 0) {3064ShouldNotReachHere();3065}30663067// managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED3068while (true) {3069if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {3070break;3071} else {3072// timeout3073os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();3074if (cancelled == os::SuspendResume::SR_RUNNING) {3075return false;3076} else if (cancelled == os::SuspendResume::SR_SUSPENDED) {3077// make sure that we consume the signal on the semaphore as well3078sr_semaphore.wait();3079break;3080} else {3081ShouldNotReachHere();3082return false;3083}3084}3085}30863087guarantee(osthread->sr.is_suspended(), "Must be suspended");3088return true;3089}30903091static void do_resume(OSThread* osthread) {3092assert(osthread->sr.is_suspended(), "thread should be suspended");3093assert(!sr_semaphore.trywait(), "invalid semaphore state");30943095if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {3096// failed to switch to WAKEUP_REQUEST3097ShouldNotReachHere();3098return;3099}31003101while (true) {3102if (sr_notify(osthread) == 0) {3103if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {3104if (osthread->sr.is_running()) {3105return;3106}3107}3108} else {3109ShouldNotReachHere();3110}3111}31123113guarantee(osthread->sr.is_running(), "Must be running!");3114}31153116////////////////////////////////////////////////////////////////////////////////3117// interrupt support31183119void os::interrupt(Thread* thread) {3120assert(Thread::current() == thread || Threads_lock->owned_by_self(),3121"possibility of dangling Thread pointer");31223123OSThread* osthread = thread->osthread();31243125if (!osthread->interrupted()) {3126osthread->set_interrupted(true);3127// More than one thread can get here with the same value of osthread,3128// resulting in multiple notifications. We do, however, want the store3129// to interrupted() to be visible to other threads before we execute unpark().3130OrderAccess::fence();3131ParkEvent * const slp = thread->_SleepEvent ;3132if (slp != NULL) slp->unpark() ;3133}31343135// For JSR166. Unpark even if interrupt status already was set3136if (thread->is_Java_thread())3137((JavaThread*)thread)->parker()->unpark();31383139ParkEvent * ev = thread->_ParkEvent ;3140if (ev != NULL) ev->unpark() ;31413142}31433144bool os::is_interrupted(Thread* thread, bool clear_interrupted) {3145assert(Thread::current() == thread || Threads_lock->owned_by_self(),3146"possibility of dangling Thread pointer");31473148OSThread* osthread = thread->osthread();31493150bool interrupted = osthread->interrupted();31513152if (interrupted && clear_interrupted) {3153osthread->set_interrupted(false);3154// consider thread->_SleepEvent->reset() ... optional optimization3155}31563157return interrupted;3158}31593160///////////////////////////////////////////////////////////////////////////////////3161// signal handling (except suspend/resume)31623163// This routine may be used by user applications as a "hook" to catch signals.3164// The user-defined signal handler must pass unrecognized signals to this3165// routine, and if it returns true (non-zero), then the signal handler must3166// return immediately. If the flag "abort_if_unrecognized" is true, then this3167// routine will never retun false (zero), but instead will execute a VM panic3168// routine kill the process.3169//3170// If this routine returns false, it is OK to call it again. This allows3171// the user-defined signal handler to perform checks either before or after3172// the VM performs its own checks. Naturally, the user code would be making3173// a serious error if it tried to handle an exception (such as a null check3174// or breakpoint) that the VM was generating for its own correct operation.3175//3176// This routine may recognize any of the following kinds of signals:3177// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.3178// It should be consulted by handlers for any of those signals.3179//3180// The caller of this routine must pass in the three arguments supplied3181// to the function referred to in the "sa_sigaction" (not the "sa_handler")3182// field of the structure passed to sigaction(). This routine assumes that3183// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.3184//3185// Note that the VM will print warnings if it detects conflicting signal3186// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".3187//3188extern "C" JNIEXPORT int3189JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,3190void* ucontext, int abort_if_unrecognized);31913192void signalHandler(int sig, siginfo_t* info, void* uc) {3193assert(info != NULL && uc != NULL, "it must be old kernel");3194int orig_errno = errno; // Preserve errno value over signal handler.3195JVM_handle_bsd_signal(sig, info, uc, true);3196errno = orig_errno;3197}319831993200// This boolean allows users to forward their own non-matching signals3201// to JVM_handle_bsd_signal, harmlessly.3202bool os::Bsd::signal_handlers_are_installed = false;32033204// For signal-chaining3205struct sigaction os::Bsd::sigact[MAXSIGNUM];3206unsigned int os::Bsd::sigs = 0;3207bool os::Bsd::libjsig_is_loaded = false;3208typedef struct sigaction *(*get_signal_t)(int);3209get_signal_t os::Bsd::get_signal_action = NULL;32103211struct sigaction* os::Bsd::get_chained_signal_action(int sig) {3212struct sigaction *actp = NULL;32133214if (libjsig_is_loaded) {3215// Retrieve the old signal handler from libjsig3216actp = (*get_signal_action)(sig);3217}3218if (actp == NULL) {3219// Retrieve the preinstalled signal handler from jvm3220actp = get_preinstalled_handler(sig);3221}32223223return actp;3224}32253226static bool call_chained_handler(struct sigaction *actp, int sig,3227siginfo_t *siginfo, void *context) {3228// Call the old signal handler3229if (actp->sa_handler == SIG_DFL) {3230// It's more reasonable to let jvm treat it as an unexpected exception3231// instead of taking the default action.3232return false;3233} else if (actp->sa_handler != SIG_IGN) {3234if ((actp->sa_flags & SA_NODEFER) == 0) {3235// automaticlly block the signal3236sigaddset(&(actp->sa_mask), sig);3237}32383239sa_handler_t hand;3240sa_sigaction_t sa;3241bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;3242// retrieve the chained handler3243if (siginfo_flag_set) {3244sa = actp->sa_sigaction;3245} else {3246hand = actp->sa_handler;3247}32483249if ((actp->sa_flags & SA_RESETHAND) != 0) {3250actp->sa_handler = SIG_DFL;3251}32523253// try to honor the signal mask3254sigset_t oset;3255pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);32563257// call into the chained handler3258if (siginfo_flag_set) {3259(*sa)(sig, siginfo, context);3260} else {3261(*hand)(sig);3262}32633264// restore the signal mask3265pthread_sigmask(SIG_SETMASK, &oset, 0);3266}3267// Tell jvm's signal handler the signal is taken care of.3268return true;3269}32703271bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {3272bool chained = false;3273// signal-chaining3274if (UseSignalChaining) {3275struct sigaction *actp = get_chained_signal_action(sig);3276if (actp != NULL) {3277chained = call_chained_handler(actp, sig, siginfo, context);3278}3279}3280return chained;3281}32823283struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {3284if ((( (unsigned int)1 << sig ) & sigs) != 0) {3285return &sigact[sig];3286}3287return NULL;3288}32893290void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {3291assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3292sigact[sig] = oldAct;3293sigs |= (unsigned int)1 << sig;3294}32953296// for diagnostic3297int os::Bsd::sigflags[MAXSIGNUM];32983299int os::Bsd::get_our_sigflags(int sig) {3300assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3301return sigflags[sig];3302}33033304void os::Bsd::set_our_sigflags(int sig, int flags) {3305assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3306sigflags[sig] = flags;3307}33083309void os::Bsd::set_signal_handler(int sig, bool set_installed) {3310// Check for overwrite.3311struct sigaction oldAct;3312sigaction(sig, (struct sigaction*)NULL, &oldAct);33133314void* oldhand = oldAct.sa_sigaction3315? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)3316: CAST_FROM_FN_PTR(void*, oldAct.sa_handler);3317if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&3318oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&3319oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {3320if (AllowUserSignalHandlers || !set_installed) {3321// Do not overwrite; user takes responsibility to forward to us.3322return;3323} else if (UseSignalChaining) {3324// save the old handler in jvm3325save_preinstalled_handler(sig, oldAct);3326// libjsig also interposes the sigaction() call below and saves the3327// old sigaction on it own.3328} else {3329fatal(err_msg("Encountered unexpected pre-existing sigaction handler "3330"%#lx for signal %d.", (long)oldhand, sig));3331}3332}33333334struct sigaction sigAct;3335sigfillset(&(sigAct.sa_mask));3336sigAct.sa_handler = SIG_DFL;3337if (!set_installed) {3338sigAct.sa_flags = SA_SIGINFO|SA_RESTART;3339} else {3340sigAct.sa_sigaction = signalHandler;3341sigAct.sa_flags = SA_SIGINFO|SA_RESTART;3342}3343#ifdef __APPLE__3344// Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV3345// (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"3346// if the signal handler declares it will handle it on alternate stack.3347// Notice we only declare we will handle it on alt stack, but we are not3348// actually going to use real alt stack - this is just a workaround.3349// Please see ux_exception.c, method catch_mach_exception_raise for details3350// link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c3351if (sig == SIGSEGV) {3352sigAct.sa_flags |= SA_ONSTACK;3353}3354#endif33553356// Save flags, which are set by ours3357assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");3358sigflags[sig] = sigAct.sa_flags;33593360int ret = sigaction(sig, &sigAct, &oldAct);3361assert(ret == 0, "check");33623363void* oldhand2 = oldAct.sa_sigaction3364? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)3365: CAST_FROM_FN_PTR(void*, oldAct.sa_handler);3366assert(oldhand2 == oldhand, "no concurrent signal handler installation");3367}33683369// install signal handlers for signals that HotSpot needs to3370// handle in order to support Java-level exception handling.33713372void os::Bsd::install_signal_handlers() {3373if (!signal_handlers_are_installed) {3374signal_handlers_are_installed = true;33753376// signal-chaining3377typedef void (*signal_setting_t)();3378signal_setting_t begin_signal_setting = NULL;3379signal_setting_t end_signal_setting = NULL;3380begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,3381dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));3382if (begin_signal_setting != NULL) {3383end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,3384dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));3385get_signal_action = CAST_TO_FN_PTR(get_signal_t,3386dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));3387libjsig_is_loaded = true;3388assert(UseSignalChaining, "should enable signal-chaining");3389}3390if (libjsig_is_loaded) {3391// Tell libjsig jvm is setting signal handlers3392(*begin_signal_setting)();3393}33943395set_signal_handler(SIGSEGV, true);3396set_signal_handler(SIGPIPE, true);3397set_signal_handler(SIGBUS, true);3398set_signal_handler(SIGILL, true);3399set_signal_handler(SIGFPE, true);3400set_signal_handler(SIGXFSZ, true);34013402#if defined(__APPLE__)3403// In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including3404// signals caught and handled by the JVM. To work around this, we reset the mach task3405// signal handler that's placed on our process by CrashReporter. This disables3406// CrashReporter-based reporting.3407//3408// This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes3409// on caught fatal signals.3410//3411// Additionally, gdb installs both standard BSD signal handlers, and mach exception3412// handlers. By replacing the existing task exception handler, we disable gdb's mach3413// exception handling, while leaving the standard BSD signal handlers functional.3414kern_return_t kr;3415kr = task_set_exception_ports(mach_task_self(),3416EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,3417MACH_PORT_NULL,3418EXCEPTION_STATE_IDENTITY,3419MACHINE_THREAD_STATE);34203421assert(kr == KERN_SUCCESS, "could not set mach task signal handler");3422#endif34233424if (libjsig_is_loaded) {3425// Tell libjsig jvm finishes setting signal handlers3426(*end_signal_setting)();3427}34283429// We don't activate signal checker if libjsig is in place, we trust ourselves3430// and if UserSignalHandler is installed all bets are off3431if (CheckJNICalls) {3432if (libjsig_is_loaded) {3433if (PrintJNIResolving) {3434tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");3435}3436check_signals = false;3437}3438if (AllowUserSignalHandlers) {3439if (PrintJNIResolving) {3440tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");3441}3442check_signals = false;3443}3444}3445}3446}344734483449/////3450// glibc on Bsd platform uses non-documented flag3451// to indicate, that some special sort of signal3452// trampoline is used.3453// We will never set this flag, and we should3454// ignore this flag in our diagnostic3455#ifdef SIGNIFICANT_SIGNAL_MASK3456#undef SIGNIFICANT_SIGNAL_MASK3457#endif3458#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)34593460static const char* get_signal_handler_name(address handler,3461char* buf, int buflen) {3462int offset;3463bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);3464if (found) {3465// skip directory names3466const char *p1, *p2;3467p1 = buf;3468size_t len = strlen(os::file_separator());3469while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;3470jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);3471} else {3472jio_snprintf(buf, buflen, PTR_FORMAT, handler);3473}3474return buf;3475}34763477static void print_signal_handler(outputStream* st, int sig,3478char* buf, size_t buflen) {3479struct sigaction sa;34803481sigaction(sig, NULL, &sa);34823483// See comment for SIGNIFICANT_SIGNAL_MASK define3484sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;34853486st->print("%s: ", os::exception_name(sig, buf, buflen));34873488address handler = (sa.sa_flags & SA_SIGINFO)3489? CAST_FROM_FN_PTR(address, sa.sa_sigaction)3490: CAST_FROM_FN_PTR(address, sa.sa_handler);34913492if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {3493st->print("SIG_DFL");3494} else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {3495st->print("SIG_IGN");3496} else {3497st->print("[%s]", get_signal_handler_name(handler, buf, buflen));3498}34993500st->print(", sa_mask[0]=");3501os::Posix::print_signal_set_short(st, &sa.sa_mask);35023503address rh = VMError::get_resetted_sighandler(sig);3504// May be, handler was resetted by VMError?3505if(rh != NULL) {3506handler = rh;3507sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;3508}35093510st->print(", sa_flags=");3511os::Posix::print_sa_flags(st, sa.sa_flags);35123513// Check: is it our handler?3514if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||3515handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {3516// It is our signal handler3517// check for flags, reset system-used one!3518if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {3519st->print(3520", flags was changed from " PTR32_FORMAT ", consider using jsig library",3521os::Bsd::get_our_sigflags(sig));3522}3523}3524st->cr();3525}352635273528#define DO_SIGNAL_CHECK(sig) \3529if (!sigismember(&check_signal_done, sig)) \3530os::Bsd::check_signal_handler(sig)35313532// This method is a periodic task to check for misbehaving JNI applications3533// under CheckJNI, we can add any periodic checks here35343535void os::run_periodic_checks() {35363537if (check_signals == false) return;35383539// SEGV and BUS if overridden could potentially prevent3540// generation of hs*.log in the event of a crash, debugging3541// such a case can be very challenging, so we absolutely3542// check the following for a good measure:3543DO_SIGNAL_CHECK(SIGSEGV);3544DO_SIGNAL_CHECK(SIGILL);3545DO_SIGNAL_CHECK(SIGFPE);3546DO_SIGNAL_CHECK(SIGBUS);3547DO_SIGNAL_CHECK(SIGPIPE);3548DO_SIGNAL_CHECK(SIGXFSZ);354935503551// ReduceSignalUsage allows the user to override these handlers3552// see comments at the very top and jvm_solaris.h3553if (!ReduceSignalUsage) {3554DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);3555DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);3556DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);3557DO_SIGNAL_CHECK(BREAK_SIGNAL);3558}35593560DO_SIGNAL_CHECK(SR_signum);3561DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);3562}35633564typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);35653566static os_sigaction_t os_sigaction = NULL;35673568void os::Bsd::check_signal_handler(int sig) {3569char buf[O_BUFLEN];3570address jvmHandler = NULL;357135723573struct sigaction act;3574if (os_sigaction == NULL) {3575// only trust the default sigaction, in case it has been interposed3576os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");3577if (os_sigaction == NULL) return;3578}35793580os_sigaction(sig, (struct sigaction*)NULL, &act);358135823583act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;35843585address thisHandler = (act.sa_flags & SA_SIGINFO)3586? CAST_FROM_FN_PTR(address, act.sa_sigaction)3587: CAST_FROM_FN_PTR(address, act.sa_handler) ;358835893590switch(sig) {3591case SIGSEGV:3592case SIGBUS:3593case SIGFPE:3594case SIGPIPE:3595case SIGILL:3596case SIGXFSZ:3597jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);3598break;35993600case SHUTDOWN1_SIGNAL:3601case SHUTDOWN2_SIGNAL:3602case SHUTDOWN3_SIGNAL:3603case BREAK_SIGNAL:3604jvmHandler = (address)user_handler();3605break;36063607case INTERRUPT_SIGNAL:3608jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);3609break;36103611default:3612if (sig == SR_signum) {3613jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);3614} else {3615return;3616}3617break;3618}36193620if (thisHandler != jvmHandler) {3621tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));3622tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));3623tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));3624// No need to check this sig any longer3625sigaddset(&check_signal_done, sig);3626// Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN3627if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {3628tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",3629exception_name(sig, buf, O_BUFLEN));3630}3631} else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {3632tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));3633tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));3634tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);3635// No need to check this sig any longer3636sigaddset(&check_signal_done, sig);3637}36383639// Dump all the signal3640if (sigismember(&check_signal_done, sig)) {3641print_signal_handlers(tty, buf, O_BUFLEN);3642}3643}36443645extern void report_error(char* file_name, int line_no, char* title, char* format, ...);36463647extern bool signal_name(int signo, char* buf, size_t len);36483649const char* os::exception_name(int exception_code, char* buf, size_t size) {3650if (0 < exception_code && exception_code <= SIGRTMAX) {3651// signal3652if (!signal_name(exception_code, buf, size)) {3653jio_snprintf(buf, size, "SIG%d", exception_code);3654}3655return buf;3656} else {3657return NULL;3658}3659}36603661// this is called _before_ the most of global arguments have been parsed3662void os::init(void) {3663char dummy; /* used to get a guess on initial stack address */3664// first_hrtime = gethrtime();36653666// With BsdThreads the JavaMain thread pid (primordial thread)3667// is different than the pid of the java launcher thread.3668// So, on Bsd, the launcher thread pid is passed to the VM3669// via the sun.java.launcher.pid property.3670// Use this property instead of getpid() if it was correctly passed.3671// See bug 6351349.3672pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();36733674_initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();36753676clock_tics_per_sec = CLK_TCK;36773678init_random(1234567);36793680ThreadCritical::initialize();36813682Bsd::set_page_size(getpagesize());3683if (Bsd::page_size() == -1) {3684fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",3685strerror(errno)));3686}3687init_page_sizes((size_t) Bsd::page_size());36883689Bsd::initialize_system_info();36903691// _main_thread points to the thread that created/loaded the JVM.3692Bsd::_main_thread = pthread_self();36933694Bsd::clock_init();3695initial_time_count = javaTimeNanos();36963697#ifdef __APPLE__3698#ifndef AARCH643699// XXXDARWIN3700// Work around the unaligned VM callbacks in hotspot's3701// sharedRuntime. The callbacks don't use SSE2 instructions, and work on3702// Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces3703// alignment when doing symbol lookup. To work around this, we force early3704// binding of all symbols now, thus binding when alignment is known-good.3705_dyld_bind_fully_image_containing_address((const void *) &os::init);3706#endif3707#endif3708}37093710// To install functions for atexit system call3711extern "C" {3712static void perfMemory_exit_helper() {3713perfMemory_exit();3714}3715}37163717// this is called _after_ the global arguments have been parsed3718jint os::init_2(void)3719{3720// Allocate a single page and mark it as readable for safepoint polling3721address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);3722guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );37233724os::set_polling_page( polling_page );37253726#ifndef PRODUCT3727if(Verbose && PrintMiscellaneous)3728tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);3729#endif37303731if (!UseMembar) {3732address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);3733guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");3734os::set_memory_serialize_page( mem_serialize_page );37353736#ifndef PRODUCT3737if(Verbose && PrintMiscellaneous)3738tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);3739#endif3740}37413742// initialize suspend/resume support - must do this before signal_sets_init()3743if (SR_initialize() != 0) {3744perror("SR_initialize failed");3745return JNI_ERR;3746}37473748Bsd::signal_sets_init();3749Bsd::install_signal_handlers();37503751// Check minimum allowable stack size for thread creation and to initialize3752// the java system classes, including StackOverflowError - depends on page3753// size. Add a page for compiler2 recursion in main thread.3754// Add in 2*BytesPerWord times page size to account for VM stack during3755// class initialization depending on 32 or 64 bit VM.3756os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,3757(size_t)(StackYellowPages+StackRedPages+StackShadowPages+37582*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());37593760size_t threadStackSizeInBytes = ThreadStackSize * K;3761if (threadStackSizeInBytes != 0 &&3762threadStackSizeInBytes < os::Bsd::min_stack_allowed) {3763tty->print_cr("\nThe stack size specified is too small, "3764"Specify at least %dk",3765os::Bsd::min_stack_allowed/ K);3766return JNI_ERR;3767}37683769// Make the stack size a multiple of the page size so that3770// the yellow/red zones can be guarded.3771JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,3772vm_page_size()));37733774if (MaxFDLimit) {3775// set the number of file descriptors to max. print out error3776// if getrlimit/setrlimit fails but continue regardless.3777struct rlimit nbr_files;3778int status = getrlimit(RLIMIT_NOFILE, &nbr_files);3779if (status != 0) {3780if (PrintMiscellaneous && (Verbose || WizardMode))3781perror("os::init_2 getrlimit failed");3782} else {3783nbr_files.rlim_cur = nbr_files.rlim_max;37843785#ifdef __APPLE__3786// Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if3787// you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must3788// be used instead3789nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);3790#endif37913792status = setrlimit(RLIMIT_NOFILE, &nbr_files);3793if (status != 0) {3794if (PrintMiscellaneous && (Verbose || WizardMode))3795perror("os::init_2 setrlimit failed");3796}3797}3798}37993800// at-exit methods are called in the reverse order of their registration.3801// atexit functions are called on return from main or as a result of a3802// call to exit(3C). There can be only 32 of these functions registered3803// and atexit() does not set errno.38043805if (PerfAllowAtExitRegistration) {3806// only register atexit functions if PerfAllowAtExitRegistration is set.3807// atexit functions can be delayed until process exit time, which3808// can be problematic for embedded VM situations. Embedded VMs should3809// call DestroyJavaVM() to assure that VM resources are released.38103811// note: perfMemory_exit_helper atexit function may be removed in3812// the future if the appropriate cleanup code can be added to the3813// VM_Exit VMOperation's doit method.3814if (atexit(perfMemory_exit_helper) != 0) {3815warning("os::init2 atexit(perfMemory_exit_helper) failed");3816}3817}38183819// initialize thread priority policy3820prio_init();38213822#ifdef __APPLE__3823// dynamically link to objective c gc registration3824void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);3825if (handleLibObjc != NULL) {3826objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);3827}3828#endif38293830return JNI_OK;3831}38323833// Mark the polling page as unreadable3834void os::make_polling_page_unreadable(void) {3835if( !guard_memory((char*)_polling_page, Bsd::page_size()) )3836fatal("Could not disable polling page");3837};38383839// Mark the polling page as readable3840void os::make_polling_page_readable(void) {3841if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {3842fatal("Could not enable polling page");3843}3844};38453846int os::active_processor_count() {3847// User has overridden the number of active processors3848if (ActiveProcessorCount > 0) {3849if (PrintActiveCpus) {3850tty->print_cr("active_processor_count: "3851"active processor count set by user : %d",3852ActiveProcessorCount);3853}3854return ActiveProcessorCount;3855}38563857return _processor_count;3858}38593860void os::set_native_thread_name(const char *name) {3861#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_53862// This is only supported in Snow Leopard and beyond3863if (name != NULL) {3864// Add a "Java: " prefix to the name3865char buf[MAXTHREADNAMESIZE];3866snprintf(buf, sizeof(buf), "Java: %s", name);3867pthread_setname_np(buf);3868}3869#endif3870}38713872bool os::distribute_processes(uint length, uint* distribution) {3873// Not yet implemented.3874return false;3875}38763877bool os::bind_to_processor(uint processor_id) {3878// Not yet implemented.3879return false;3880}38813882void os::SuspendedThreadTask::internal_do_task() {3883if (do_suspend(_thread->osthread())) {3884SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());3885do_task(context);3886do_resume(_thread->osthread());3887}3888}38893890///3891class PcFetcher : public os::SuspendedThreadTask {3892public:3893PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}3894ExtendedPC result();3895protected:3896void do_task(const os::SuspendedThreadTaskContext& context);3897private:3898ExtendedPC _epc;3899};39003901ExtendedPC PcFetcher::result() {3902guarantee(is_done(), "task is not done yet.");3903return _epc;3904}39053906void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {3907Thread* thread = context.thread();3908OSThread* osthread = thread->osthread();3909if (osthread->ucontext() != NULL) {3910_epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());3911} else {3912// NULL context is unexpected, double-check this is the VMThread3913guarantee(thread->is_VM_thread(), "can only be called for VMThread");3914}3915}39163917// Suspends the target using the signal mechanism and then grabs the PC before3918// resuming the target. Used by the flat-profiler only3919ExtendedPC os::get_thread_pc(Thread* thread) {3920// Make sure that it is called by the watcher for the VMThread3921assert(Thread::current()->is_Watcher_thread(), "Must be watcher");3922assert(thread->is_VM_thread(), "Can only be called for VMThread");39233924PcFetcher fetcher(thread);3925fetcher.run();3926return fetcher.result();3927}39283929int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)3930{3931return pthread_cond_timedwait(_cond, _mutex, _abstime);3932}39333934////////////////////////////////////////////////////////////////////////////////3935// debug support39363937bool os::find(address addr, outputStream* st) {3938Dl_info dlinfo;3939memset(&dlinfo, 0, sizeof(dlinfo));3940if (dladdr(addr, &dlinfo) != 0) {3941st->print(PTR_FORMAT ": ", addr);3942if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {3943st->print("%s+%#x", dlinfo.dli_sname,3944addr - (intptr_t)dlinfo.dli_saddr);3945} else if (dlinfo.dli_fbase != NULL) {3946st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);3947} else {3948st->print("<absolute address>");3949}3950if (dlinfo.dli_fname != NULL) {3951st->print(" in %s", dlinfo.dli_fname);3952}3953if (dlinfo.dli_fbase != NULL) {3954st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);3955}3956st->cr();39573958if (Verbose) {3959// decode some bytes around the PC3960address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());3961address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());3962address lowest = (address) dlinfo.dli_sname;3963if (!lowest) lowest = (address) dlinfo.dli_fbase;3964if (begin < lowest) begin = lowest;3965Dl_info dlinfo2;3966if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr3967&& end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)3968end = (address) dlinfo2.dli_saddr;3969Disassembler::decode(begin, end, st);3970}3971return true;3972}3973return false;3974}39753976////////////////////////////////////////////////////////////////////////////////3977// misc39783979// This does not do anything on Bsd. This is basically a hook for being3980// able to use structured exception handling (thread-local exception filters)3981// on, e.g., Win32.3982void3983os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,3984JavaCallArguments* args, Thread* thread) {3985f(value, method, args, thread);3986}39873988void os::print_statistics() {3989}39903991int os::message_box(const char* title, const char* message) {3992int i;3993fdStream err(defaultStream::error_fd());3994for (i = 0; i < 78; i++) err.print_raw("=");3995err.cr();3996err.print_raw_cr(title);3997for (i = 0; i < 78; i++) err.print_raw("-");3998err.cr();3999err.print_raw_cr(message);4000for (i = 0; i < 78; i++) err.print_raw("=");4001err.cr();40024003char buf[16];4004// Prevent process from exiting upon "read error" without consuming all CPU4005while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }40064007return buf[0] == 'y' || buf[0] == 'Y';4008}40094010int os::stat(const char *path, struct stat *sbuf) {4011char pathbuf[MAX_PATH];4012if (strlen(path) > MAX_PATH - 1) {4013errno = ENAMETOOLONG;4014return -1;4015}4016os::native_path(strcpy(pathbuf, path));4017return ::stat(pathbuf, sbuf);4018}40194020bool os::check_heap(bool force) {4021return true;4022}40234024ATTRIBUTE_PRINTF(3, 0)4025int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {4026return ::vsnprintf(buf, count, format, args);4027}40284029// Is a (classpath) directory empty?4030bool os::dir_is_empty(const char* path) {4031DIR *dir = NULL;4032struct dirent *ptr;40334034dir = opendir(path);4035if (dir == NULL) return true;40364037/* Scan the directory */4038bool result = true;4039while (result && (ptr = readdir(dir)) != NULL) {4040if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {4041result = false;4042}4043}4044closedir(dir);4045return result;4046}40474048// This code originates from JDK's sysOpen and open64_w4049// from src/solaris/hpi/src/system_md.c40504051#ifndef O_DELETE4052#define O_DELETE 0x100004053#endif40544055// Open a file. Unlink the file immediately after open returns4056// if the specified oflag has the O_DELETE flag set.4057// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c40584059int os::open(const char *path, int oflag, int mode) {40604061if (strlen(path) > MAX_PATH - 1) {4062errno = ENAMETOOLONG;4063return -1;4064}4065int fd;4066int o_delete = (oflag & O_DELETE);4067oflag = oflag & ~O_DELETE;40684069fd = ::open(path, oflag, mode);4070if (fd == -1) return -1;40714072//If the open succeeded, the file might still be a directory4073{4074struct stat buf;4075int ret = ::fstat(fd, &buf);4076int st_mode = buf.st_mode;40774078if (ret != -1) {4079if ((st_mode & S_IFMT) == S_IFDIR) {4080errno = EISDIR;4081::close(fd);4082return -1;4083}4084} else {4085::close(fd);4086return -1;4087}4088}40894090/*4091* All file descriptors that are opened in the JVM and not4092* specifically destined for a subprocess should have the4093* close-on-exec flag set. If we don't set it, then careless 3rd4094* party native code might fork and exec without closing all4095* appropriate file descriptors (e.g. as we do in closeDescriptors in4096* UNIXProcess.c), and this in turn might:4097*4098* - cause end-of-file to fail to be detected on some file4099* descriptors, resulting in mysterious hangs, or4100*4101* - might cause an fopen in the subprocess to fail on a system4102* suffering from bug 1085341.4103*4104* (Yes, the default setting of the close-on-exec flag is a Unix4105* design flaw)4106*4107* See:4108* 1085341: 32-bit stdio routines should support file descriptors >2554109* 4843136: (process) pipe file descriptor from Runtime.exec not being closed4110* 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 94111*/4112#ifdef FD_CLOEXEC4113{4114int flags = ::fcntl(fd, F_GETFD);4115if (flags != -1)4116::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);4117}4118#endif41194120if (o_delete != 0) {4121::unlink(path);4122}4123return fd;4124}412541264127// create binary file, rewriting existing file if required4128int os::create_binary_file(const char* path, bool rewrite_existing) {4129int oflags = O_WRONLY | O_CREAT;4130if (!rewrite_existing) {4131oflags |= O_EXCL;4132}4133return ::open(path, oflags, S_IREAD | S_IWRITE);4134}41354136// return current position of file pointer4137jlong os::current_file_offset(int fd) {4138return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);4139}41404141// move file pointer to the specified offset4142jlong os::seek_to_file_offset(int fd, jlong offset) {4143return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);4144}41454146// This code originates from JDK's sysAvailable4147// from src/solaris/hpi/src/native_threads/src/sys_api_td.c41484149int os::available(int fd, jlong *bytes) {4150jlong cur, end;4151int mode;4152struct stat buf;41534154if (::fstat(fd, &buf) >= 0) {4155mode = buf.st_mode;4156if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {4157/*4158* XXX: is the following call interruptible? If so, this might4159* need to go through the INTERRUPT_IO() wrapper as for other4160* blocking, interruptible calls in this file.4161*/4162int n;4163if (::ioctl(fd, FIONREAD, &n) >= 0) {4164*bytes = n;4165return 1;4166}4167}4168}4169if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {4170return 0;4171} else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {4172return 0;4173} else if (::lseek(fd, cur, SEEK_SET) == -1) {4174return 0;4175}4176*bytes = end - cur;4177return 1;4178}41794180int os::socket_available(int fd, jint *pbytes) {4181if (fd < 0)4182return OS_OK;41834184int ret;41854186RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);41874188//%% note ioctl can return 0 when successful, JVM_SocketAvailable4189// is expected to return 0 on failure and 1 on success to the jdk.41904191return (ret == OS_ERR) ? 0 : 1;4192}41934194// Map a block of memory.4195char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,4196char *addr, size_t bytes, bool read_only,4197bool allow_exec) {4198int prot;4199int flags;42004201if (read_only) {4202prot = PROT_READ;4203flags = MAP_SHARED;4204} else {4205prot = PROT_READ | PROT_WRITE;4206flags = MAP_PRIVATE;4207}42084209if (allow_exec) {4210prot |= PROT_EXEC;4211}42124213if (addr != NULL) {4214flags |= MAP_FIXED;4215}42164217char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,4218fd, file_offset);4219if (mapped_address == MAP_FAILED) {4220return NULL;4221}4222return mapped_address;4223}422442254226// Remap a block of memory.4227char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,4228char *addr, size_t bytes, bool read_only,4229bool allow_exec) {4230// same as map_memory() on this OS4231return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,4232allow_exec);4233}423442354236// Unmap a block of memory.4237bool os::pd_unmap_memory(char* addr, size_t bytes) {4238return munmap(addr, bytes) == 0;4239}42404241// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)4242// are used by JVM M&M and JVMTI to get user+sys or user CPU time4243// of a thread.4244//4245// current_thread_cpu_time() and thread_cpu_time(Thread*) returns4246// the fast estimate available on the platform.42474248jlong os::current_thread_cpu_time() {4249#ifdef __APPLE__4250return os::thread_cpu_time(Thread::current(), true /* user + sys */);4251#else4252Unimplemented();4253return 0;4254#endif4255}42564257jlong os::thread_cpu_time(Thread* thread) {4258#ifdef __APPLE__4259return os::thread_cpu_time(thread, true /* user + sys */);4260#else4261Unimplemented();4262return 0;4263#endif4264}42654266jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {4267#ifdef __APPLE__4268return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);4269#else4270Unimplemented();4271return 0;4272#endif4273}42744275jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {4276#ifdef __APPLE__4277struct thread_basic_info tinfo;4278mach_msg_type_number_t tcount = THREAD_INFO_MAX;4279kern_return_t kr;4280thread_t mach_thread;42814282mach_thread = thread->osthread()->thread_id();4283kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);4284if (kr != KERN_SUCCESS)4285return -1;42864287if (user_sys_cpu_time) {4288jlong nanos;4289nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;4290nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;4291return nanos;4292} else {4293return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);4294}4295#else4296Unimplemented();4297return 0;4298#endif4299}430043014302void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {4303info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits4304info_ptr->may_skip_backward = false; // elapsed time not wall time4305info_ptr->may_skip_forward = false; // elapsed time not wall time4306info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned4307}43084309void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {4310info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits4311info_ptr->may_skip_backward = false; // elapsed time not wall time4312info_ptr->may_skip_forward = false; // elapsed time not wall time4313info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned4314}43154316bool os::is_thread_cpu_time_supported() {4317#ifdef __APPLE__4318return true;4319#else4320return false;4321#endif4322}43234324// System loadavg support. Returns -1 if load average cannot be obtained.4325// Bsd doesn't yet have a (official) notion of processor sets,4326// so just return the system wide load average.4327int os::loadavg(double loadavg[], int nelem) {4328return ::getloadavg(loadavg, nelem);4329}43304331void os::pause() {4332char filename[MAX_PATH];4333if (PauseAtStartupFile && PauseAtStartupFile[0]) {4334jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);4335} else {4336jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());4337}43384339int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);4340if (fd != -1) {4341struct stat buf;4342::close(fd);4343while (::stat(filename, &buf) == 0) {4344(void)::poll(NULL, 0, 100);4345}4346} else {4347jio_fprintf(stderr,4348"Could not open pause file '%s', continuing immediately.\n", filename);4349}4350}435143524353// Refer to the comments in os_solaris.cpp park-unpark.4354//4355// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can4356// hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.4357// For specifics regarding the bug see GLIBC BUGID 261237 :4358// http://www.mail-archive.com/[email protected]/msg10837.html.4359// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future4360// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar4361// is used. (The simple C test-case provided in the GLIBC bug report manifests the4362// hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()4363// and monitorenter when we're using 1-0 locking. All those operations may result in4364// calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version4365// of libpthread avoids the problem, but isn't practical.4366//4367// Possible remedies:4368//4369// 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.4370// This is palliative and probabilistic, however. If the thread is preempted4371// between the call to compute_abstime() and pthread_cond_timedwait(), more4372// than the minimum period may have passed, and the abstime may be stale (in the4373// past) resultin in a hang. Using this technique reduces the odds of a hang4374// but the JVM is still vulnerable, particularly on heavily loaded systems.4375//4376// 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead4377// of the usual flag-condvar-mutex idiom. The write side of the pipe is set4378// NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)4379// reduces to poll()+read(). This works well, but consumes 2 FDs per extant4380// thread.4381//4382// 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread4383// that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing4384// a timeout request to the chron thread and then blocking via pthread_cond_wait().4385// This also works well. In fact it avoids kernel-level scalability impediments4386// on certain platforms that don't handle lots of active pthread_cond_timedwait()4387// timers in a graceful fashion.4388//4389// 4. When the abstime value is in the past it appears that control returns4390// correctly from pthread_cond_timedwait(), but the condvar is left corrupt.4391// Subsequent timedwait/wait calls may hang indefinitely. Given that, we4392// can avoid the problem by reinitializing the condvar -- by cond_destroy()4393// followed by cond_init() -- after all calls to pthread_cond_timedwait().4394// It may be possible to avoid reinitialization by checking the return4395// value from pthread_cond_timedwait(). In addition to reinitializing the4396// condvar we must establish the invariant that cond_signal() is only called4397// within critical sections protected by the adjunct mutex. This prevents4398// cond_signal() from "seeing" a condvar that's in the midst of being4399// reinitialized or that is corrupt. Sadly, this invariant obviates the4400// desirable signal-after-unlock optimization that avoids futile context switching.4401//4402// I'm also concerned that some versions of NTPL might allocate an auxilliary4403// structure when a condvar is used or initialized. cond_destroy() would4404// release the helper structure. Our reinitialize-after-timedwait fix4405// put excessive stress on malloc/free and locks protecting the c-heap.4406//4407// We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.4408// It may be possible to refine (4) by checking the kernel and NTPL verisons4409// and only enabling the work-around for vulnerable environments.44104411// utility to compute the abstime argument to timedwait:4412// millis is the relative timeout time4413// abstime will be the absolute timeout time4414// TODO: replace compute_abstime() with unpackTime()44154416static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {4417if (millis < 0) millis = 0;4418struct timeval now;4419int status = gettimeofday(&now, NULL);4420assert(status == 0, "gettimeofday");4421jlong seconds = millis / 1000;4422millis %= 1000;4423if (seconds > 50000000) { // see man cond_timedwait(3T)4424seconds = 50000000;4425}4426abstime->tv_sec = now.tv_sec + seconds;4427long usec = now.tv_usec + millis * 1000;4428if (usec >= 1000000) {4429abstime->tv_sec += 1;4430usec -= 1000000;4431}4432abstime->tv_nsec = usec * 1000;4433return abstime;4434}443544364437// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.4438// Conceptually TryPark() should be equivalent to park(0).44394440int os::PlatformEvent::TryPark() {4441for (;;) {4442const int v = _Event ;4443guarantee ((v == 0) || (v == 1), "invariant") ;4444if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;4445}4446}44474448void os::PlatformEvent::park() { // AKA "down()"4449// Invariant: Only the thread associated with the Event/PlatformEvent4450// may call park().4451// TODO: assert that _Assoc != NULL or _Assoc == Self4452int v ;4453for (;;) {4454v = _Event ;4455if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;4456}4457guarantee (v >= 0, "invariant") ;4458if (v == 0) {4459// Do this the hard way by blocking ...4460int status = pthread_mutex_lock(_mutex);4461assert_status(status == 0, status, "mutex_lock");4462guarantee (_nParked == 0, "invariant") ;4463++ _nParked ;4464while (_Event < 0) {4465status = pthread_cond_wait(_cond, _mutex);4466// for some reason, under 2.7 lwp_cond_wait() may return ETIME ...4467// Treat this the same as if the wait was interrupted4468if (status == ETIMEDOUT) { status = EINTR; }4469assert_status(status == 0 || status == EINTR, status, "cond_wait");4470}4471-- _nParked ;44724473_Event = 0 ;4474status = pthread_mutex_unlock(_mutex);4475assert_status(status == 0, status, "mutex_unlock");4476// Paranoia to ensure our locked and lock-free paths interact4477// correctly with each other.4478OrderAccess::fence();4479}4480guarantee (_Event >= 0, "invariant") ;4481}44824483int os::PlatformEvent::park(jlong millis) {4484guarantee (_nParked == 0, "invariant") ;44854486int v ;4487for (;;) {4488v = _Event ;4489if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;4490}4491guarantee (v >= 0, "invariant") ;4492if (v != 0) return OS_OK ;44934494// We do this the hard way, by blocking the thread.4495// Consider enforcing a minimum timeout value.4496struct timespec abst;4497compute_abstime(&abst, millis);44984499int ret = OS_TIMEOUT;4500int status = pthread_mutex_lock(_mutex);4501assert_status(status == 0, status, "mutex_lock");4502guarantee (_nParked == 0, "invariant") ;4503++_nParked ;45044505// Object.wait(timo) will return because of4506// (a) notification4507// (b) timeout4508// (c) thread.interrupt4509//4510// Thread.interrupt and object.notify{All} both call Event::set.4511// That is, we treat thread.interrupt as a special case of notification.4512// The underlying Solaris implementation, cond_timedwait, admits4513// spurious/premature wakeups, but the JLS/JVM spec prevents the4514// JVM from making those visible to Java code. As such, we must4515// filter out spurious wakeups. We assume all ETIME returns are valid.4516//4517// TODO: properly differentiate simultaneous notify+interrupt.4518// In that case, we should propagate the notify to another waiter.45194520while (_Event < 0) {4521status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);4522if (status != 0 && WorkAroundNPTLTimedWaitHang) {4523pthread_cond_destroy (_cond);4524pthread_cond_init (_cond, NULL) ;4525}4526assert_status(status == 0 || status == EINTR ||4527status == ETIMEDOUT,4528status, "cond_timedwait");4529if (!FilterSpuriousWakeups) break ; // previous semantics4530if (status == ETIMEDOUT) break ;4531// We consume and ignore EINTR and spurious wakeups.4532}4533--_nParked ;4534if (_Event >= 0) {4535ret = OS_OK;4536}4537_Event = 0 ;4538status = pthread_mutex_unlock(_mutex);4539assert_status(status == 0, status, "mutex_unlock");4540assert (_nParked == 0, "invariant") ;4541// Paranoia to ensure our locked and lock-free paths interact4542// correctly with each other.4543OrderAccess::fence();4544return ret;4545}45464547void os::PlatformEvent::unpark() {4548// Transitions for _Event:4549// 0 :=> 14550// 1 :=> 14551// -1 :=> either 0 or 1; must signal target thread4552// That is, we can safely transition _Event from -1 to either4553// 0 or 1. Forcing 1 is slightly more efficient for back-to-back4554// unpark() calls.4555// See also: "Semaphores in Plan 9" by Mullender & Cox4556//4557// Note: Forcing a transition from "-1" to "1" on an unpark() means4558// that it will take two back-to-back park() calls for the owning4559// thread to block. This has the benefit of forcing a spurious return4560// from the first park() call after an unpark() call which will help4561// shake out uses of park() and unpark() without condition variables.45624563if (Atomic::xchg(1, &_Event) >= 0) return;45644565// Wait for the thread associated with the event to vacate4566int status = pthread_mutex_lock(_mutex);4567assert_status(status == 0, status, "mutex_lock");4568int AnyWaiters = _nParked;4569assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");4570if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {4571AnyWaiters = 0;4572pthread_cond_signal(_cond);4573}4574status = pthread_mutex_unlock(_mutex);4575assert_status(status == 0, status, "mutex_unlock");4576if (AnyWaiters != 0) {4577status = pthread_cond_signal(_cond);4578assert_status(status == 0, status, "cond_signal");4579}45804581// Note that we signal() _after dropping the lock for "immortal" Events.4582// This is safe and avoids a common class of futile wakeups. In rare4583// circumstances this can cause a thread to return prematurely from4584// cond_{timed}wait() but the spurious wakeup is benign and the victim will4585// simply re-test the condition and re-park itself.4586}458745884589// JSR1664590// -------------------------------------------------------45914592/*4593* The solaris and bsd implementations of park/unpark are fairly4594* conservative for now, but can be improved. They currently use a4595* mutex/condvar pair, plus a a count.4596* Park decrements count if > 0, else does a condvar wait. Unpark4597* sets count to 1 and signals condvar. Only one thread ever waits4598* on the condvar. Contention seen when trying to park implies that someone4599* is unparking you, so don't wait. And spurious returns are fine, so there4600* is no need to track notifications.4601*/46024603#define MAX_SECS 1000000004604/*4605* This code is common to bsd and solaris and will be moved to a4606* common place in dolphin.4607*4608* The passed in time value is either a relative time in nanoseconds4609* or an absolute time in milliseconds. Either way it has to be unpacked4610* into suitable seconds and nanoseconds components and stored in the4611* given timespec structure.4612* Given time is a 64-bit value and the time_t used in the timespec is only4613* a signed-32-bit value (except on 64-bit Bsd) we have to watch for4614* overflow if times way in the future are given. Further on Solaris versions4615* prior to 10 there is a restriction (see cond_timedwait) that the specified4616* number of seconds, in abstime, is less than current_time + 100,000,000.4617* As it will be 28 years before "now + 100000000" will overflow we can4618* ignore overflow and just impose a hard-limit on seconds using the value4619* of "now + 100,000,000". This places a limit on the timeout of about 3.174620* years from "now".4621*/46224623static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {4624assert (time > 0, "convertTime");46254626struct timeval now;4627int status = gettimeofday(&now, NULL);4628assert(status == 0, "gettimeofday");46294630time_t max_secs = now.tv_sec + MAX_SECS;46314632if (isAbsolute) {4633jlong secs = time / 1000;4634if (secs > max_secs) {4635absTime->tv_sec = max_secs;4636}4637else {4638absTime->tv_sec = secs;4639}4640absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;4641}4642else {4643jlong secs = time / NANOSECS_PER_SEC;4644if (secs >= MAX_SECS) {4645absTime->tv_sec = max_secs;4646absTime->tv_nsec = 0;4647}4648else {4649absTime->tv_sec = now.tv_sec + secs;4650absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;4651if (absTime->tv_nsec >= NANOSECS_PER_SEC) {4652absTime->tv_nsec -= NANOSECS_PER_SEC;4653++absTime->tv_sec; // note: this must be <= max_secs4654}4655}4656}4657assert(absTime->tv_sec >= 0, "tv_sec < 0");4658assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");4659assert(absTime->tv_nsec >= 0, "tv_nsec < 0");4660assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");4661}46624663void Parker::park(bool isAbsolute, jlong time) {4664// Ideally we'd do something useful while spinning, such4665// as calling unpackTime().46664667// Optional fast-path check:4668// Return immediately if a permit is available.4669// We depend on Atomic::xchg() having full barrier semantics4670// since we are doing a lock-free update to _counter.4671if (Atomic::xchg(0, &_counter) > 0) return;46724673Thread* thread = Thread::current();4674assert(thread->is_Java_thread(), "Must be JavaThread");4675JavaThread *jt = (JavaThread *)thread;46764677// Optional optimization -- avoid state transitions if there's an interrupt pending.4678// Check interrupt before trying to wait4679if (Thread::is_interrupted(thread, false)) {4680return;4681}46824683// Next, demultiplex/decode time arguments4684struct timespec absTime;4685if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all4686return;4687}4688if (time > 0) {4689unpackTime(&absTime, isAbsolute, time);4690}469146924693// Enter safepoint region4694// Beware of deadlocks such as 6317397.4695// The per-thread Parker:: mutex is a classic leaf-lock.4696// In particular a thread must never block on the Threads_lock while4697// holding the Parker:: mutex. If safepoints are pending both the4698// the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.4699ThreadBlockInVM tbivm(jt);47004701// Don't wait if cannot get lock since interference arises from4702// unblocking. Also. check interrupt before trying wait4703if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {4704return;4705}47064707int status ;4708if (_counter > 0) { // no wait needed4709_counter = 0;4710status = pthread_mutex_unlock(_mutex);4711assert (status == 0, "invariant") ;4712// Paranoia to ensure our locked and lock-free paths interact4713// correctly with each other and Java-level accesses.4714OrderAccess::fence();4715return;4716}47174718#ifdef ASSERT4719// Don't catch signals while blocked; let the running threads have the signals.4720// (This allows a debugger to break into the running thread.)4721sigset_t oldsigs;4722sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();4723pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);4724#endif47254726OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);4727jt->set_suspend_equivalent();4728// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()47294730if (time == 0) {4731status = pthread_cond_wait (_cond, _mutex) ;4732} else {4733status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;4734if (status != 0 && WorkAroundNPTLTimedWaitHang) {4735pthread_cond_destroy (_cond) ;4736pthread_cond_init (_cond, NULL);4737}4738}4739assert_status(status == 0 || status == EINTR ||4740status == ETIMEDOUT,4741status, "cond_timedwait");47424743#ifdef ASSERT4744pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);4745#endif47464747_counter = 0 ;4748status = pthread_mutex_unlock(_mutex) ;4749assert_status(status == 0, status, "invariant") ;4750// Paranoia to ensure our locked and lock-free paths interact4751// correctly with each other and Java-level accesses.4752OrderAccess::fence();47534754// If externally suspended while waiting, re-suspend4755if (jt->handle_special_suspend_equivalent_condition()) {4756jt->java_suspend_self();4757}4758}47594760void Parker::unpark() {4761int s, status ;4762status = pthread_mutex_lock(_mutex);4763assert (status == 0, "invariant") ;4764s = _counter;4765_counter = 1;4766if (s < 1) {4767if (WorkAroundNPTLTimedWaitHang) {4768status = pthread_cond_signal (_cond) ;4769assert (status == 0, "invariant") ;4770status = pthread_mutex_unlock(_mutex);4771assert (status == 0, "invariant") ;4772} else {4773status = pthread_mutex_unlock(_mutex);4774assert (status == 0, "invariant") ;4775status = pthread_cond_signal (_cond) ;4776assert (status == 0, "invariant") ;4777}4778} else {4779pthread_mutex_unlock(_mutex);4780assert (status == 0, "invariant") ;4781}4782}478347844785/* Darwin has no "environ" in a dynamic library. */4786#ifdef __APPLE__4787#include <crt_externs.h>4788#define environ (*_NSGetEnviron())4789#else4790extern char** environ;4791#endif47924793// Run the specified command in a separate process. Return its exit value,4794// or -1 on failure (e.g. can't fork a new process).4795// Unlike system(), this function can be called from signal handler. It4796// doesn't block SIGINT et al.4797int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {4798const char * argv[4] = {"sh", "-c", cmd, NULL};47994800// fork() in BsdThreads/NPTL is not async-safe. It needs to run4801// pthread_atfork handlers and reset pthread library. All we need is a4802// separate process to execve. Make a direct syscall to fork process.4803// On IA64 there's no fork syscall, we have to use fork() and hope for4804// the best...4805pid_t pid = fork();48064807if (pid < 0) {4808// fork failed4809return -1;48104811} else if (pid == 0) {4812// child process48134814// execve() in BsdThreads will call pthread_kill_other_threads_np()4815// first to kill every thread on the thread list. Because this list is4816// not reset by fork() (see notes above), execve() will instead kill4817// every thread in the parent process. We know this is the only thread4818// in the new process, so make a system call directly.4819// IA64 should use normal execve() from glibc to match the glibc fork()4820// above.4821execve("/bin/sh", (char* const*)argv, environ);48224823// execve failed4824_exit(-1);48254826} else {4827// copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't4828// care about the actual exit code, for now.48294830int status;48314832// Wait for the child process to exit. This returns immediately if4833// the child has already exited. */4834while (waitpid(pid, &status, 0) < 0) {4835switch (errno) {4836case ECHILD: return 0;4837case EINTR: break;4838default: return -1;4839}4840}48414842if (WIFEXITED(status)) {4843// The child exited normally; get its exit code.4844return WEXITSTATUS(status);4845} else if (WIFSIGNALED(status)) {4846// The child exited because of a signal4847// The best value to return is 0x80 + signal number,4848// because that is what all Unix shells do, and because4849// it allows callers to distinguish between process exit and4850// process death by signal.4851return 0x80 + WTERMSIG(status);4852} else {4853// Unknown exit code; pass it through4854return status;4855}4856}4857}48584859// is_headless_jre()4860//4861// Test for the existence of xawt/libmawt.so or libawt_xawt.so4862// in order to report if we are running in a headless jre4863//4864// Since JDK8 xawt/libmawt.so was moved into the same directory4865// as libawt.so, and renamed libawt_xawt.so4866//4867bool os::is_headless_jre() {4868#ifdef __APPLE__4869// We no longer build headless-only on Mac OS X4870return false;4871#else4872struct stat statbuf;4873char buf[MAXPATHLEN];4874char libmawtpath[MAXPATHLEN];4875const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX;4876const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;4877char *p;48784879// Get path to libjvm.so4880os::jvm_path(buf, sizeof(buf));48814882// Get rid of libjvm.so4883p = strrchr(buf, '/');4884if (p == NULL) return false;4885else *p = '\0';48864887// Get rid of client or server4888p = strrchr(buf, '/');4889if (p == NULL) return false;4890else *p = '\0';48914892// check xawt/libmawt.so4893strcpy(libmawtpath, buf);4894strcat(libmawtpath, xawtstr);4895if (::stat(libmawtpath, &statbuf) == 0) return false;48964897// check libawt_xawt.so4898strcpy(libmawtpath, buf);4899strcat(libmawtpath, new_xawtstr);4900if (::stat(libmawtpath, &statbuf) == 0) return false;49014902return true;4903#endif4904}49054906// Get the default path to the core file4907// Returns the length of the string4908int os::get_core_path(char* buffer, size_t bufferSize) {4909int n = jio_snprintf(buffer, bufferSize, "/cores");49104911// Truncate if theoretical string was longer than bufferSize4912n = MIN2(n, (int)bufferSize);49134914return n;4915}49164917#ifndef PRODUCT4918void TestReserveMemorySpecial_test() {4919// No tests available for this platform4920}4921#endif492249234924