os_bsd.cpp revision 4559
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// no precompiled headers
#include "classfile/classLoader.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/icBuffer.hpp"
#include "code/vtableStubs.hpp"
#include "compiler/compileBroker.hpp"
#include "interpreter/interpreter.hpp"
#include "jvm_bsd.h"
#include "memory/allocation.inline.hpp"
#include "memory/filemap.hpp"
#include "mutex_bsd.inline.hpp"
#include "oops/oop.inline.hpp"
#include "os_share_bsd.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm_misc.hpp"
#include "runtime/arguments.hpp"
#include "runtime/extendedPC.hpp"
#include "runtime/globals.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/osThread.hpp"
#include "runtime/perfMemory.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/statSampler.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/threadCritical.hpp"
#include "services/attachListener.hpp"
#include "services/memTracker.hpp"
#include "services/runtimeService.hpp"
#include "thread_bsd.inline.hpp"
#include "utilities/decoder.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
#include "utilities/growableArray.hpp"
#include "utilities/vmError.hpp"
#ifdef TARGET_ARCH_x86
# include "assembler_x86.inline.hpp"
# include "nativeInst_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "assembler_sparc.inline.hpp"
# include "nativeInst_sparc.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "assembler_zero.inline.hpp"
# include "nativeInst_zero.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "assembler_arm.inline.hpp"
# include "nativeInst_arm.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "assembler_ppc.inline.hpp"
# include "nativeInst_ppc.hpp"
#endif
// put OS-includes here
# include <pthread.h>
# include <signal.h>
# include <errno.h>
# include <dlfcn.h>
# include <stdio.h>
# include <unistd.h>
# include <sys/resource.h>
# include <pthread.h>
# include <time.h>
# include <pwd.h>
# include <poll.h>
# include <semaphore.h>
# include <fcntl.h>
# include <string.h>
#ifdef _ALLBSD_SOURCE
#else
# include <syscall.h>
# include <gnu/libc-version.h>
#endif
#ifndef __APPLE__
# include <link.h>
#endif
# include <stdint.h>
# include <inttypes.h>
#if defined(__FreeBSD__) || defined(__NetBSD__)
# include <elf.h>
#endif
#ifdef __APPLE__
# include <sys/proc_info.h>
# include <objc/objc-auto.h>
#endif
#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif
#define MAX_PATH (2 * K)
// for timer info max values which include all bits
////////////////////////////////////////////////////////////////////////////////
// global variables
#ifndef _ALLBSD_SOURCE
#endif
#ifndef _ALLBSD_SOURCE
#endif
#ifndef _ALLBSD_SOURCE
#endif
static jlong initial_time_count=0;
static int clock_tics_per_sec = 100;
// For diagnostics to print a message once. see run_periodic_checks
static sigset_t check_signal_done;
static bool check_signals = true;;
static pid_t _initial_pid = 0;
/* do not use any signal number less than SIGSEGV, see 4355769 */
////////////////////////////////////////////////////////////////////////////////
// utility functions
static int SR_initialize();
static int SR_finalize();
return Bsd::available_memory();
}
#ifdef _ALLBSD_SOURCE
// XXXBSD: this is just a stopgap implementation
return physical_memory() >> 2;
#else
// values in struct sysinfo are "unsigned long"
#endif
}
return Bsd::physical_memory();
}
#ifdef _LP64
return size;
#else
if (!is_allocatable(result)) {
// See comments under solaris for alignment considerations
}
return result;
#endif // _LP64
}
////////////////////////////////////////////////////////////////////////////////
// environment support
return true;
}
return false;
}
// Return true if user is running as root.
bool os::have_special_privileges() {
static bool init = false;
static bool privileges = false;
if (!init) {
init = true;
}
return privileges;
}
#ifndef _ALLBSD_SOURCE
#ifndef SYS_gettid
// i386: 224, ia64: 1105, amd64: 186, sparc 143
#ifdef __ia64__
#define SYS_gettid 1105
#define SYS_gettid 224
#define SYS_gettid 186
#define SYS_gettid 143
#else
#endif
#endif
#endif
// Cpu architecture string
#if defined(ZERO)
static char cpu_arch[] = ZERO_LIBARCH;
static char cpu_arch[] = "ia64";
static char cpu_arch[] = "i386";
static char cpu_arch[] = "amd64";
static char cpu_arch[] = "arm";
static char cpu_arch[] = "ppc";
# ifdef _LP64
static char cpu_arch[] = "sparcv9";
# else
static char cpu_arch[] = "sparc";
# endif
#else
#endif
// Compiler variant
#ifdef COMPILER2
#define COMPILER_VARIANT "server"
#else
#define COMPILER_VARIANT "client"
#endif
#ifndef _ALLBSD_SOURCE
// pid_t gettid()
//
// Returns the kernel thread id of the currently running thread. Kernel
// thread id is used to access /proc.
//
// (Note that getpid() on BsdThreads returns kernel thread id too; but
// on NPTL, it returns the same pid for all threads, as required by POSIX.)
//
if (rslt == -1) {
// old kernel, no NPTL support
return getpid();
} else {
}
}
// Most versions of bsd have a bug where the number of processors are
// determined by looking at the /proc file system. In a chroot environment,
// the system call returns 1. This causes the VM to act as if it is
// a single processor and elide locking (see is_MP() call).
static bool unsafe_chroot_detected = false;
static const char *unstable_chroot_error = "/proc file system not found.\n"
"Java may be unstable running multithreaded in a chroot "
"environment on Bsd when /proc filesystem is not mounted.";
#endif
#ifdef _ALLBSD_SOURCE
int mib[2];
int cpu_val;
/* get processors count via hw.ncpus sysctl */
}
else {
}
/* get physical memory via hw.memsize sysctl (hw.memsize is used
* since it returns a 64 bit value)
*/
} else {
}
#ifdef __OpenBSD__
{
// limit _physical_memory memory view on OpenBSD since
// datasize rlimit restricts us anyway.
}
#endif
}
#else
if (processor_count() == 1) {
char fname[32];
unsafe_chroot_detected = true;
} else {
}
}
}
#endif
#ifdef __APPLE__
static const char *get_home() {
if (passwd_info != NULL) {
}
}
return home_dir;
}
#endif
void os::init_system_properties_values() {
// char arch[12];
// sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
// The next steps are taken in the product version:
//
// Obtain the JAVA_HOME value from the location of libjvm[_g].so.
// This library should be located at:
//
// assume libjvm[_g].so is installed in a JDK and we use this path.
//
// Otherwise exit with message: "Could not create the Java virtual machine."
//
// The following extra steps are taken in the debugging version:
//
// instead of exit check for $JAVA_HOME environment variable.
//
// it looks like libjvm[_g].so is installed there
//
// Otherwise exit.
//
// Important note: if the location of libjvm.so changes this
// code needs to be changed accordingly.
// The next few definitions allow the code to be verbatim:
/*
* See ld(1):
* The linker uses the following search paths to locate required
* shared libraries:
* 1: ...
* ...
*/
#ifndef DEFAULT_LIBPATH
#define DEFAULT_LIBPATH "/lib:/usr/lib"
#endif
#define EXTENSIONS_DIR "/lib/ext"
#define ENDORSED_DIR "/lib/endorsed"
#ifdef __APPLE__
#define SYS_EXTENSIONS_DIR "/Library/Java/Extensions"
#define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
const char *user_home_dir = get_home();
// the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
sizeof(SYS_EXTENSIONS_DIRS);
#endif
{
/* sysclasspath, java_home, dll_dir */
{
char *home_path;
char *dll_path;
char *pslash;
char buf[MAXPATHLEN];
// Found the full path to libjvm.so.
// Now cut the path to <java_home>/jre if we can.
return;
#ifndef __APPLE__
#endif
}
}
return;
return;
}
/*
* Where to look for native libraries
*
* Note: Due to a legacy implementation, most of the library path
* is set in the launcher. This was to accomodate linking restrictions
* on legacy Bsd implementations (which are no longer supported).
* Eventually, all the library path setting will be done here.
*
* However, to prevent the proliferation of improperly built native
* Eventually, all the library path setting will be done here.
*/
{
char *ld_library_path;
/*
* Construct the invariant part of ld_library_path. Note that the
* space for the colon and the trailing null are provided by the
* nulls included by the sizeof operator (so actually we allocate
* a byte more than necessary).
*/
#ifdef __APPLE__
#else
#endif
/*
* Get the user setting of LD_LIBRARY_PATH, and prepended it. It
* should always exist (until the legacy problem cited above is
* addressed).
*/
#ifdef __APPLE__
// Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
char *l = getenv("JAVA_LIBRARY_PATH");
if (l != NULL) {
char *t = ld_library_path;
/* That's +1 for the colon and +1 for the trailing '\0' */
free(t);
}
char *v = getenv("DYLD_LIBRARY_PATH");
#else
char *v = getenv("LD_LIBRARY_PATH");
#endif
if (v != NULL) {
char *t = ld_library_path;
/* That's +1 for the colon and +1 for the trailing '\0' */
free(t);
}
#ifdef __APPLE__
// Apple's Java6 has "." at the beginning of java.library.path.
// OpenJDK on Windows has "." at the end of java.library.path.
// OpenJDK on Linux and Solaris don't have "." in java.library.path
// at all. To ease the transition from Apple's Java6 to OpenJDK7,
// "." is appended to the end of java.library.path. Yes, this
// could cause a change in behavior, but Apple's Java6 behavior
// can be achieved by putting "." at the beginning of the
// JAVA_LIBRARY_PATH environment variable.
{
char *t = ld_library_path;
// that's +3 for appending ":." and the trailing '\0'
free(t);
}
#endif
}
/*
* Extensions directories.
*
* Note that the space for the colon and the trailing null are provided
* by the nulls included by the sizeof operator (so actually one byte more
* than necessary is allocated).
*/
{
#ifdef __APPLE__
sizeof(EXTENSIONS_DIR) + system_ext_size);
#else
Arguments::get_java_home());
#endif
}
/* Endorsed standards default directory. */
{
char * buf;
}
}
#ifdef __APPLE__
#endif
// Done
return;
}
////////////////////////////////////////////////////////////////////////////////
// breakpoint support
void os::breakpoint() {
}
extern "C" void breakpoint() {
// use debugger to set breakpoint here
}
////////////////////////////////////////////////////////////////////////////////
// signal support
debug_only(static bool signal_sets_initialized = false);
return true;
else
return false;
}
// Should also have an assertion stating we are still single-threaded.
// Fill in signals that are necessarily unblocked for all threads in
// the VM. Currently, we unblock the following signals:
// SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
// by -Xrs (=ReduceSignalUsage));
// BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
// other threads. The "ReduceSignalUsage" boolean tells us not to alter
// the dispositions or masks wrt these signals.
// Programs embedding the VM that want to use the above signals for their
// own purposes must, at this time, use the "-Xrs" option to prevent
// interference with shutdown hooks and BREAK_SIGNAL thread dumping.
// (See bug 4345157, and other related bugs).
// In reality, though, unblocking these signals is really a nop, since
// these signals are not blocked by default.
if (!ReduceSignalUsage) {
}
}
}
}
// Fill in signals that are blocked by all but the VM thread.
if (!ReduceSignalUsage)
debug_only(signal_sets_initialized = true);
}
// These are signals that are unblocked while a thread is running Java.
// (For some reason, they get blocked by default.)
return &unblocked_sigs;
}
// These are the signals that are blocked while a (non-VM) thread is
// running Java. Only the VM thread handles these signals.
return &vm_sigs;
}
// These are signals that are blocked during cond_wait to allow debugger in
return &allowdebug_blocked_sigs;
}
//Save caller's signal mask before setting VM signal mask
if (!ReduceSignalUsage) {
if (thread->is_VM_thread()) {
// Only the VM thread handles BREAK_SIGNAL ...
} else {
// ... all other threads block BREAK_SIGNAL
}
}
}
#ifndef _ALLBSD_SOURCE
//////////////////////////////////////////////////////////////////////////////
// detecting pthread library
// Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION
// and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a
// generic name for earlier versions.
// Define macros here so we can build HotSpot on old systems.
# ifndef _CS_GNU_LIBC_VERSION
# define _CS_GNU_LIBC_VERSION 2
# endif
# ifndef _CS_GNU_LIBPTHREAD_VERSION
# define _CS_GNU_LIBPTHREAD_VERSION 3
# endif
if (n > 0) {
} else {
// _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
static char _gnu_libc_version[32];
}
if (n > 0) {
// Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells
// us "NPTL-0.29" even we are running with BsdThreads. Check if this
// is the case. BsdThreads has a hard limit on max number of threads.
// So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value.
// On the other hand, NPTL does not have such a limit, sysconf()
// will return -1 and errno is not changed. Check if it is really NPTL.
sysconf(_SC_THREAD_THREADS_MAX) > 0) {
} else {
}
} else {
// glibc before 2.3.2 only has BsdThreads.
}
} else {
}
// BsdThreads have two flavors: floating-stack mode, which allows variable
// stack size; and fixed-stack mode. NPTL is always floating-stack.
}
}
/////////////////////////////////////////////////////////////////////////////
// thread stack
// Force Bsd kernel to expand current thread stack. If "bottom" is close
// to the stack guard, caller should block all signals.
//
// MAP_GROWSDOWN:
// A special mmap() flag that is used to implement thread stacks. It tells
// kernel that the memory region should extend downwards when needed. This
// allows early versions of BsdThreads to only mmap the first few pages
// when creating a new thread. Bsd kernel will automatically expand thread
// stack as needed (on page faults).
//
// However, because the memory region of a MAP_GROWSDOWN stack can grow on
// demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
// region, it's hard to tell if the fault is due to a legitimate stack
// overrun). As a rule, if the fault happens below current stack pointer,
// Bsd kernel does not expand stack, instead a SIGSEGV is sent to the
// application (see Bsd kernel fault.c).
//
// This Bsd feature can cause SIGSEGV when VM bangs thread stack for
// stack overflow detection.
//
// Newer version of BsdThreads (since glibc-2.2, or, RH-7.x) and NPTL do
// not use this flag. However, the stack of initial thread is not created
// by pthread, it is still MAP_GROWSDOWN. Also it's possible (though
// unlikely) that user code can create a thread with MAP_GROWSDOWN stack
// and then attach the thread to JVM.
//
// To get around the problem and allow stack banging on Bsd, we need to
// manually expand thread stack after receiving the SIGSEGV.
//
// There are two ways to expand thread stack to address "bottom", we used
// both of them in JVM before 1.5:
// 1. adjust stack pointer first so that it is below "bottom", and then
// touch "bottom"
// 2. mmap() the page in question
//
// Now alternate signal stack is gone, it's harder to use 2. For instance,
// if current sp is already near the lower end of page 101, and we need to
// call mmap() to map page 100, it is possible that part of the mmap() frame
// will be placed in page 100. When page 100 is mapped, it is zero-filled.
// That will destroy the mmap() frame and cause VM to crash.
//
// The following code works by adjusting sp first, then accessing the "bottom"
// page to force a page fault. Bsd kernel will then automatically expand the
// stack mapping.
//
// _expand_stack_to() assumes its frame size is less than page size, which
// should always be true if the function is not inlined.
#define NOINLINE
#else
#endif
volatile char *p;
// Adjust bottom to point to the largest address within the same page, it
// gives us a one-page buffer if alloca() allocates slightly more memory.
// sp might be slightly above current stack pointer; if that's the case, we
// will alloca() a little more space than necessary, which is OK. Don't use
// os::current_stack_pointer(), as its result can be slightly below current
// stack pointer, causing us to not alloca enough to reach "bottom".
p[0] = '\0';
}
}
return true;
}
return false;
}
#endif
//////////////////////////////////////////////////////////////////////////////
// create new thread
static address highest_vm_reserved_address();
// check if it's safe to start a new thread
#ifdef _ALLBSD_SOURCE
return true;
#else
// Heap is mmap'ed at lower end of memory space. Thread stacks are
// allocated (MAP_FIXED) from high address space. Every thread stack
// occupies a fixed size slot (usually 2Mbytes, but user can change
// it to other values if they rebuild BsdThreads).
//
// Problem with MAP_FIXED is that mmap() can still succeed even part of
// the memory region has already been mmap'ed. That means if we have too
// collide with heap.
//
// stack bottom with the highest address that has been mmap'ed by JVM
// plus a safety margin for memory maps created by native code.
//
// This feature can be disabled by setting ThreadSafetyMargin to 0
//
if (ThreadSafetyMargin > 0) {
// not safe if our stack extends below the safety margin
} else {
return true;
}
} else {
// Floating stack BsdThreads or NPTL:
// Unlike fixed stack BsdThreads, thread stacks are not MAP_FIXED. When
// there's not enough space left, pthread_create() will fail. If we come
// here, that means enough space has been reserved for stack.
return true;
}
#endif
}
#ifdef __APPLE__
// library handle for calling objc_registerThreadWithCollector()
// without static linking to the libobjc library
#define OBJC_LIB "/usr/lib/libobjc.dylib"
#define OBJC_GCREGISTER "objc_registerThreadWithCollector"
typedef void (*objc_registerThreadWithCollector_t)();
#endif
#ifdef __APPLE__
static uint64_t locate_unique_thread_id() {
// Additional thread_id used to correlate threads in SA
return m_ident_info.thread_id;
}
#endif
// Thread start routine for all newly created threads
// Try to randomize the cache line index of hot stack frames.
// This helps when threads of the same stack traces evict each other's
// cache lines. The threads can be either from the same JVM instance, or
// from different JVM instances. The benefit is especially true for
// processors with hyperthreading technology.
static int counter = 0;
// non floating stack BsdThreads needs extra check, see above
if (!_thread_safety_check(thread)) {
// notify parent thread
sync->notify_all();
return NULL;
}
#ifdef _ALLBSD_SOURCE
#ifdef __APPLE__
// thread_id is mach thread on macos
#else
// thread_id is pthread_id on BSD
#endif
#else
// thread_id is kernel thread id (similar to Solaris LWP id)
if (UseNUMA) {
if (lgrp_id != -1) {
}
}
#endif
// initialize signal mask for this thread
// initialize floating point control register
#ifdef __APPLE__
// register thread with objc gc
if (objc_registerThreadWithCollectorFunction != NULL) {
}
#endif
// handshaking with parent thread
{
// notify parent thread
sync->notify_all();
// wait until os::start_thread()
}
}
// call one more level start routine
return 0;
}
// Allocate the OSThread object
return false;
}
// set the correct thread state
// Initial state is ALLOCATED but not INITIALIZED
// init thread attributes
// stack size
// calculate stack size if it's not specified by caller
if (stack_size == 0) {
switch (thr_type) {
case os::java_thread:
// Java threads use ThreadStackSize which default value can be
// changed with the flag -Xss
break;
case os::compiler_thread:
if (CompilerThreadStackSize > 0) {
break;
} // else fall through:
// use VMThreadStackSize if CompilerThreadStackSize is not defined
case os::pgc_thread:
case os::cgc_thread:
case os::watcher_thread:
break;
}
}
} else {
// let pthread_create() pick the default value.
}
#ifndef _ALLBSD_SOURCE
// glibc guard page
#endif
{
#ifndef _ALLBSD_SOURCE
// Serialize thread creation if we are running with fixed stack BsdThreads
if (lock) {
}
#endif
if (ret != 0) {
perror("pthread_create()");
}
// Need to clean up stuff we've allocated so far
delete osthread;
#ifndef _ALLBSD_SOURCE
#endif
return false;
}
// Store pthread info into the OSThread
// Wait until child thread is either initialized or aborted
{
}
}
#ifndef _ALLBSD_SOURCE
if (lock) {
}
#endif
}
// Aborted due to thread limit being reached
delete osthread;
return false;
}
// The thread is returned suspended (in state INITIALIZED),
// and is started higher up in the call chain
return true;
}
/////////////////////////////////////////////////////////////////////////////
// attach existing thread
// bootstrap the main thread
return create_attached_thread(thread);
}
#ifdef ASSERT
#endif
// Allocate the OSThread object
return false;
}
// Store pthread info into the OSThread
#ifdef _ALLBSD_SOURCE
#ifdef __APPLE__
#else
#endif
#else
#endif
// initialize floating point control register
// Initial thread state is RUNNABLE
#ifndef _ALLBSD_SOURCE
if (UseNUMA) {
if (lgrp_id != -1) {
}
}
// If current thread is initial thread, its stack is mapped on demand,
// see notes about MAP_GROWSDOWN. Here we try to force kernel to map
// the entire stack region to avoid SEGV in stack banging.
// It is also useful to get around the heap-stack-gap problem on SuSE
// kernel (see 4821821 for details). We first expand stack to the top
// of yellow zone, then enable stack yellow zone (order is significant,
// enabling yellow zone first will crash JVM on SuSE Bsd), so there
// is no gap between the last two virtual memory regions.
}
#endif
// initialize signal mask for this thread
// and save the caller's signal mask
return true;
}
}
// Free Bsd resources related to the OSThread
// Restore caller's signal mask
}
delete osthread;
}
//////////////////////////////////////////////////////////////////////////////
// thread local storage
int os::allocate_thread_local_storage() {
return (int)key;
}
// Note: This is currently not used by VM, as we don't destroy TLS key
// on VM exit.
}
}
return ThreadLocalStorage::thread();
}
//////////////////////////////////////////////////////////////////////////////
// initial thread
#ifndef _ALLBSD_SOURCE
// Check if current thread is the initial thread, similar to Solaris thr_main.
char dummy;
// If called before init complete, thread stack bottom will be null.
// Can be called if fatal error occurs before initialization.
if (initial_thread_stack_bottom() == NULL) return false;
initial_thread_stack_size() != 0,
"os::init did not locate initial thread's stack region");
return true;
else return false;
}
// Find the virtual memory area that contains addr
if (fp) {
return true;
}
}
for (;;) {
}
}
}
return false;
}
// Locate initial thread stack. This special handling of initial thread stack
// is needed because pthread_getattr_np() on most (all?) Bsd distros returns
// bogus value for initial thread.
// stack size is the easy part, get it from RLIMIT_STACK
// 6308388: a bug in ld.so will relocate its own .data section to the
// lower end of primordial stack; reduce ulimit -s value a little bit
// so we won't install guard page on ld.so's data section.
// 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat
// 7.1, in both cases we will get 2G in return value.
// 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0,
// SuSE 7.2, Debian) can not handle alternate signal stack correctly
// for initial thread if its stack size exceeds 6M. Cap it at 2M,
// in case other parts in glibc still assumes 2M max stack size.
// FIXME: alt signal stack is gone, maybe we can relax this constraint?
#ifndef IA64
#else
// Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small
#endif
// Try to figure out where the stack base (top) is. This is harder.
//
// When an application is started, glibc saves the initial stack pointer in
// a global variable "__libc_stack_end", which is then used by system
// libraries. __libc_stack_end should be pretty close to stack top. The
// variable is available since the very early days. However, because it is
// a private interface, it could disappear in the future.
//
// Bsd kernel saves start_stack information in /proc/<pid>/stat. Similar
// to __libc_stack_end, it is very close to stack top, but isn't the real
// stack top. Note that /proc may not exist if VM is running as a chroot
// program, so reading /proc/<pid>/stat could fail. Also the contents of
// /proc/<pid>/stat could change in the future (though unlikely).
//
// We try __libc_stack_end first. If that doesn't work, look for
// /proc/<pid>/stat. If neither of them works, we use current stack pointer
// as a hint, which should work well in most cases.
// try __libc_stack_end first
if (p && *p) {
stack_start = *p;
} else {
int pid;
char state;
int ppid;
int pgrp;
int session;
int nr;
int tpgrp;
unsigned long flags;
unsigned long minflt;
unsigned long cminflt;
unsigned long majflt;
unsigned long cmajflt;
unsigned long utime;
unsigned long stime;
long cutime;
long cstime;
long prio;
long nice;
long junk;
long it_real;
int i;
// Figure what the primordial thread stack base is. Code is inspired
// followed by command name surrounded by parentheses, state, etc.
char stat[2048];
int statlen;
if (fp) {
// Skip pid and the command string. Note that we could be dealing with
// weird command names, e.g. user could decide to rename java launcher
// to "java 1.4.2 :)", then the stat file would look like
// 1234 (java 1.4.2 :)) R ... ...
// We don't really need to know the command string, just find the last
// occurrence of ")" and then start parsing from there. See bug 4726580.
i = 0;
if (s) {
// Skip blank chars
do s++; while (isspace(*s));
#define _UFM UINTX_FORMAT
#define _DFM INTX_FORMAT
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */
/* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */
i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM,
&state, /* 3 %c */
&ppid, /* 4 %d */
&pgrp, /* 5 %d */
&session, /* 6 %d */
&nr, /* 7 %d */
&tpgrp, /* 8 %d */
&flags, /* 9 %lu */
&minflt, /* 10 %lu */
&cminflt, /* 11 %lu */
&majflt, /* 12 %lu */
&cmajflt, /* 13 %lu */
&utime, /* 14 %lu */
&stime, /* 15 %lu */
&cutime, /* 16 %ld */
&cstime, /* 17 %ld */
&prio, /* 18 %ld */
&nice, /* 19 %ld */
&junk, /* 20 %ld */
&it_real, /* 21 %ld */
&start, /* 22 UINTX_FORMAT */
&vsize, /* 23 UINTX_FORMAT */
&rss, /* 24 INTX_FORMAT */
&rsslim, /* 25 UINTX_FORMAT */
&scodes, /* 26 UINTX_FORMAT */
&ecode, /* 27 UINTX_FORMAT */
&stack_start); /* 28 UINTX_FORMAT */
}
if (i != 28 - 2) {
// product mode - assume we are the initial thread, good luck in the
// embedded case.
warning("Can't detect initial thread stack location - bad conversion");
}
} else {
// FreeBSD with a Bsd emulator, or inside chroot), this should work for
// most cases, so don't abort:
}
}
// Now we have a pointer (stack_start) very close to the stack top, the
// next thing to do is to figure out the exact location of stack top. We
// can find out the virtual memory area that contains stack_start by
// and its upper limit is the real stack top. (again, this would fail if
// running inside chroot, because /proc may not exist.)
// success, "high" is the true stack top. (ignore "low", because initial
// thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
} else {
warning("Can't detect initial thread stack location - find_vma failed");
// best effort: stack_start is normally within a few pages below the real
// stack top, use it as stack top, and reduce stack size so we won't put
// guard page outside stack.
}
// stack_top could be partially down the page so align it
} else {
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
// time support
// Time since start-up in seconds to a fine granularity.
// Used by VMSelfDestructTimer and the MemProfiler.
double os::elapsedTime() {
}
}
return (1000 * 1000);
}
// XXX: For now, code this as if BSD does not support vtime.
bool os::supports_vtime() { return false; }
bool os::enable_vtime() { return false; }
bool os::vtime_enabled() { return false; }
double os::elapsedVTime() {
// better than nothing, but not much
return elapsedTime();
}
}
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC (1)
#endif
#ifdef __APPLE__
// XXXDARWIN: Investigate replacement monotonic clock
}
#elif defined(_ALLBSD_SOURCE)
// yes, monotonic clock is supported
}
}
#else
// we do dlopen's in this particular order due to bug in bsd
// dynamical loader (see 6348968) leading to crash on exit
}
if (handle) {
if (clock_getres_func && clock_gettime_func) {
// See if monotonic clock is supported by the kernel. Note that some
// early implementations simply return kernel jiffies (updated every
// 1/100 or 1/1000 second). It would be bad to use such a low res clock
// for nano time (though the monotonic property is still nice to have).
// It's fixed in newer kernels, however clock_getres() still returns
// 1/HZ. We check if clock_getres() works, but will ignore its reported
// resolution for now. Hopefully as people move to new kernels, this
// won't be a problem.
// yes, monotonic clock is supported
} else {
// close librt if there is no monotonic clock
}
}
}
}
#endif
#ifndef _ALLBSD_SOURCE
#ifndef SYS_clock_getres
#else
#warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
#define sys_clock_getres(x,y) -1
#endif
#else
#endif
if (!UseBsdPosixThreadCPUClocks) {
return;
}
// Switch to using fast clocks for thread cpu time if
// the sys_clock_getres() returns 0 error code.
// Note, that some kernels may support the current thread
// clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
// returned by the pthread_getcpuclockid().
// If the fast Posix clocks are supported then the sys_clock_getres()
// must return at least tp.tv_sec == 0 which means a resolution
// better than 1 sec. This is extra check for reliability.
_supports_fast_thread_cpu_time = true;
}
}
#endif
if (Bsd::supports_monotonic_clock()) {
return result;
} else {
return 1000 * usecs;
}
}
if (Bsd::supports_monotonic_clock()) {
// CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
} else {
// gettimeofday - based on time in seconds since the Epoch thus does not wrap
// gettimeofday is a real time clock so it skips
info_ptr->may_skip_backward = true;
info_ptr->may_skip_forward = true;
}
}
// Return the real, user, and system times in seconds from an
// arbitrary fixed point in the past.
double* process_user_time,
double* process_system_time) {
return false;
} else {
double ticks_per_second = (double) clock_tics_per_sec;
return true;
}
}
struct tm t;
localtime_r(&long_time, &t);
return buf;
}
}
////////////////////////////////////////////////////////////////////////////////
// runtime exit support
// Note: os::shutdown() might be called very early during initialization, or
// called from signal handler. Before adding something to os::shutdown(), make
// sure it is async-safe and can handle partially initialized VM.
// allow PerfMemory to attempt cleanup of any persistent resources
// needs to remove object in file system
AttachListener::abort();
// flush buffered output, finish log files
// Check for abort hook
if (abort_hook != NULL) {
abort_hook();
}
}
// Note: os::abort() might be called very early during initialization, or
// called from signal handler. Before adding something to os::abort(), make
// sure it is async-safe and can handle partially initialized VM.
if (dump_core) {
#ifndef PRODUCT
char buf[16];
#endif
::abort(); // dump core
}
::exit(1);
}
// Die immediately, no exit hook, no abort hook, no cleanup.
// _exit() on BsdThreads only kills current thread
::abort();
}
// unused on bsd for now.
// This method is a copy of JDK's sysGetLastErrorString
// from src/solaris/hpi/src/system_md.c
if (errno == 0) return 0;
if (n >= len) {
n = len - 1;
}
buf[n] = '\0';
return n;
}
#ifdef __APPLE__
return (intx)::mach_thread_self();
#else
return (intx)::pthread_self();
#endif
}
int os::current_process_id() {
// Under the old bsd thread library, bsd gives each thread
// its own process id. Because of this each thread will return
// a different pid if this method were to return the result
// of getpid(2). Bsd provides no api that returns the pid
// of the launcher thread for the vm. This implementation
// returns a unique pid, the pid of the launcher thread
// that starts the vm 'process'.
// Under the NPTL, getpid() returns the same pid as the
// launcher thread rather than a unique pid per thread.
// Use gettid() if you want the old pre NPTL behaviour.
// if you are looking for the result of a call to getpid() that
// returns a unique pid for the calling thread, then look at the
// OSThread::thread_id() method in osThread_bsd.hpp file
}
// DLL functions
#define JNI_LIB_PREFIX "lib"
#ifdef __APPLE__
#define JNI_LIB_SUFFIX ".dylib"
#else
#define JNI_LIB_SUFFIX ".so"
#endif
// This must be hard coded because it's the system's temporary
// directory not the java application's temp directory, ala java.io.tmpdir.
#ifdef __APPLE__
// macosx has a secure per-user temporary directory
char temp_path_storage[PATH_MAX];
const char* os::get_temp_directory() {
}
}
return temp_path;
}
#else /* __APPLE__ */
#endif /* __APPLE__ */
static bool file_exists(const char* filename) {
return false;
}
}
// Copied from libhpi
// Quietly truncate on buffer overflow. Should be an error.
*buffer = '\0';
return;
}
if (pnamelen == 0) {
int n;
for (int i = 0 ; i < n ; i++) {
// Really shouldn't be NULL, but check can't hurt
continue; // skip the empty path values
}
if (file_exists(buffer)) {
break;
}
}
// release the storage
for (int i = 0 ; i < n ; i++) {
}
}
}
} else {
}
}
}
// check if addr is inside libjvm[_g].so
static address libjvm_base_addr;
if (libjvm_base_addr == NULL) {
}
}
return false;
}
#define MACH_MAXSYMLEN 256
char localbuf[MACH_MAXSYMLEN];
// dladdr will find names of dynamic functions only, but does
// it set dli_fbase with mach_header address when it "fails" ?
}
}
return true;
return true;
}
}
// Handle non-dymanic manually:
}
return true;
}
return false;
}
#ifdef _ALLBSD_SOURCE
// ported from solaris version
return true;
} else {
return false;
}
}
#else
struct _address_to_library_name {
char* fname; // output: library name
};
int i;
bool found = false;
// iterate through all loadable segments
for (i = 0; i < info->dlpi_phnum; i++) {
// base address of a library is the lowest address of its loaded
// segments.
}
// see if 'addr' is within current segment
found = true;
}
}
}
// dlpi_name is NULL or empty if the ELF file is executable, return 0
// so dll_address_to_library_name() can fall through to use dladdr() which
// can figure out executable name from argv[0].
if (d->fname) {
}
return 1;
}
return 0;
}
struct _address_to_library_name data;
// There is a bug in old glibc dladdr() implementation that it could resolve
// to wrong library name if the .so file has a base address != NULL. Here
// we iterate through the program headers of all loaded libraries to find
// out which library 'addr' really belongs to. This workaround can be
// removed once the minimum requirement for glibc is moved to 2.3.x.
if (rslt) {
// buf already contains library name
return true;
return true;
} else {
return false;
}
}
#endif
// Loads .dll/.so and
// in case of error it checks if .dll/.so was built for the
// same architecture as Hotspot is running on
#ifdef __APPLE__
// Successful loading
return result;
}
// Read system error message into ebuf
return NULL;
}
#else
{
// Successful loading
return result;
}
// Read system error message into ebuf
// It may or may not be overwritten below
if (diag_msg_max_length==0) {
// No more space in ebuf for additional diagnostics message
return NULL;
}
if (file_descriptor < 0) {
// Can't open library, report dlerror() message
return NULL;
}
bool failed_to_read_elf_head=
(sizeof(elf_head)!=
::close(file_descriptor);
if (failed_to_read_elf_head) {
// file i/o error - report dlerror() msg
return NULL;
}
typedef struct {
char elf_class; // 32 or 64 bit
char endianess; // MSB or LSB
char* name; // String representation
} arch_t;
#ifndef EM_486
#endif
#ifndef EM_MIPS_RS3_LE
#endif
#ifndef EM_PPC64
#endif
#ifndef EM_S390
#endif
#ifndef EM_IA_64
#endif
#ifndef EM_X86_64
#endif
static const arch_t arch_array[]={
};
#if (defined IA32)
#elif (defined __powerpc64__)
#elif (defined __powerpc__)
#else
#endif
// Identify compatability class for VM's architecture and library's architecture
// Obtain string descriptions for architectures
int running_arch_index=-1;
for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
running_arch_index = i;
}
}
}
"Didn't find running architecture code (running_arch_code) in arch_array");
if (running_arch_index == -1) {
// Even though running architecture detection failed
// we may still continue with reporting dlerror() message
return NULL;
}
return NULL;
}
#ifndef S390
::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
return NULL;
}
#endif // !S390
" (Possible cause: can't load %s-bit .so on a %s-bit platform)",
} else {
" (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
}
}
return NULL;
}
#endif /* !__APPLE__ */
// XXX: Do we need a lock around this as per Linux?
}
if (fd == -1) {
return false;
}
char buf[32];
int bytes;
}
return true;
}
#ifdef _ALLBSD_SOURCE
#ifdef RTLD_DI_LINKMAP
void *handle;
Link_map *p;
return;
}
return;
}
return;
}
}
uint32_t i;
count = _dyld_image_count();
for (i = 1; i < count; i++) {
const char *name = _dyld_get_image_name(i);
}
#else
#endif
#else
char fname[32];
}
#endif
}
}
}
// Nothing to do for now.
}
#ifndef _ALLBSD_SOURCE
// values in struct sysinfo are "unsigned long"
#endif
#ifndef _ALLBSD_SOURCE
#endif
// meminfo
}
// but they're the same for all the bsd arch that we support
// and they're the same for solaris but there's no common place to put this.
"ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
"ILL_COPROC", "ILL_BADSTK" };
"FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
"FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
const int buflen = 100;
} else {
}
assert(c > 0, "unexpected si_code");
case SIGILL:
break;
case SIGFPE:
break;
case SIGSEGV:
break;
case SIGBUS:
break;
default:
// no si_addr
}
" Mapped file inaccessible during execution, " \
}
}
}
}
static char saved_jvm_path[MAXPATHLEN] = {0};
// Find the full path to the current module, libjvm or libjvm_g
// Error checking.
if (buflen < MAXPATHLEN) {
assert(false, "must use a large-enough buffer");
buf[0] = '\0';
return;
}
// Lazy resolve the path to current module.
if (saved_jvm_path[0] != 0) {
return;
}
char dli_fname[MAXPATHLEN];
bool ret = dll_address_to_library_name(
return;
if (Arguments::created_by_gamma_launcher()) {
// Support for the gamma launcher. Typical value for buf is
// the right place in the string, then assume we are installed in a JDK and
// we're done. Otherwise, check for a JAVA_HOME environment variable and
// construct a path to the JVM being overridden.
for (--p; p > buf && *p != '/'; --p)
/* empty */ ;
}
// Look for JAVA_HOME in the environment.
char* jrelib_p;
int len;
// Check the current module name "libjvm" or "libjvm_g".
return;
// determine if this is a legacy image or modules image
// modules image doesn't have "jre" subdirectory
// Add the appropriate library subdir
}
// Add the appropriate client or server subdir
}
// If the path exists within JAVA_HOME, add the JVM library name
// to complete the path to JVM being overridden. Otherwise fallback
// to the path to the current library.
// Use current module name "libjvm[_g]" instead of
// "libjvm"debug_only("_g")"" since for fastdebug version
// we should have "libjvm" but debug_only("_g") adds "_g"!
} else {
// Fall back to path of current library
return;
}
}
}
}
}
// no prefix required, not even "_"
}
// no suffix required
}
////////////////////////////////////////////////////////////////////////////////
// sun.misc.Signal support
static volatile jint sigint_count = 0;
static void
// 4511530 - sem_post is serialized and handled by the manager thread. When
// the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
// don't want to flood the manager thread with sem_post requests.
return;
// Ctrl-C is pressed during error reporting, likely because the error
// handler fails to abort. Let VM die immediately.
}
}
void* os::user_handler() {
return CAST_FROM_FN_PTR(void*, UserHandler);
}
extern "C" {
typedef void (*sa_handler_t)(int);
typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
}
// -1 means registration failed
return (void *)-1;
}
}
::raise(signal_number);
}
/*
* The following code is moved from os.cpp for making this
* code platform specific, which it is by its very nature.
*/
// Will be modified when max signal is changed to be dynamic
int os::sigexitnum_pd() {
return NSIG;
}
// a counter for each possible signal value
// Bsd(POSIX) specific hand shaking semaphore.
#ifdef __APPLE__
typedef semaphore_t os_semaphore_t;
#else
typedef sem_t os_semaphore_t;
#endif
public:
Semaphore();
~Semaphore();
void signal();
void wait();
bool trywait();
private:
jlong currenttime() const;
};
SEM_INIT(_semaphore, 0);
}
}
}
}
}
#ifdef __APPLE__
return timedwait(0, 0);
}
while (kr == KERN_ABORTED) {
if (passedtime >= totalwait) {
} else {
}
}
return kr == KERN_SUCCESS;
}
#else
return sem_trywait(&_semaphore) == 0;
}
while (1) {
if (result == 0) {
return true;
continue;
return false;
} else {
return false;
}
}
}
#endif // __APPLE__
static os_semaphore_t sig_sem;
static Semaphore sr_semaphore;
void os::signal_init_pd() {
// Initialize signal structures
// Initialize signal semaphore
}
}
static int check_pending_signals(bool wait) {
for (;;) {
for (int i = 0; i < NSIG + 1; i++) {
jint n = pending_signals[i];
return i;
}
}
if (!wait) {
return -1;
}
bool threadIsSuspended;
do {
// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
// were we externally suspended while we were waiting?
if (threadIsSuspended) {
//
// The semaphore has been incremented, but while we were waiting
// another thread suspended us. We don't want to continue running
// while suspended because that would surprise the thread that
// suspended us.
//
}
} while (threadIsSuspended);
}
}
int os::signal_lookup() {
return check_pending_signals(false);
}
int os::signal_wait() {
return check_pending_signals(true);
}
////////////////////////////////////////////////////////////////////////////////
// Virtual Memory
int os::vm_page_size() {
// Seems redundant as all get out
}
// Solaris allocates memory by pages.
int os::vm_allocation_granularity() {
}
// Rationale behind this function:
// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
// samples for JITted code. Here we create private executable mapping over the code cache
// and then we can use standard (well, almost, as mapping can change) way to provide
// info for the reporting script by storing timestamp and location of symbol
if (!UseOprofile) {
return;
}
if (fd != -1) {
}
}
}
}
// NOTE: Bsd kernel does not really reserve the pages for us.
// All it does is to check if there are enough free pages
// left at the time of mmap(). This could be a potential
// problem.
#ifdef __OpenBSD__
#else
#endif
}
#ifndef _ALLBSD_SOURCE
// Define MAP_HUGETLB here so we can build HotSpot on old systems.
#ifndef MAP_HUGETLB
#define MAP_HUGETLB 0x40000
#endif
// Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
#ifndef MADV_HUGEPAGE
#define MADV_HUGEPAGE 14
#endif
#endif
bool exec) {
#ifndef _ALLBSD_SOURCE
-1, 0);
}
#endif
}
#ifndef _ALLBSD_SOURCE
// We don't check the return value: madvise(MADV_HUGEPAGE) may not
// be supported or the memory may already be backed by huge pages.
}
#endif
}
}
}
}
bool os::numa_topology_changed() { return false; }
return 1;
}
int os::numa_get_group_id() {
return 0;
}
if (size > 0) {
ids[0] = 0;
return 1;
}
return 0;
}
return false;
}
return end;
}
#ifndef _ALLBSD_SOURCE
// Something to do with the numa-aware allocator needs these symbols
// If we are running with libnuma version > 2, then we should
// be trying to use symbols with versions 1.1
// If we are running with earlier version, which did not have symbol versions,
// we should use the base version.
if (f == NULL) {
}
return f;
}
// sched_getcpu() should be in libc.
if (numa_available() != -1) {
// Create a cpu -> node mapping
return true;
}
}
}
return false;
}
// rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
// The table is later used in get_node_by_cpu().
// in libnuma (possible values are starting from 16,
// and continuing up with every other power of 2, but less
// than the maximum number of CPUs supported by kernel), and
// is a subject to change (in libnuma version 2 the requirements
// are more reasonable) we'll just hardcode the number they use
// in the library.
cpu_to_node()->clear();
for (size_t j = 0; j < cpu_map_valid_size; j++) {
if (cpu_map[j] != 0) {
for (size_t k = 0; k < BitsPerCLong; k++) {
if (cpu_map[j] & (1UL << k)) {
}
}
}
}
}
}
FREE_C_HEAP_ARRAY(unsigned long, cpu_map);
}
}
return -1;
}
#endif
#ifdef __OpenBSD__
#else
#endif
}
}
// If this is a growable mapping, remove the guard pages entirely by
// munmap()ping them. If not, just call uncommit_memory().
}
// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
// at 'requested_addr'. If there are existing memory mappings at the same
// location, however, they will be overwritten. If 'fixed' is false,
// 'requested_addr' is only treated as a hint, the return value may or
// may not start from the requested address. Unlike Bsd mmap(), this
// function returns NULL to indicate failure.
char * addr;
int flags;
if (fixed) {
}
// Map uncommitted pages PROT_READ and PROT_WRITE, change access
// to PROT_EXEC if executable when we commit the page.
flags, -1, 0);
if (addr != MAP_FAILED) {
// anon_mmap() should only get called during VM initialization,
// don't need lock (actually we can skip locking even it can be called
// from multiple threads, because _highest_vm_reserved_address is just a
// hint about the upper limit of non-stack memory regions.)
}
}
}
// Don't update _highest_vm_reserved_address, because there might be memory
// regions above addr + size. If so, releasing a memory region only creates
// a hole in the address space, it doesn't help prevent heap-stack collision.
//
}
}
}
static address highest_vm_reserved_address() {
return _highest_vm_reserved_address;
}
// Bsd wants the mprotect address argument to be page aligned.
// According to SUSv3, mprotect() should only be used with mappings
// established by mmap(), and mmap() always maps whole pages. Unaligned
// 'addr' likely indicates problem in the VM (e.g. trying to change
// protection of malloc'ed or statically allocated memory). Check the
// caller if you hit this assert.
}
// Set protections specified
bool is_committed) {
unsigned int p = 0;
switch (prot) {
case MEM_PROT_NONE: p = PROT_NONE; break;
case MEM_PROT_READ: p = PROT_READ; break;
default:
}
// is_committed is unused.
}
}
}
bool result = false;
#ifndef _ALLBSD_SOURCE
-1, 0);
if (p != (void *) -1) {
// We don't know if this really is a huge page or not.
if (fp) {
char chars[257];
long x = 0;
&& x == (long)p) {
result = true;
break;
}
}
}
}
}
if (result)
return true;
}
if (warn) {
warning("HugeTLBFS is not supported by the operating system.");
}
#endif
return result;
}
/*
* Set the coredump_filter bits to include largepages in core dump (bit 6)
*
* From the coredump_filter documentation:
*
* - (bit 0) anonymous private memory
* - (bit 1) anonymous shared memory
* - (bit 2) file-backed private memory
* - (bit 3) file-backed shared memory
* - (bit 4) ELF header pages in file-backed private memory areas (it is
* effective only if the bit 2 is cleared)
* - (bit 5) hugetlb private memory
* - (bit 6) hugetlb shared memory
*/
static void set_coredump_filter(void) {
FILE *f;
long cdm;
return;
}
fclose(f);
return;
}
rewind(f);
if ((cdm & LARGEPAGES_BIT) == 0) {
cdm |= LARGEPAGES_BIT;
}
fclose(f);
}
// Large page support
static size_t _large_page_size = 0;
void os::large_page_init() {
#ifndef _ALLBSD_SOURCE
if (!UseLargePages) {
UseHugeTLBFS = false;
UseSHM = false;
return;
}
// If UseLargePages is specified on the command line try both methods,
// if it's default, then try only HugeTLBFS.
if (FLAG_IS_DEFAULT(UseLargePages)) {
UseHugeTLBFS = true;
} else {
UseHugeTLBFS = UseSHM = true;
}
}
if (LargePageSizeInBytes) {
} else {
// large_page_size on Bsd is used to round up heap size. x86 uses either
// 2M or 4M page, depending on whether PAE (Physical Address Extensions)
// page as large as 256M.
//
// for a line with the following format:
// Hugepagesize: 2048 kB
//
// If we can't determine the value (e.g. /proc is not mounted, or the text
// format has been changed), we'll use the largest page size supported by
// the processor.
#ifndef ZERO
#endif // ZERO
if (fp) {
int x = 0;
char buf[16];
_large_page_size = x * K;
break;
}
} else {
// skip to next line
for (;;) {
}
}
}
}
}
// print a warning if any large page related flag is specified on command line
if (_large_page_size > default_page_size) {
_page_sizes[0] = _large_page_size;
_page_sizes[2] = 0;
}
UseHugeTLBFS = UseHugeTLBFS &&
if (UseHugeTLBFS)
UseSHM = false;
#endif
}
#ifndef _ALLBSD_SOURCE
#ifndef SHM_HUGETLB
#define SHM_HUGETLB 04000
#endif
#endif
// "exec" is passed in but not used. Creating the shared image for
// the code cache doesn't have an SHM_X executable permission to check.
char *addr;
bool warn_on_failure = UseLargePages &&
(!FLAG_IS_DEFAULT(UseLargePages) ||
);
char msg[128];
// Create a large shared memory region to attach to based on size.
// Currently, size is the total size of the heap
#ifndef _ALLBSD_SOURCE
#else
#endif
if (shmid == -1) {
// Possible reasons for shmget failure:
// 1. shmmax is too small for Java heap.
// 2. not enough large page memory.
// > increase amount of large pages:
// echo new_value > /proc/sys/vm/nr_hugepages
// Note 1: different Bsd may use different name for this property,
// e.g. on Redhat AS-3 it is "hugetlb_pool".
// Note 2: it's possible there's enough physical memory available but
// they are so fragmented after a long run that they can't
// coalesce into large pages. Try to reserve large pages when
// the system is still "fresh".
if (warn_on_failure) {
}
return NULL;
}
// attach to the region
// Remove shmid. If shmat() is successful, the actual shared memory segment
// will be deleted when it's detached by shmdt() or when the process
// terminates. If shmat() is not successful this will remove the shared
// segment immediately.
if (warn_on_failure) {
}
return NULL;
}
// The memory is committed
return addr;
}
// detaching the SHM segment will also delete it, see reserve_memory_special()
if (rslt == 0) {
return true;
} else {
return false;
}
}
return _large_page_size;
}
// HugeTLBFS allows application to commit large page memory on demand;
// with SysV SHM the entire memory region must be allocated as shared
// memory.
bool os::can_commit_large_page_memory() {
return UseHugeTLBFS;
}
bool os::can_execute_large_page_memory() {
return UseHugeTLBFS;
}
// Reserve memory at an arbitrary address, only if that area is
// available (and not reserved for something else).
const int max_tries = 10;
// Assert only that the size is a multiple of the page size, since
// that's all that mmap requires, and since that's all we really know
// about at this low abstraction level. If we need higher alignment,
// we can either pass an alignment to this method or verify alignment
// in one of the methods further up the call chain. See bug 5044738.
// Repeatedly allocate blocks until the block is allocated at the
// right spot. Give up after max_tries. Note that reserve_memory() will
// automatically update _highest_vm_reserved_address if the call is
// successful. The variable tracks the highest memory address every reserved
// by JVM. It is used to detect heap-stack collision if running with
// fixed-stack BsdThreads. Because here we may attempt to reserve more
// space than needed, it could confuse the collision detecting code. To
// solve the problem, save current _highest_vm_reserved_address and
// calculate the correct value before return.
// Bsd mmap allows caller to pass an address as hint; give it a try first,
// if kernel honors the hint then we can return immediately.
if (addr == requested_addr) {
return requested_addr;
}
// mmap() is successful but it fails to reserve at the requested address
}
int i;
for (i = 0; i < max_tries; ++i) {
// Is this the block we wanted?
if (base[i] == requested_addr) {
break;
}
// Does this overlap the block we wanted? Give back the overlapped
// parts and try again.
base[i] += top_overlap;
} else {
} else {
}
}
}
}
// Give back the unused reserved pieces.
for (int j = 0; j < i; ++j) {
}
}
if (i < max_tries) {
return requested_addr;
} else {
return NULL;
}
}
}
// TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
// Solaris uses poll(), bsd uses park().
// Poll() is likely a better choice, assuming that Thread.interrupt()
// generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
// SIGSEGV, see 4355769.
OrderAccess::fence() ;
if (interruptible) {
for (;;) {
return OS_INTRPT;
}
// time moving backwards, should only happen if no monotonic clock
} else {
}
if(millis <= 0) {
return OS_OK;
}
{
// cleared by handle_special_suspend_equivalent_condition() or
// java_suspend_self() via check_and_wait_while_suspended()
// were we externally suspended while we were waiting?
}
}
} else {
for (;;) {
// It'd be nice to avoid the back-to-back javaTimeNanos() calls on
// the 1st iteration ...
// time moving backwards, should only happen if no monotonic clock
} else {
}
if(millis <= 0) break ;
}
return OS_OK ;
}
}
int os::naked_sleep() {
// %% make the sleep time an integer flag. for now use 1 millisec.
}
// Sleep forever; naked call to OS-specific sleep; use with CAUTION
void os::infinite_sleep() {
while (true) { // sleep forever ...
}
}
// Used to convert frequent JVM_Yield() to nops
bool os::dont_yield() {
return DontYieldALot;
}
sched_yield();
}
// Yields to all threads, including threads with lower priorities
// Threads on Bsd are all with same priority. The Solaris style
// os::yield_all() with nanosleep(1ms) is not necessary.
sched_yield();
}
// Called from the tight loops to possibly influence time-sharing heuristics
}
////////////////////////////////////////////////////////////////////////////////
// thread priority support
// Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
// only supports dynamic priority, static priority must be zero. For real-time
// applications, Bsd supports SCHED_RR which allows static priority (1-99).
// However, for large multi-threaded applications, SCHED_RR is not only slower
// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
// of 5 runs - Sep 2005).
//
// The following code actually changes the niceness of kernel-thread/LWP. It
// has an assumption that setpriority() only modifies one kernel-thread/LWP,
// not the entire user process, and user level threads are 1:1 mapped to kernel
// threads. It has always been the case, but could change in the future. For
// this reason, the code should not be used as default (ThreadPriorityPolicy=0).
// It is only used when ThreadPriorityPolicy=1 and requires root privilege.
#if defined(_ALLBSD_SOURCE) && !defined(__APPLE__)
19, // 0 Entry should never be used
0, // 1 MinPriority
3, // 2
6, // 3
10, // 4
15, // 5 NormPriority
18, // 6
21, // 7
25, // 8
28, // 9 NearMaxPriority
31, // 10 MaxPriority
31 // 11 CriticalPriority
};
/* Using Mach high-level priority assignments */
0, // 0 Entry should never be used (MINPRI_USER)
27, // 1 MinPriority
28, // 2
29, // 3
30, // 4
31, // 5 NormPriority (BASEPRI_DEFAULT)
32, // 6
33, // 7
34, // 8
35, // 9 NearMaxPriority
36, // 10 MaxPriority
36 // 11 CriticalPriority
};
#else
19, // 0 Entry should never be used
4, // 1 MinPriority
3, // 2
2, // 3
1, // 4
0, // 5 NormPriority
-1, // 6
-2, // 7
-3, // 8
-4, // 9 NearMaxPriority
-5, // 10 MaxPriority
-5 // 11 CriticalPriority
};
#endif
static int prio_init() {
if (ThreadPriorityPolicy == 1) {
// Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
// if effective uid is not root. Perhaps, a more elegant way of doing
// this is to test CAP_SYS_NICE capability, but that will require libcap.so
if (geteuid() != 0) {
if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
}
ThreadPriorityPolicy = 0;
}
}
}
return 0;
}
#ifdef __OpenBSD__
// OpenBSD pthread_setprio starves low priority threads
return OS_OK;
#elif defined(__FreeBSD__)
struct sched_param sp;
int policy;
return OS_ERR;
return OS_ERR;
return OS_OK;
#else
#endif
}
if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
return OS_OK;
}
errno = 0;
#if defined(__OpenBSD__) || defined(__FreeBSD__)
int policy;
struct sched_param sp;
#else
#endif
}
// Hint to the underlying OS that a task switch would not be good.
// Void return because it's a hint and can fail.
void os::hint_no_preempt() {}
////////////////////////////////////////////////////////////////////////////////
// old VM-suspension that used to be for java-suspension, safepoints etc,
// within hotspot. Now there is a single use-case for this:
// - calling get_thread_pc() on the VMThread by the flat-profiler task
// that runs in the watcher thread.
// The remaining code is greatly simplified from the more general suspension
// code that used to be used.
//
// The protocol is quite simple:
// - suspend:
// - sends a signal to the target thread
// - polls the suspend state of the osthread using a yield loop
// - target thread signal handler (SR_handler) sets suspend state
// and blocks in sigsuspend until continued
// - resume:
// - sets target osthread state to continue
// - sends signal to end the sigsuspend loop in the SR_handler
//
//
}
}
//
// Handler function invoked when a thread's execution is suspended or
// resumed. We have to be careful that only async-safe functions are
// called here (Note: most pthread functions are not async safe and
// should be avoided.)
//
// Note: sigwait() is a more natural fit than sigsuspend() from an
// interface point of view, but sigwait() prevents the signal hander
// from being run. libpthread would get very confused by not having
// its signal handlers run and prevents sigwait()'s use with the
// mutex granting granting signal.
//
// Currently only ever called on the VMThread or JavaThread
//
// Save and restore errno to avoid confusing native code with EINTR
// after sigsuspend.
// attempt to switch the state, we assume we had a SUSPEND_REQUEST
// get current set of blocked signals and unblock resume signal
// wait here until we are resumed
while (1) {
break;
}
}
// request was cancelled, continue
} else {
}
// request was cancelled, continue
// ignore
} else {
// ignore
}
}
static int SR_initialize() {
char *s;
if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
}
}
"SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
// SR_signum is blocked by default.
// 4528190 - We also need to block pthread restart signal (32 on all
// supported Bsd platforms). Note that BsdThreads need to block
// this signal for all threads to work properly. So we don't have
// to use hard-coded signal number when setting up the mask.
return -1;
}
// Save signal flag
return 0;
}
static int SR_finalize() {
return 0;
}
return status;
}
// "Randomly" selected value for how long we want to spin
// before bailing out on suspending a thread, also how often
// we send a signal to a thread we want to resume
static const int RANDOMLY_LARGE_INTEGER = 1000000;
static const int RANDOMLY_LARGE_INTEGER2 = 100;
// returns true on success and false on error - really an error is fatal
// but this seems the normal response to library errors
// mark as suspended and send signal
// failed to switch, state wasn't running?
return false;
}
}
// managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
while (true) {
break;
} else {
// timeout
return false;
// make sure that we consume the signal on the semaphore as well
sr_semaphore.wait();
break;
} else {
return false;
}
}
}
return true;
}
// failed to switch to WAKEUP_REQUEST
return;
}
while (true) {
return;
}
}
} else {
}
}
}
////////////////////////////////////////////////////////////////////////////////
// interrupt support
"possibility of dangling Thread pointer");
if (!osthread->interrupted()) {
osthread->set_interrupted(true);
// More than one thread can get here with the same value of osthread,
// resulting in multiple notifications. We do, however, want the store
// to interrupted() to be visible to other threads before we execute unpark().
OrderAccess::fence();
}
// For JSR166. Unpark even if interrupt status already was set
if (thread->is_Java_thread())
}
"possibility of dangling Thread pointer");
if (interrupted && clear_interrupted) {
osthread->set_interrupted(false);
// consider thread->_SleepEvent->reset() ... optional optimization
}
return interrupted;
}
///////////////////////////////////////////////////////////////////////////////////
// This routine may be used by user applications as a "hook" to catch signals.
// The user-defined signal handler must pass unrecognized signals to this
// routine, and if it returns true (non-zero), then the signal handler must
// return immediately. If the flag "abort_if_unrecognized" is true, then this
// routine will never retun false (zero), but instead will execute a VM panic
// routine kill the process.
//
// If this routine returns false, it is OK to call it again. This allows
// the user-defined signal handler to perform checks either before or after
// the VM performs its own checks. Naturally, the user code would be making
// a serious error if it tried to handle an exception (such as a null check
// or breakpoint) that the VM was generating for its own correct operation.
//
// This routine may recognize any of the following kinds of signals:
// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
// It should be consulted by handlers for any of those signals.
//
// The caller of this routine must pass in the three arguments supplied
// to the function referred to in the "sa_sigaction" (not the "sa_handler")
// field of the structure passed to sigaction(). This routine assumes that
// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
//
// Note that the VM will print warnings if it detects conflicting signal
// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
//
extern "C" JNIEXPORT int
void* ucontext, int abort_if_unrecognized);
}
// This boolean allows users to forward their own non-matching signals
// to JVM_handle_bsd_signal, harmlessly.
// For signal-chaining
typedef struct sigaction *(*get_signal_t)(int);
if (libjsig_is_loaded) {
// Retrieve the old signal handler from libjsig
}
// Retrieve the preinstalled signal handler from jvm
}
return actp;
}
// Call the old signal handler
// It's more reasonable to let jvm treat it as an unexpected exception
// instead of taking the default action.
return false;
// automaticlly block the signal
}
// retrieve the chained handler
if (siginfo_flag_set) {
} else {
}
}
// try to honor the signal mask
// call into the chained handler
if (siginfo_flag_set) {
} else {
}
// restore the signal mask
}
// Tell jvm's signal handler the signal is taken care of.
return true;
}
bool chained = false;
// signal-chaining
if (UseSignalChaining) {
}
}
return chained;
}
}
return NULL;
}
}
// for diagnostic
}
}
// Check for overwrite.
if (AllowUserSignalHandlers || !set_installed) {
// Do not overwrite; user takes responsibility to forward to us.
return;
} else if (UseSignalChaining) {
// save the old handler in jvm
// libjsig also interposes the sigaction() call below and saves the
// old sigaction on it own.
} else {
}
}
if (!set_installed) {
} else {
}
#if __APPLE__
// Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
// (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
// if the signal handler declares it will handle it on alternate stack.
// Notice we only declare we will handle it on alt stack, but we are not
// actually going to use real alt stack - this is just a workaround.
// Please see ux_exception.c, method catch_mach_exception_raise for details
}
#endif
// Save flags, which are set by ours
}
// install signal handlers for signals that HotSpot needs to
// handle in order to support Java-level exception handling.
if (!signal_handlers_are_installed) {
signal_handlers_are_installed = true;
// signal-chaining
typedef void (*signal_setting_t)();
if (begin_signal_setting != NULL) {
libjsig_is_loaded = true;
}
if (libjsig_is_loaded) {
// Tell libjsig jvm is setting signal handlers
(*begin_signal_setting)();
}
set_signal_handler(SIGSEGV, true);
set_signal_handler(SIGPIPE, true);
set_signal_handler(SIGBUS, true);
set_signal_handler(SIGILL, true);
set_signal_handler(SIGFPE, true);
set_signal_handler(SIGXFSZ, true);
#if defined(__APPLE__)
// In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
// signals caught and handled by the JVM. To work around this, we reset the mach task
// signal handler that's placed on our process by CrashReporter. This disables
// CrashReporter-based reporting.
//
// This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
// on caught fatal signals.
//
// Additionally, gdb installs both standard BSD signal handlers, and mach exception
// handlers. By replacing the existing task exception handler, we disable gdb's mach
// exception handling, while leaving the standard BSD signal handlers functional.
#endif
if (libjsig_is_loaded) {
// Tell libjsig jvm finishes setting signal handlers
(*end_signal_setting)();
}
// We don't activate signal checker if libjsig is in place, we trust ourselves
// and if UserSignalHandler is installed all bets are off
if (CheckJNICalls) {
if (libjsig_is_loaded) {
check_signals = false;
}
if (AllowUserSignalHandlers) {
tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
check_signals = false;
}
}
}
}
#ifndef _ALLBSD_SOURCE
// This is the fastest way to get thread cpu time on Bsd.
// Returns cpu time (user+sys) for any thread, not only for current.
// POSIX compliant clocks are implemented in the kernels 2.6.16+.
// For reference, please, see IEEE Std 1003.1-2004:
}
#endif
/////
// glibc on Bsd platform uses non-documented flag
// to indicate, that some special sort of signal
// trampoline is used.
// We will never set this flag, and we should
// ignore this flag in our diagnostic
#ifdef SIGNIFICANT_SIGNAL_MASK
#endif
#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
int offset;
if (found) {
// skip directory names
} else {
}
return buf;
}
// See comment for SIGNIFICANT_SIGNAL_MASK define
} else {
}
// May be, handler was resetted by VMError?
}
// Check: is it our handler?
// It is our signal handler
// check for flags, reset system-used one!
}
}
}
#define DO_SIGNAL_CHECK(sig) \
// This method is a periodic task to check for misbehaving JNI applications
// under CheckJNI, we can add any periodic checks here
void os::run_periodic_checks() {
if (check_signals == false) return;
// SEGV and BUS if overridden could potentially prevent
// generation of hs*.log in the event of a crash, debugging
// such a case can be very challenging, so we absolutely
// check the following for a good measure:
// ReduceSignalUsage allows the user to override these handlers
// see comments at the very top and jvm_solaris.h
if (!ReduceSignalUsage) {
}
}
if (os_sigaction == NULL) {
// only trust the default sigaction, in case it has been interposed
if (os_sigaction == NULL) return;
}
switch(sig) {
case SIGSEGV:
case SIGBUS:
case SIGFPE:
case SIGPIPE:
case SIGILL:
case SIGXFSZ:
break;
case SHUTDOWN1_SIGNAL:
case SHUTDOWN2_SIGNAL:
case SHUTDOWN3_SIGNAL:
case BREAK_SIGNAL:
break;
case INTERRUPT_SIGNAL:
break;
default:
} else {
return;
}
break;
}
if (thisHandler != jvmHandler) {
// No need to check this sig any longer
} else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
// No need to check this sig any longer
}
// Dump all the signal
}
}
// signal
}
return buf;
} else {
return NULL;
}
}
// this is called _before_ the most of global arguments have been parsed
char dummy; /* used to get a guess on initial stack address */
// first_hrtime = gethrtime();
// With BsdThreads the JavaMain thread pid (primordial thread)
// is different than the pid of the java launcher thread.
// So, on Bsd, the launcher thread pid is passed to the VM
// via the sun.java.launcher.pid property.
// Use this property instead of getpid() if it was correctly passed.
// See bug 6351349.
init_random(1234567);
}
// main_thread points to the aboriginal thread
Bsd::clock_init();
#ifdef __APPLE__
// XXXDARWIN
// Work around the unaligned VM callbacks in hotspot's
// sharedRuntime. The callbacks don't use SSE2 instructions, and work on
// Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
// alignment when doing symbol lookup. To work around this, we force early
// binding of all symbols now, thus binding when alignment is known-good.
#endif
}
// To install functions for atexit system call
extern "C" {
static void perfMemory_exit_helper() {
}
}
// this is called _after_ the global arguments have been parsed
{
#ifndef _ALLBSD_SOURCE
#endif
// Allocate a single page and mark it as readable for safepoint polling
address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#ifndef PRODUCT
if(Verbose && PrintMiscellaneous)
#endif
if (!UseMembar) {
address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#ifndef PRODUCT
if(Verbose && PrintMiscellaneous)
#endif
}
os::large_page_init();
if (SR_initialize() != 0) {
perror("SR_initialize failed");
return JNI_ERR;
}
Bsd::signal_sets_init();
// Check minimum allowable stack size for thread creation and to initialize
// the java system classes, including StackOverflowError - depends on page
// size. Add a page for compiler2 recursion in main thread.
// Add in 2*BytesPerWord times page size to account for VM stack during
// class initialization depending on 32 or 64 bit VM.
if (threadStackSizeInBytes != 0 &&
"Specify at least %dk",
return JNI_ERR;
}
// Make the stack size a multiple of the page size so that
vm_page_size()));
#ifndef _ALLBSD_SOURCE
Bsd::libpthread_init();
}
if (UseNUMA) {
if (!Bsd::libnuma_init()) {
UseNUMA = false;
} else {
// There's only one node(they start from 0), disable NUMA.
UseNUMA = false;
}
}
// With SHM large pages we cannot uncommit a page, so there's not way
// we can make the adaptive lgrp chunk resizing work. If the user specified
// both UseNUMA and UseLargePages (or UseSHM) on the command line - warn and
// disable adaptive resizing.
if (!FLAG_IS_DEFAULT(UseNUMA)) {
UseLargePages = false;
} else {
warning("UseNUMA is not fully compatible with SHM large pages, disabling adaptive resizing");
UseAdaptiveSizePolicy = false;
UseAdaptiveNUMAChunkSizing = false;
}
} else {
UseNUMA = false;
}
}
UseNUMA = true;
}
}
#endif
if (MaxFDLimit) {
// set the number of file descriptors to max. print out error
if (status != 0) {
perror("os::init_2 getrlimit failed");
} else {
#ifdef __APPLE__
// Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
// you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
// be used instead
#endif
if (status != 0) {
perror("os::init_2 setrlimit failed");
}
}
}
#ifndef _ALLBSD_SOURCE
// Initialize lock used to serialize thread creation (see os::create_thread)
#endif
// at-exit methods are called in the reverse order of their registration.
// atexit functions are called on return from main or as a result of a
// call to exit(3C). There can be only 32 of these functions registered
// and atexit() does not set errno.
if (PerfAllowAtExitRegistration) {
// only register atexit functions if PerfAllowAtExitRegistration is set.
// atexit functions can be delayed until process exit time, which
// can be problematic for embedded VM situations. Embedded VMs should
// call DestroyJavaVM() to assure that VM resources are released.
// note: perfMemory_exit_helper atexit function may be removed in
// the future if the appropriate cleanup code can be added to the
// VM_Exit VMOperation's doit method.
if (atexit(perfMemory_exit_helper) != 0) {
warning("os::init2 atexit(perfMemory_exit_helper) failed");
}
}
// initialize thread priority policy
prio_init();
#ifdef __APPLE__
// dynamically link to objective c gc registration
if (handleLibObjc != NULL) {
objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
}
#endif
return JNI_OK;
}
// this is called at the end of vm_initialization
// Mark the polling page as unreadable
void os::make_polling_page_unreadable(void) {
fatal("Could not disable polling page");
};
// Mark the polling page as readable
void os::make_polling_page_readable(void) {
fatal("Could not enable polling page");
}
};
int os::active_processor_count() {
#ifdef _ALLBSD_SOURCE
return _processor_count;
#else
// Bsd doesn't yet have a (official) notion of processor sets,
// so just return the number of online processors.
return online_cpus;
#endif
}
// This is only supported in Snow Leopard and beyond
// Add a "Java: " prefix to the name
char buf[MAXTHREADNAMESIZE];
}
#endif
}
// Not yet implemented.
return false;
}
// Not yet implemented.
return false;
}
}
}
///
public:
ExtendedPC result();
protected:
private:
};
return _epc;
}
} else {
// NULL context is unexpected, double-check this is the VMThread
}
}
// Suspends the target using the signal mechanism and then grabs the PC before
// resuming the target. Used by the flat-profiler only
// Make sure that it is called by the watcher for the VMThread
}
int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
{
#ifdef _ALLBSD_SOURCE
#else
if (is_NPTL()) {
} else {
#ifndef IA64
// 6292965: BsdThreads pthread_cond_timedwait() resets FPU control
// word back to default 64bit precision if condvar is signaled. Java
// wants 53bit precision. Save and restore current value.
int fpu = get_fpu_control_word();
#endif // IA64
#ifndef IA64
#endif // IA64
return status;
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
// debug support
return x;
else if (x > y)
else
}
} else {
}
}
}
if (Verbose) {
// decode some bytes around the PC
}
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// misc
// This does not do anything on Bsd. This is basically a hook for being
// able to use structured exception handling (thread-local exception filters)
// on, e.g., Win32.
void
}
void os::print_statistics() {
}
int i;
char buf[16];
// Prevent process from exiting upon "read error" without consuming all CPU
}
return -1;
}
}
return true;
}
}
// Is a (classpath) directory empty?
/* Scan the directory */
bool result = true;
result = false;
}
}
return result;
}
// This code originates from JDK's sysOpen and open64_w
// from src/solaris/hpi/src/system_md.c
#ifndef O_DELETE
#define O_DELETE 0x10000
#endif
// Open a file. Unlink the file immediately after open returns
// if the specified oflag has the O_DELETE flag set.
return -1;
}
int fd;
//If the open succeeded, the file might still be a directory
{
if (ret != -1) {
return -1;
}
} else {
return -1;
}
}
/*
* All file descriptors that are opened in the JVM and not
* specifically destined for a subprocess should have the
* close-on-exec flag set. If we don't set it, then careless 3rd
* party native code might fork and exec without closing all
* appropriate file descriptors (e.g. as we do in closeDescriptors in
* UNIXProcess.c), and this in turn might:
*
* - cause end-of-file to fail to be detected on some file
* descriptors, resulting in mysterious hangs, or
*
* - might cause an fopen in the subprocess to fail on a system
* suffering from bug 1085341.
*
* (Yes, the default setting of the close-on-exec flag is a Unix
* design flaw)
*
* See:
* 1085341: 32-bit stdio routines should support file descriptors >255
* 4843136: (process) pipe file descriptor from Runtime.exec not being closed
* 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
*/
#ifdef FD_CLOEXEC
{
if (flags != -1)
}
#endif
if (o_delete != 0) {
}
return fd;
}
// create binary file, rewriting existing file if required
if (!rewrite_existing) {
}
}
// return current position of file pointer
}
// move file pointer to the specified offset
}
// This code originates from JDK's sysAvailable
// from src/solaris/hpi/src/native_threads/src/sys_api_td.c
int mode;
/*
* XXX: is the following call interruptible? If so, this might
* need to go through the INTERRUPT_IO() wrapper as for other
* blocking, interruptible calls in this file.
*/
int n;
*bytes = n;
return 1;
}
}
}
return 0;
return 0;
return 0;
}
return 1;
}
if (fd < 0)
return OS_OK;
int ret;
//%% note ioctl can return 0 when successful, JVM_SocketAvailable
// is expected to return 0 on failure and 1 on success to the jdk.
}
// Map a block of memory.
bool allow_exec) {
int prot;
int flags;
if (read_only) {
flags = MAP_SHARED;
} else {
flags = MAP_PRIVATE;
}
if (allow_exec) {
}
}
fd, file_offset);
if (mapped_address == MAP_FAILED) {
return NULL;
}
return mapped_address;
}
// Remap a block of memory.
bool allow_exec) {
// same as map_memory() on this OS
}
// Unmap a block of memory.
}
#ifndef _ALLBSD_SOURCE
// Get thread clockid
return clockid;
}
#endif
// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
// are used by JVM M&M and JVMTI to get user+sys or user CPU time
// of a thread.
//
// current_thread_cpu_time() and thread_cpu_time(Thread*) returns
// the fast estimate available on the platform.
#ifdef __APPLE__
#elif !defined(_ALLBSD_SOURCE)
} else {
// return user + sys since the cost is the same
}
#endif
}
#ifndef _ALLBSD_SOURCE
// consistent with what current_thread_cpu_time() returns
} else {
}
#endif
}
#ifdef __APPLE__
#elif !defined(_ALLBSD_SOURCE)
} else {
}
#endif
}
#ifdef __APPLE__
struct thread_basic_info tinfo;
if (kr != KERN_SUCCESS)
return -1;
if (user_sys_cpu_time) {
nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
return nanos;
} else {
return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
}
#elif !defined(_ALLBSD_SOURCE)
} else {
}
#endif
}
#ifndef _ALLBSD_SOURCE
//
// -1 on error.
//
static bool proc_pid_cpu_avail = true;
static bool proc_task_unchecked = true;
static const char *proc_stat_path = "/proc/%d/stat";
int i;
char *s;
char stat[2048];
int statlen;
char proc_name[64];
int count;
char string[64];
char cdummy;
int idummy;
long ldummy;
// We first try accessing /proc/<pid>/cpu since this is faster to
// process. If this file is not present (bsd kernels 2.5 and above)
// then we open /proc/<pid>/stat.
if ( proc_pid_cpu_avail ) {
if (user_sys_cpu_time) {
} else {
}
}
else proc_pid_cpu_avail = false;
}
// The /proc/<tid>/stat aggregates per-process usage on
// new Bsd kernels 2.6+ where NPTL is supported.
// See bug 6328462.
// and possibly in some other cases, so we check its availability.
// This is executed only once
proc_task_unchecked = false;
}
}
// Skip pid and the command string. Note that we could be dealing with
// weird command names, e.g. user could decide to rename java launcher
// to "java 1.4.2 :)", then the stat file would look like
// 1234 (java 1.4.2 :)) R ... ...
// We don't really need to know the command string, just find the last
// occurrence of ")" and then start parsing from there. See bug 4726580.
i = 0;
if (s == NULL ) return -1;
// Skip blank chars
do s++; while (isspace(*s));
if (user_sys_cpu_time) {
} else {
}
}
#endif
}
}
bool os::is_thread_cpu_time_supported() {
#ifdef __APPLE__
return true;
#elif defined(_ALLBSD_SOURCE)
return false;
#else
return true;
#endif
}
// System loadavg support. Returns -1 if load average cannot be obtained.
// Bsd doesn't yet have a (official) notion of processor sets,
// so just return the system wide load average.
}
if (PauseAtStartupFile && PauseAtStartupFile[0]) {
} else {
}
if (fd != -1) {
}
} else {
"Could not open pause file '%s', continuing immediately.\n", filename);
}
}
// Refer to the comments in os_solaris.cpp park-unpark.
//
// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
// hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
// For specifics regarding the bug see GLIBC BUGID 261237 :
// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
// is used. (The simple C test-case provided in the GLIBC bug report manifests the
// hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
// and monitorenter when we're using 1-0 locking. All those operations may result in
// calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
// of libpthread avoids the problem, but isn't practical.
//
// Possible remedies:
//
// 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
// This is palliative and probabilistic, however. If the thread is preempted
// between the call to compute_abstime() and pthread_cond_timedwait(), more
// than the minimum period may have passed, and the abstime may be stale (in the
// past) resultin in a hang. Using this technique reduces the odds of a hang
// but the JVM is still vulnerable, particularly on heavily loaded systems.
//
// 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
// of the usual flag-condvar-mutex idiom. The write side of the pipe is set
// NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
// reduces to poll()+read(). This works well, but consumes 2 FDs per extant
// thread.
//
// 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
// that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
// a timeout request to the chron thread and then blocking via pthread_cond_wait().
// This also works well. In fact it avoids kernel-level scalability impediments
// on certain platforms that don't handle lots of active pthread_cond_timedwait()
// timers in a graceful fashion.
//
// 4. When the abstime value is in the past it appears that control returns
// correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
// can avoid the problem by reinitializing the condvar -- by cond_destroy()
// followed by cond_init() -- after all calls to pthread_cond_timedwait().
// It may be possible to avoid reinitialization by checking the return
// value from pthread_cond_timedwait(). In addition to reinitializing the
// condvar we must establish the invariant that cond_signal() is only called
// within critical sections protected by the adjunct mutex. This prevents
// cond_signal() from "seeing" a condvar that's in the midst of being
// reinitialized or that is corrupt. Sadly, this invariant obviates the
// desirable signal-after-unlock optimization that avoids futile context switching.
//
// I'm also concerned that some versions of NTPL might allocate an auxilliary
// structure when a condvar is used or initialized. cond_destroy() would
// release the helper structure. Our reinitialize-after-timedwait fix
//
// We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
// It may be possible to refine (4) by checking the kernel and NTPL verisons
// and only enabling the work-around for vulnerable environments.
// utility to compute the abstime argument to timedwait:
// millis is the relative timeout time
// abstime will be the absolute timeout time
// TODO: replace compute_abstime() with unpackTime()
millis %= 1000;
seconds = 50000000;
}
if (usec >= 1000000) {
usec -= 1000000;
}
return abstime;
}
// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
// Conceptually TryPark() should be equivalent to park(0).
for (;;) {
const int v = _Event ;
}
}
// Invariant: Only the thread associated with the Event/PlatformEvent
// may call park().
// TODO: assert that _Assoc != NULL or _Assoc == Self
int v ;
for (;;) {
v = _Event ;
}
guarantee (v >= 0, "invariant") ;
if (v == 0) {
// Do this the hard way by blocking ...
++ _nParked ;
while (_Event < 0) {
// for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
// Treat this the same as if the wait was interrupted
}
-- _nParked ;
_Event = 0 ;
// Paranoia to ensure our locked and lock-free paths interact
// correctly with each other.
OrderAccess::fence();
}
}
int v ;
for (;;) {
v = _Event ;
}
guarantee (v >= 0, "invariant") ;
if (v != 0) return OS_OK ;
// We do this the hard way, by blocking the thread.
// Consider enforcing a minimum timeout value.
int ret = OS_TIMEOUT;
++_nParked ;
// Object.wait(timo) will return because of
// (a) notification
// (b) timeout
// (c) thread.interrupt
//
// Thread.interrupt and object.notify{All} both call Event::set.
// That is, we treat thread.interrupt as a special case of notification.
// The underlying Solaris implementation, cond_timedwait, admits
// JVM from making those visible to Java code. As such, we must
// filter out spurious wakeups. We assume all ETIME returns are valid.
//
// TODO: properly differentiate simultaneous notify+interrupt.
// In that case, we should propagate the notify to another waiter.
while (_Event < 0) {
if (status != 0 && WorkAroundNPTLTimedWaitHang) {
}
status, "cond_timedwait");
if (!FilterSpuriousWakeups) break ; // previous semantics
// We consume and ignore EINTR and spurious wakeups.
}
--_nParked ;
if (_Event >= 0) {
}
_Event = 0 ;
// Paranoia to ensure our locked and lock-free paths interact
// correctly with each other.
OrderAccess::fence();
return ret;
}
// Transitions for _Event:
// 0 :=> 1
// 1 :=> 1
// -1 :=> either 0 or 1; must signal target thread
// That is, we can safely transition _Event from -1 to either
// 0 or 1. Forcing 1 is slightly more efficient for back-to-back
// unpark() calls.
// See also: "Semaphores in Plan 9" by Mullender & Cox
//
// Note: Forcing a transition from "-1" to "1" on an unpark() means
// that it will take two back-to-back park() calls for the owning
// thread to block. This has the benefit of forcing a spurious return
// from the first park() call after an unpark() call which will help
// shake out uses of park() and unpark() without condition variables.
// Wait for the thread associated with the event to vacate
int AnyWaiters = _nParked;
if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
AnyWaiters = 0;
}
if (AnyWaiters != 0) {
}
// Note that we signal() _after dropping the lock for "immortal" Events.
// This is safe and avoids a common class of futile wakeups. In rare
// circumstances this can cause a thread to return prematurely from
// cond_{timed}wait() but the spurious wakeup is benign and the victim will
// simply re-test the condition and re-park itself.
}
// JSR166
// -------------------------------------------------------
/*
* conservative for now, but can be improved. They currently use a
* Park decrements count if > 0, else does a condvar wait. Unpark
* sets count to 1 and signals condvar. Only one thread ever waits
* on the condvar. Contention seen when trying to park implies that someone
* is unparking you, so don't wait. And spurious returns are fine, so there
* is no need to track notifications.
*/
#define MAX_SECS 100000000
/*
* This code is common to bsd and solaris and will be moved to a
* common place in dolphin.
*
* The passed in time value is either a relative time in nanoseconds
* or an absolute time in milliseconds. Either way it has to be unpacked
* into suitable seconds and nanoseconds components and stored in the
* given timespec structure.
* Given time is a 64-bit value and the time_t used in the timespec is only
* a signed-32-bit value (except on 64-bit Bsd) we have to watch for
* overflow if times way in the future are given. Further on Solaris versions
* prior to 10 there is a restriction (see cond_timedwait) that the specified
* number of seconds, in abstime, is less than current_time + 100,000,000.
* As it will be 28 years before "now + 100000000" will overflow we can
* ignore overflow and just impose a hard-limit on seconds using the value
* of "now + 100,000,000". This places a limit on the timeout of about 3.17
* years from "now".
*/
if (isAbsolute) {
}
else {
}
}
else {
}
else {
}
}
}
}
// Ideally we'd do something useful while spinning, such
// as calling unpackTime().
// Optional fast-path check:
// Return immediately if a permit is available.
// We depend on Atomic::xchg() having full barrier semantics
// since we are doing a lock-free update to _counter.
// Optional optimization -- avoid state transitions if there's an interrupt pending.
// Check interrupt before trying to wait
return;
}
// Next, demultiplex/decode time arguments
return;
}
if (time > 0) {
}
// Enter safepoint region
// Beware of deadlocks such as 6317397.
// The per-thread Parker:: mutex is a classic leaf-lock.
// In particular a thread must never block on the Threads_lock while
// holding the Parker:: mutex. If safepoints are pending both the
// the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
// Don't wait if cannot get lock since interference arises from
// unblocking. Also. check interrupt before trying wait
return;
}
int status ;
if (_counter > 0) { // no wait needed
_counter = 0;
// Paranoia to ensure our locked and lock-free paths interact
// correctly with each other and Java-level accesses.
OrderAccess::fence();
return;
}
#ifdef ASSERT
// Don't catch signals while blocked; let the running threads have the signals.
// (This allows a debugger to break into the running thread.)
#endif
// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
if (time == 0) {
} else {
if (status != 0 && WorkAroundNPTLTimedWaitHang) {
}
}
status, "cond_timedwait");
#ifdef ASSERT
#endif
_counter = 0 ;
// Paranoia to ensure our locked and lock-free paths interact
// correctly with each other and Java-level accesses.
OrderAccess::fence();
// If externally suspended while waiting, re-suspend
jt->java_suspend_self();
}
}
int s, status ;
s = _counter;
_counter = 1;
if (s < 1) {
if (WorkAroundNPTLTimedWaitHang) {
} else {
}
} else {
}
}
/* Darwin has no "environ" in a dynamic library. */
#ifdef __APPLE__
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
extern char** environ;
#endif
// Run the specified command in a separate process. Return its exit value,
// or -1 on failure (e.g. can't fork a new process).
// Unlike system(), this function can be called from signal handler. It
// doesn't block SIGINT et al.
// fork() in BsdThreads/NPTL is not async-safe. It needs to run
// pthread_atfork handlers and reset pthread library. All we need is a
// separate process to execve. Make a direct syscall to fork process.
// On IA64 there's no fork syscall, we have to use fork() and hope for
// the best...
if (pid < 0) {
// fork failed
return -1;
} else if (pid == 0) {
// child process
// execve() in BsdThreads will call pthread_kill_other_threads_np()
// first to kill every thread on the thread list. Because this list is
// not reset by fork() (see notes above), execve() will instead kill
// every thread in the parent process. We know this is the only thread
// in the new process, so make a system call directly.
// IA64 should use normal execve() from glibc to match the glibc fork()
// above.
// execve failed
_exit(-1);
} else {
// copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
// care about the actual exit code, for now.
int status;
// Wait for the child process to exit. This returns immediately if
// the child has already exited. */
switch (errno) {
case ECHILD: return 0;
case EINTR: break;
default: return -1;
}
}
// The child exited normally; get its exit code.
return WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
// The child exited because of a signal
// The best value to return is 0x80 + signal number,
// because that is what all Unix shells do, and because
// it allows callers to distinguish between process exit and
// process death by signal.
} else {
// Unknown exit code; pass it through
return status;
}
}
}
// is_headless_jre()
//
// Test for the existence of xawt/libmawt.so or libawt_xawt.so
// in order to report if we are running in a headless jre
//
// Since JDK8 xawt/libmawt.so was moved into the same directory
// as libawt.so, and renamed libawt_xawt.so
//
bool os::is_headless_jre() {
char buf[MAXPATHLEN];
char libmawtpath[MAXPATHLEN];
char *p;
// Get path to libjvm.so
// Get rid of libjvm.so
if (p == NULL) return false;
else *p = '\0';
// Get rid of client or server
if (p == NULL) return false;
else *p = '\0';
// check xawt/libmawt.so
// check libawt_xawt.so
return true;
}
// Get the default path to the core file
// Returns the length of the string
// Truncate if theoretical string was longer than bufferSize
n = MIN2(n, (int)bufferSize);
return n;
}