/*
* 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_linux.h"
#include "memory/allocation.inline.hpp"
#include "memory/filemap.hpp"
#include "mutex_linux.inline.hpp"
#include "oops/oop.inline.hpp"
#include "os_share_linux.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_linux.inline.hpp"
#include "utilities/decoder.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
#include "utilities/elfFile.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 <pwd.h>
# include <poll.h>
# include <semaphore.h>
# include <fcntl.h>
# include <string.h>
# include <syscall.h>
# include <gnu/libc-version.h>
# include <link.h>
# include <stdint.h>
# include <inttypes.h>
// for timer info max values which include all bits
////////////////////////////////////////////////////////////////////////////////
// global variables
// For diagnostics to print a message once. see run_periodic_checks
static bool check_signals = true;;
/* do not use any signal number less than SIGSEGV, see 4355769 */
/* Used to protect dlsym() calls */
// Declarations
#ifdef JAVASE_EMBEDDED
friend class VMStructs;
public:
virtual void run();
private:
int _fd;
public:
// Constructor
MemNotifyThread(int fd);
// Tester
bool is_memnotify_thread() const { return true; }
// Printing
// Returns the single instance of the MemNotifyThread
// Create and start the single instance of MemNotifyThread
static void start();
};
#endif // JAVASE_EMBEDDED
// utility functions
static int SR_initialize();
static int SR_finalize();
return Linux::available_memory();
}
// values in struct sysinfo are "unsigned long"
}
return Linux::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.
static bool init = false;
static bool privileges = false;
if (!init) {
init = true;
}
return privileges;
}
#ifndef SYS_gettid
// i386: 224, ia64: 1105, amd64: 186, sparc 143
#ifdef __ia64__
#else
#endif
#endif
// Cpu architecture string
#if defined(ZERO)
# ifdef _LP64
# else
# endif
#else
#endif
// 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 LinuxThreads 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 linux 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;
"Java may be unstable running multithreaded in a chroot "
"environment on Linux when /proc filesystem is not mounted.";
if (processor_count() == 1) {
unsafe_chroot_detected = true;
} else {
}
}
}
// 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: ...
* ...
*/
#else
#define DEFAULT_LIBPATH "/lib:/usr/lib"
#endif
{
/* sysclasspath, java_home, dll_dir */
{
char *home_path;
char *dll_path;
char *pslash;
// Found the full path to libjvm.so.
// Now cut the path to <java_home>/jre if we can.
return;
}
}
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 Linux 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).
*/
/*
* Get the user setting of LD_LIBRARY_PATH, and prepended it. It
* should always exist (until the legacy problem cited above is
* addressed).
*/
char *v = getenv("LD_LIBRARY_PATH");
if (v != NULL) {
char *t = ld_library_path;
/* That's +1 for the colon and +1 for the trailing '\0' */
}
}
/*
* 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).
*/
{
Arguments::get_java_home());
}
/* Endorsed standards default directory. */
{
char * buf;
}
}
// Done
return;
}
////////////////////////////////////////////////////////////////////////////////
// breakpoint support
}
// 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
}
}
}
//////////////////////////////////////////////////////////////////////////////
// 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
# endif
# ifndef _CS_GNU_LIBPTHREAD_VERSION
# endif
if (n > 0) {
} else {
// _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
}
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 LinuxThreads. Check if this
// is the case. LinuxThreads 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 LinuxThreads.
}
} else {
}
// LinuxThreads have two flavors: floating-stack mode, which allows variable
// stack size; and fixed-stack mode. NPTL is always floating-stack.
}
}
/////////////////////////////////////////////////////////////////////////////
// thread stack
// Force Linux 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 LinuxThreads to only mmap the first few pages
// when creating a new thread. Linux 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,
// Linux kernel does not expand stack, instead a SIGSEGV is sent to the
// application (see Linux kernel fault.c).
//
// This Linux feature can cause SIGSEGV when VM bangs thread stack for
// stack overflow detection.
//
// Newer version of LinuxThreads (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 Linux, 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. Linux 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;
}
//////////////////////////////////////////////////////////////////////////////
// create new thread
static address highest_vm_reserved_address();
// check if it's safe to start a new thread
// 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 LinuxThreads).
//
// 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 LinuxThreads or NPTL:
// Unlike fixed stack LinuxThreads, 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;
}
}
// 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 LinuxThreads needs extra check, see above
if (!_thread_safety_check(thread)) {
// notify parent thread
sync->notify_all();
return NULL;
}
// thread_id is kernel thread id (similar to Solaris LWP id)
if (UseNUMA) {
if (lgrp_id != -1) {
}
}
// initialize signal mask for this thread
// initialize floating point control register
// 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.
}
// glibc guard page
{
// Serialize thread creation if we are running with fixed stack LinuxThreads
if (lock) {
}
if (ret != 0) {
perror("pthread_create()");
}
// Need to clean up stuff we've allocated so far
delete osthread;
return false;
}
// Store pthread info into the OSThread
// Wait until child thread is either initialized or aborted
{
}
}
if (lock) {
}
}
// 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
// initialize floating point control register
// Initial thread state is RUNNABLE
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 Linux), so there
// is no gap between the last two virtual memory regions.
}
// initialize signal mask for this thread
// and save the caller's signal mask
return true;
}
}
// Free Linux resources related to the OSThread
// Restore caller's signal mask
}
delete osthread;
}
//////////////////////////////////////////////////////////////////////////////
// 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
// 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?) Linux 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.
//
// Linux 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.
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));
/* 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 Linux 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 {
}
}
////////////////////////////////////////////////////////////////////////////////
// time support
// Time since start-up in seconds to a fine granularity.
// Used by VMSelfDestructTimer and the MemProfiler.
}
}
return (1000 * 1000);
}
// For now, we say that linux does not support vtime. I have no idea
// whether it can actually be made to (DLD, 9/13/05).
// better than nothing, but not much
return elapsedTime();
}
}
#ifndef CLOCK_MONOTONIC
#endif
// we do dlopen's in this particular order due to bug in linux
// 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
}
}
}
}
#ifndef SYS_clock_getres
#else
#warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
#endif
#else
#endif
if (!UseLinuxPosixThreadCPUClocks) {
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;
}
}
if (Linux::supports_monotonic_clock()) {
return result;
} else {
return 1000 * usecs;
}
}
if (Linux::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 {
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
#endif
::abort(); // dump core
}
::exit(1);
}
// Die immediately, no exit hook, no abort hook, no cleanup.
// _exit() on LinuxThreads only kills current thread
::abort();
}
// unused on linux 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;
}
// Under the old linux thread library, linux 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). Linux 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_linux.hpp file
}
// DLL functions
// This must be hard coded because it's the system's temporary
// directory not the java application's temp directory, ala java.io.tmpdir.
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
if (libjvm_base_addr == NULL) {
}
}
return false;
}
}
}
return true;
return true;
}
}
return false;
}
struct _address_to_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;
}
// 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;
}
}
// Loads .dll/.so and
// in case of error it checks if .dll/.so was built for the
// same architecture as Hotspot is running on
// Remember the stack's state. The Linux dynamic linker will change
// the stack to 'executable' at most once, so we must safepoint only once.
// VM operation that loads a library. This is necessary if stack protection
// of the Java stacks can be lost during loading the library. If we
// do not stop the Java threads, they can stack overflow before the stacks
// are protected again.
private:
const char *_filename;
char *_ebuf;
int _ebuflen;
void *_lib;
public:
void doit() {
}
};
{
bool load_attempted = false;
// Check whether the library to load might change execution rights
// of the stack. If they are changed, the protection of the stack
// guard pages will be lost. We need a safepoint to fix this.
//
// See Linux man page execstack(8) for more info.
if (!ef.specifies_noexecstack()) {
if (!is_init_completed()) {
// This is OK - No Java threads have been created yet, and hence no
// stack guard pages to fix.
//
// This should happen only when you are building JDK7 using a very
// old version of JDK6 (e.g., with JPRT) and running test_gamma.
//
// Dynamic loader will make all stacks executable after
// this function returns, and will not do that again.
} else {
warning("You have loaded library %s which might have disabled stack guard. "
"The VM will try to fix the stack guard now.\n"
"It's highly recommended that you fix the library with "
"'execstack -c <libfile>', or link it with '-z noexecstack'.",
filename);
// This happens when a compiler thread tries to load a hsdis-<arch>.so file
// that requires ExecStack. Cannot enter safe point. Let's give up.
warning("Unable to fix stack guard. Giving up.");
} else {
if (!LoadExecStackDllInVMThread) {
// This is for the case where the DLL has an static
// constructor function that executes JNI code. We cannot
// load such DLLs in the VMThread.
}
if (LoadExecStackDllInVMThread) {
}
load_attempted = true;
}
}
}
}
if (!load_attempted) {
}
// Successful loading
return result;
}
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 {
} arch_t;
#ifndef EM_486
#endif
};
#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
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;
}
}
return result;
}
if (LoadExecStackDllInVMThread) {
}
// Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
// library that requires an executable stack, or which does not have this
// stack attribute set, dlopen changes the stack attribute to executable. The
// read protection of the guard pages gets lost.
//
// Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
// may have been queued at the same time.
if (!_stack_is_executable) {
while (jt) {
warning("Attempt to reguard stack yellow zone failed.");
}
}
}
}
return result;
}
/*
* glibc-2.0 libdl is not MT safe. If you are building with any glibc,
* chances are you might want to run the generated bits against glibc-2.0
* libdl.so, so always use locking for any version of glibc.
*/
return res;
}
if (fd == -1) {
return false;
}
int bytes;
}
return true;
}
}
}
}
// Print warning if unsafe chroot environment detected
if (unsafe_chroot_detected) {
}
}
// Try to identify popular distros.
// Most Linux distributions have /etc/XXX-release file, which contains
// the OS version string. Some have more than one /etc/XXX-release file
// (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.),
// so the order is important.
}
}
// libc, pthread
}
}
}
// values in struct sysinfo are "unsigned long"
}
}
}
// but they're the same for all the linux 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" };
} 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, " \
}
}
}
}
// Find the full path to the current module, libjvm.so or libjvm_g.so
// 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;
}
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 fix
// up the path so it looks like libjvm.so is installed there (append a
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.so" or "libjvm_g.so".
return;
// determine if this is a legacy image or modules image
// modules image doesn't have "jre" subdirectory
}
// Use current module name "libjvm[_g].so" instead of
// "libjvm"debug_only("_g")".so" since for fastdebug version
// we should have "libjvm.so" but debug_only("_g") adds "_g"!
} else {
// Go back to path of .so
return;
}
}
}
}
}
// no prefix required, not even "_"
}
// no suffix required
}
////////////////////////////////////////////////////////////////////////////////
// sun.misc.Signal support
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.
}
}
return CAST_FROM_FN_PTR(void*, UserHandler);
}
public:
Semaphore();
~Semaphore();
void signal();
void wait();
bool trywait();
private:
};
sem_init(&_semaphore, 0, 0);
}
}
}
}
return sem_trywait(&_semaphore) == 0;
}
while (1) {
if (result == 0) {
return true;
continue;
return false;
} else {
return false;
}
}
}
extern "C" {
typedef void (*sa_handler_t)(int);
}
// -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
return NSIG;
}
// a counter for each possible signal value
// Linux(POSIX) specific hand shaking semaphore.
// Initialize signal structures
// Initialize signal semaphore
}
}
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);
}
}
return check_pending_signals(false);
}
return check_pending_signals(true);
}
////////////////////////////////////////////////////////////////////////////////
// Virtual Memory
// Seems redundant as all get out
}
// Solaris allocates memory by pages.
}
// 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) {
}
}
}
}
// See if the error is one we can let the caller handle. This
// list of errno values comes from JBS-6843484. I can't find a
// Linux man page that documents this specific set of errno
// values so while this list currently matches Solaris, it may
// change as we gain experience with this failure mode.
switch (err) {
case EBADF:
case EINVAL:
case ENOTSUP:
// let the caller deal with these errors
return true;
default:
// Any remaining errors on this OS can cause our reserved mapping
// to be lost. That can cause confusion where different data
// structures think they have the same memory mapped. The worst
// scenario is if both the VM and a library think they have the
// same memory mapped.
return false;
}
}
int err) {
}
int err) {
}
// NOTE: Linux 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.
if (UseNUMAInterleaving) {
}
return 0;
}
if (!recoverable_mmap_error(err)) {
}
return err;
}
}
const char* mesg) {
if (err != 0) {
// the caller wants all commit errors to exit with the specified mesg:
}
}
// Define MAP_HUGETLB here so we can build HotSpot on old systems.
#ifndef MAP_HUGETLB
#endif
// Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
#ifndef MADV_HUGEPAGE
#endif
int err;
-1, 0);
if (UseNUMAInterleaving) {
}
return 0;
}
if (!recoverable_mmap_error(err)) {
// However, it is not clear that this loss of our reserved mapping
// happens with large pages on Linux or that we cannot recover
// from the loss. For now, we just issue a warning and we don't
// call vm_exit_out_of_memory(). This issue is being tracked by
// JBS-8007074.
// vm_exit_out_of_memory(size, "committing reserved memory.");
}
// Fall through and try to use small pages
}
if (err == 0) {
}
return err;
}
bool exec) {
}
const char* mesg) {
if (err != 0) {
// the caller wants all commit errors to exit with the specified mesg:
}
}
// We don't check the return value: madvise(MADV_HUGEPAGE) may not
// be supported or the memory may already be backed by huge pages.
}
}
// This method works by doing an mmap over an existing mmaping and effectively discarding
// the existing pages. However it won't work for SHM-based large pages that cannot be
// uncommitted at all. We don't do anything in this case to avoid creating a segment with
// small pages on top of the SHM segment. This method always works for small pages, so we
// allow that in any case.
}
}
}
}
}
if (cpu_id != -1) {
if (lgrp_id != -1) {
return lgrp_id;
}
}
return 0;
}
ids[i] = i;
}
return size;
}
return false;
}
return end;
}
unsigned int cpu;
#if defined(IA32)
# ifndef SYS_getcpu
# endif
// Unfortunately we have to bring all these macros here from vsyscall.h
// to be able to compile on old linuxes.
#endif
}
// 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 it's not, try a direct syscall.
if (sched_getcpu() == -1)
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)) {
}
}
}
}
}
}
}
}
return -1;
}
}
// Linux uses a growable mapping for the stack, and if the mapping for
// the stack guard pages is not removed when we detach a thread the
// stack cannot grow beyond the pages where the stack guard was
// mapped. If at some point later in the process the stack expands to
// that point, the Linux kernel cannot expand the stack any further
// because the guard pages are in the way, and a segfault occurs.
//
// However, it's essential not to split the stack region by unmapping
// a region (leaving a hole) that's already part of the stack mapping,
// so if the stack mapping has already grown beyond the guard pages at
// the time we create them, we have to truncate the stack mapping.
// So, we need to know the extent of the stack mapping when
// create_stack_guard_pages() is called.
// Find the bounds of the stack mapping. Return true for success.
//
// We only need this for stacks that are growable: at the time of
// writing thread stacks don't use growable mappings (i.e. those
// creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
// only applies to the main thread.
static
return false;
}
// Extract addresses
return true;
}
}
}
}
return false;
}
// If the (growable) stack mapping already extends beyond the point
// where we're going to put our guard pages, truncate the mapping at
// that point by munmap()ping it. This ensures that when we later
// munmap() the guard pages we don't leave a hole in the stack
// against future OS changes
"growable stack in non-initial thread");
}
}
// If this is a growable mapping, remove the guard pages entirely by
// munmap()ping them. If not, just call uncommit_memory(). This only
"growable stack in non-initial thread");
}
}
// 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 Linux 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.
//
}
}
}
return _highest_vm_reserved_address;
}
// Linux 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;
-1, 0);
if (p != MAP_FAILED) {
// We don't know if this really is a huge page or not.
if (fp) {
long x = 0;
&& x == (long)p) {
result = true;
break;
}
}
}
}
}
if (result)
return true;
}
if (warn) {
warning("HugeTLBFS is not supported by the operating system.");
}
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
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 Linux 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;
_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;
}
#ifndef SHM_HUGETLB
#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;
(!FLAG_IS_DEFAULT(UseLargePages) ||
);
// Create a large shared memory region to attach to based on size.
// Currently, size is the total size of the heap
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 Linux 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.
return UseHugeTLBFS;
}
return UseHugeTLBFS;
}
// Reserve memory at an arbitrary address, only if that area is
// available (and not reserved for something else).
// 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 LinuxThreads. 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.
// Linux 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 linux variation.
// Solaris uses poll(), linux 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 ;
}
}
// %% make the sleep time an integer flag. for now use 1 millisec.
}
// Sleep forever; naked call to OS-specific sleep; use with CAUTION
while (true) { // sleep forever ...
}
}
// Used to convert frequent JVM_Yield() to nops
return DontYieldALot;
}
sched_yield();
}
// Yields to all threads, including threads with lower priorities
// Threads on Linux 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 Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
// only supports dynamic priority, static priority must be zero. For real-time
// applications, Linux 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.
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
};
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 Linux");
}
ThreadPriorityPolicy = 0;
}
}
}
return 0;
}
}
if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
return OS_OK;
}
errno = 0;
}
// Hint to the underlying OS that a task switch would not be good.
// Void return because it's a hint and can fail.
////////////////////////////////////////////////////////////////////////////////
// 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 and JavaThreads (PC sampling)
//
// 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 Linux platforms). Note that LinuxThreads 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
// 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_linux_signal, harmlessly.
// For signal-chaining
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 {
}
// 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 (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.
// Log that signal checking is off only if -verbose:jni is specified.
if (CheckJNICalls) {
if (libjsig_is_loaded) {
if (PrintJNIResolving) {
}
check_signals = false;
}
if (AllowUserSignalHandlers) {
if (PrintJNIResolving) {
tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
}
check_signals = false;
}
}
}
}
// This is the fastest way to get thread cpu time on Linux.
// 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:
}
/////
// glibc on Linux 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
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!
}
}
}
// This method is a periodic task to check for misbehaving JNI applications
// under CheckJNI, we can add any periodic checks here
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::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::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
// first_hrtime = gethrtime();
// With LinuxThreads the JavaMain thread pid (primordial thread)
// is different than the pid of the java launcher thread.
// So, on Linux, 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
Linux::clock_init();
// If the pagesize of the VM is greater than 8K determine the appropriate
// number of initial guard pages. The user can change this with the
// command line arguments, if needed.
StackYellowPages = 1;
StackRedPages = 1;
StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
}
}
// To install functions for atexit system call
extern "C" {
static void perfMemory_exit_helper() {
}
}
// this is called _after_ the global arguments have been parsed
{
// Allocate a single page and mark it as readable for safepoint polling
address polling_page = (address) ::mmap(NULL, Linux::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, Linux::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;
}
// 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()));
Linux::libpthread_init();
}
if (UseNUMA) {
if (!Linux::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;
}
}
if (MaxFDLimit) {
// set the number of file descriptors to max. print out error
if (status != 0) {
perror("os::init_2 getrlimit failed");
} else {
if (status != 0) {
perror("os::init_2 setrlimit failed");
}
}
}
// Initialize lock used to serialize thread creation (see os::create_thread)
// 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();
return JNI_OK;
}
// this is called at the end of vm_initialization
{
#ifdef JAVASE_EMBEDDED
// Start the MemNotifyThread
if (LowMemoryProtection) {
MemNotifyThread::start();
}
return;
#endif
}
// Mark the polling page as unreadable
fatal("Could not disable polling page");
};
// Mark the polling page as readable
fatal("Could not enable polling page");
}
};
// Linux doesn't yet have a (official) notion of processor sets,
// so just return the number of online processors.
return online_cpus;
}
// Not yet implemented.
return;
}
// 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::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
{
if (is_NPTL()) {
} else {
#ifndef IA64
// 6292965: LinuxThreads 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.
#endif // IA64
#ifndef IA64
#endif // IA64
return status;
}
}
////////////////////////////////////////////////////////////////////////////////
// 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 Linux. This is basically a hook for being
// able to use structured exception handling (thread-local exception filters)
// on, e.g., Win32.
void
}
}
int i;
// 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
#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;
}
// Linux doc says EINTR not returned, unlike Solaris
//%% note ioctl can return 0 when successful, JVM_SocketAvailable
// is expected to return 0 on failure and 1 on success to the jdk.
return (ret < 0) ? 0 : 1;
}
// Map a block of memory.
bool allow_exec) {
int prot;
if (read_only) {
} else {
}
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.
}
// Get thread clockid
return clockid;
}
// 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.
} else {
// return user + sys since the cost is the same
}
}
// consistent with what current_thread_cpu_time() returns
} else {
}
}
} else {
}
}
} else {
}
}
//
// -1 on error.
//
static bool proc_pid_cpu_avail = true;
static bool proc_task_unchecked = true;
int i;
char *s;
int statlen;
int count;
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 (linux 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 Linux 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 {
}
}
}
}
return true;
}
// System loadavg support. Returns -1 if load average cannot be obtained.
// Linux 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.
++_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
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.
*/
/*
* This code is common to linux 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 Linux) 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 {
}
}
extern char** environ;
#ifndef __NR_fork
#endif
#ifndef __NR_execve
#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 LinuxThreads/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 LinuxThreads 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];
const char *xawtstr = "/xawt/libmawt.so";
const char *new_xawtstr = "/libawt_xawt.so";
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
if (p == NULL) {
return 0;
}
}
#ifdef JAVASE_EMBEDDED
//
// A thread to watch the '/dev/mem_notify' device, which will tell us when the OS is running low on memory.
//
// ctor
//
_memnotify_thread = this;
os::start_thread(this);
}
}
// Where all the work gets done
//
// Set up the select arguments
if (_fd != -1) {
}
// Now wait for the mem_notify device to wake up
while (1) {
// Wait for the mem_notify device to signal us..
if (rc == -1) {
perror("select!\n");
break;
} else if (rc) {
//ssize_t free_before = os::available_memory();
//tty->print ("Notified: Free: %dK \n",os::available_memory()/1024);
// The kernel is telling us there is not much memory left...
// try to do something about that
// If we are not already in a GC, try one.
//ssize_t free_after = os::available_memory();
//tty->print ("Post-Notify: Free: %dK\n",free_after/1024);
//tty->print ("GC freed: %dK\n", (free_after - free_before)/1024);
}
// We might want to do something like the following if we find the GC's are not helping...
// Universe::heap()->size_policy()->set_gc_time_limit_exceeded(true);
}
}
}
//
// See if the /dev/mem_notify device exists, and if so, start a thread to monitor it.
//
int fd;
if (fd < 0) {
return;
}
if (memnotify_thread() == NULL) {
new MemNotifyThread(fd);
}
}
#endif // JAVASE_EMBEDDED