0N/A/*
4278N/A * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
1472N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1472N/A * or visit www.oracle.com if you need additional information or have any
1472N/A * questions.
0N/A *
0N/A */
0N/A
1879N/A// no precompiled headers
1879N/A#include "classfile/classLoader.hpp"
1879N/A#include "classfile/systemDictionary.hpp"
1879N/A#include "classfile/vmSymbols.hpp"
1879N/A#include "code/icBuffer.hpp"
1879N/A#include "code/vtableStubs.hpp"
1879N/A#include "compiler/compileBroker.hpp"
1879N/A#include "interpreter/interpreter.hpp"
1879N/A#include "jvm_linux.h"
1879N/A#include "memory/allocation.inline.hpp"
1879N/A#include "memory/filemap.hpp"
1879N/A#include "mutex_linux.inline.hpp"
1879N/A#include "oops/oop.inline.hpp"
1879N/A#include "os_share_linux.hpp"
1879N/A#include "prims/jniFastGetField.hpp"
1879N/A#include "prims/jvm.h"
1879N/A#include "prims/jvm_misc.hpp"
1879N/A#include "runtime/arguments.hpp"
1879N/A#include "runtime/extendedPC.hpp"
1879N/A#include "runtime/globals.hpp"
1879N/A#include "runtime/interfaceSupport.hpp"
4340N/A#include "runtime/init.hpp"
1879N/A#include "runtime/java.hpp"
1879N/A#include "runtime/javaCalls.hpp"
1879N/A#include "runtime/mutexLocker.hpp"
1879N/A#include "runtime/objectMonitor.hpp"
1879N/A#include "runtime/osThread.hpp"
1879N/A#include "runtime/perfMemory.hpp"
1879N/A#include "runtime/sharedRuntime.hpp"
1879N/A#include "runtime/statSampler.hpp"
1879N/A#include "runtime/stubRoutines.hpp"
1879N/A#include "runtime/threadCritical.hpp"
1879N/A#include "runtime/timer.hpp"
1879N/A#include "services/attachListener.hpp"
4299N/A#include "services/memTracker.hpp"
1879N/A#include "services/runtimeService.hpp"
1879N/A#include "thread_linux.inline.hpp"
1929N/A#include "utilities/decoder.hpp"
1879N/A#include "utilities/defaultStream.hpp"
1879N/A#include "utilities/events.hpp"
4340N/A#include "utilities/elfFile.hpp"
1879N/A#include "utilities/growableArray.hpp"
1879N/A#include "utilities/vmError.hpp"
1879N/A#ifdef TARGET_ARCH_x86
1879N/A# include "assembler_x86.inline.hpp"
1879N/A# include "nativeInst_x86.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_ARCH_sparc
1879N/A# include "assembler_sparc.inline.hpp"
1879N/A# include "nativeInst_sparc.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_ARCH_zero
1879N/A# include "assembler_zero.inline.hpp"
1879N/A# include "nativeInst_zero.hpp"
1879N/A#endif
2073N/A#ifdef TARGET_ARCH_arm
2073N/A# include "assembler_arm.inline.hpp"
2073N/A# include "nativeInst_arm.hpp"
2073N/A#endif
2073N/A#ifdef TARGET_ARCH_ppc
2073N/A# include "assembler_ppc.inline.hpp"
2073N/A# include "nativeInst_ppc.hpp"
2073N/A#endif
0N/A
0N/A// put OS-includes here
0N/A# include <sys/types.h>
0N/A# include <sys/mman.h>
1601N/A# include <sys/stat.h>
1601N/A# include <sys/select.h>
0N/A# include <pthread.h>
0N/A# include <signal.h>
0N/A# include <errno.h>
0N/A# include <dlfcn.h>
0N/A# include <stdio.h>
0N/A# include <unistd.h>
0N/A# include <sys/resource.h>
0N/A# include <pthread.h>
0N/A# include <sys/stat.h>
0N/A# include <sys/time.h>
0N/A# include <sys/times.h>
0N/A# include <sys/utsname.h>
0N/A# include <sys/socket.h>
0N/A# include <sys/wait.h>
0N/A# include <pwd.h>
0N/A# include <poll.h>
0N/A# include <semaphore.h>
0N/A# include <fcntl.h>
0N/A# include <string.h>
0N/A# include <syscall.h>
0N/A# include <sys/sysinfo.h>
0N/A# include <gnu/libc-version.h>
0N/A# include <sys/ipc.h>
0N/A# include <sys/shm.h>
0N/A# include <link.h>
1320N/A# include <stdint.h>
1320N/A# include <inttypes.h>
1940N/A# include <sys/ioctl.h>
0N/A
0N/A#define MAX_PATH (2 * K)
0N/A
0N/A// for timer info max values which include all bits
0N/A#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
0N/A
2085N/A#define LARGEPAGES_BIT (1 << 6)
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// global variables
0N/Ajulong os::Linux::_physical_memory = 0;
0N/A
0N/Aaddress os::Linux::_initial_thread_stack_bottom = NULL;
0N/Auintptr_t os::Linux::_initial_thread_stack_size = 0;
0N/A
0N/Aint (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL;
0N/Aint (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
0N/AMutex* os::Linux::_createThread_lock = NULL;
0N/Apthread_t os::Linux::_main_thread;
0N/Aint os::Linux::_page_size = -1;
4531N/Aconst int os::Linux::_vm_default_page_size = (8 * K);
0N/Abool os::Linux::_is_floating_stack = false;
0N/Abool os::Linux::_is_NPTL = false;
0N/Abool os::Linux::_supports_fast_thread_cpu_time = false;
199N/Aconst char * os::Linux::_glibc_version = NULL;
199N/Aconst char * os::Linux::_libpthread_version = NULL;
0N/A
0N/Astatic jlong initial_time_count=0;
0N/A
0N/Astatic int clock_tics_per_sec = 100;
0N/A
0N/A// For diagnostics to print a message once. see run_periodic_checks
0N/Astatic sigset_t check_signal_done;
0N/Astatic bool check_signals = true;;
0N/A
0N/Astatic pid_t _initial_pid = 0;
0N/A
0N/A/* Signal number used to suspend/resume a thread */
0N/A
0N/A/* do not use any signal number less than SIGSEGV, see 4355769 */
0N/Astatic int SR_signum = SIGUSR2;
0N/Asigset_t SR_sigset;
0N/A
242N/A/* Used to protect dlsym() calls */
242N/Astatic pthread_mutex_t dl_mutex;
242N/A
4433N/A// Declarations
4433N/Astatic void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
4433N/A
2627N/A#ifdef JAVASE_EMBEDDED
2627N/Aclass MemNotifyThread: public Thread {
2627N/A friend class VMStructs;
2627N/A public:
2627N/A virtual void run();
2627N/A
2627N/A private:
2627N/A static MemNotifyThread* _memnotify_thread;
2627N/A int _fd;
2627N/A
2627N/A public:
2627N/A
2627N/A // Constructor
2627N/A MemNotifyThread(int fd);
2627N/A
2627N/A // Tester
2627N/A bool is_memnotify_thread() const { return true; }
2627N/A
2627N/A // Printing
2627N/A char* name() const { return (char*)"Linux MemNotify Thread"; }
2627N/A
2627N/A // Returns the single instance of the MemNotifyThread
2627N/A static MemNotifyThread* memnotify_thread() { return _memnotify_thread; }
2627N/A
2627N/A // Create and start the single instance of MemNotifyThread
2627N/A static void start();
2627N/A};
2627N/A#endif // JAVASE_EMBEDDED
2627N/A
0N/A// utility functions
0N/A
0N/Astatic int SR_initialize();
0N/Astatic int SR_finalize();
0N/A
0N/Ajulong os::available_memory() {
0N/A return Linux::available_memory();
0N/A}
0N/A
0N/Ajulong os::Linux::available_memory() {
0N/A // values in struct sysinfo are "unsigned long"
0N/A struct sysinfo si;
0N/A sysinfo(&si);
0N/A
0N/A return (julong)si.freeram * si.mem_unit;
0N/A}
0N/A
0N/Ajulong os::physical_memory() {
0N/A return Linux::physical_memory();
0N/A}
0N/A
20N/Ajulong os::allocatable_physical_memory(julong size) {
20N/A#ifdef _LP64
20N/A return size;
20N/A#else
20N/A julong result = MIN2(size, (julong)3800*M);
20N/A if (!is_allocatable(result)) {
20N/A // See comments under solaris for alignment considerations
20N/A julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
20N/A result = MIN2(size, reasonable_size);
20N/A }
20N/A return result;
20N/A#endif // _LP64
20N/A}
20N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// environment support
0N/A
0N/Abool os::getenv(const char* name, char* buf, int len) {
0N/A const char* val = ::getenv(name);
0N/A if (val != NULL && strlen(val) < (size_t)len) {
0N/A strcpy(buf, val);
0N/A return true;
0N/A }
0N/A if (len > 0) buf[0] = 0; // return a null string
0N/A return false;
0N/A}
0N/A
0N/A
0N/A// Return true if user is running as root.
0N/A
0N/Abool os::have_special_privileges() {
0N/A static bool init = false;
0N/A static bool privileges = false;
0N/A if (!init) {
0N/A privileges = (getuid() != geteuid()) || (getgid() != getegid());
0N/A init = true;
0N/A }
0N/A return privileges;
0N/A}
0N/A
0N/A
0N/A#ifndef SYS_gettid
0N/A// i386: 224, ia64: 1105, amd64: 186, sparc 143
0N/A#ifdef __ia64__
0N/A#define SYS_gettid 1105
0N/A#elif __i386__
0N/A#define SYS_gettid 224
0N/A#elif __amd64__
0N/A#define SYS_gettid 186
0N/A#elif __sparc__
0N/A#define SYS_gettid 143
0N/A#else
0N/A#error define gettid for the arch
0N/A#endif
0N/A#endif
0N/A
0N/A// Cpu architecture string
1010N/A#if defined(ZERO)
1010N/Astatic char cpu_arch[] = ZERO_LIBARCH;
1010N/A#elif defined(IA64)
0N/Astatic char cpu_arch[] = "ia64";
0N/A#elif defined(IA32)
0N/Astatic char cpu_arch[] = "i386";
0N/A#elif defined(AMD64)
0N/Astatic char cpu_arch[] = "amd64";
1601N/A#elif defined(ARM)
1601N/Astatic char cpu_arch[] = "arm";
1601N/A#elif defined(PPC)
1601N/Astatic char cpu_arch[] = "ppc";
0N/A#elif defined(SPARC)
0N/A# ifdef _LP64
0N/Astatic char cpu_arch[] = "sparcv9";
0N/A# else
0N/Astatic char cpu_arch[] = "sparc";
0N/A# endif
0N/A#else
0N/A#error Add appropriate cpu_arch setting
0N/A#endif
0N/A
0N/A
0N/A// pid_t gettid()
0N/A//
0N/A// Returns the kernel thread id of the currently running thread. Kernel
0N/A// thread id is used to access /proc.
0N/A//
0N/A// (Note that getpid() on LinuxThreads returns kernel thread id too; but
0N/A// on NPTL, it returns the same pid for all threads, as required by POSIX.)
0N/A//
0N/Apid_t os::Linux::gettid() {
0N/A int rslt = syscall(SYS_gettid);
0N/A if (rslt == -1) {
0N/A // old kernel, no NPTL support
0N/A return getpid();
0N/A } else {
0N/A return (pid_t)rslt;
0N/A }
0N/A}
0N/A
0N/A// Most versions of linux have a bug where the number of processors are
0N/A// determined by looking at the /proc file system. In a chroot environment,
0N/A// the system call returns 1. This causes the VM to act as if it is
0N/A// a single processor and elide locking (see is_MP() call).
0N/Astatic bool unsafe_chroot_detected = false;
199N/Astatic const char *unstable_chroot_error = "/proc file system not found.\n"
199N/A "Java may be unstable running multithreaded in a chroot "
199N/A "environment on Linux when /proc filesystem is not mounted.";
0N/A
0N/Avoid os::Linux::initialize_system_info() {
1123N/A set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
1123N/A if (processor_count() == 1) {
0N/A pid_t pid = os::Linux::gettid();
0N/A char fname[32];
0N/A jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
0N/A FILE *fp = fopen(fname, "r");
0N/A if (fp == NULL) {
0N/A unsafe_chroot_detected = true;
0N/A } else {
0N/A fclose(fp);
0N/A }
0N/A }
0N/A _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
1123N/A assert(processor_count() > 0, "linux error");
0N/A}
0N/A
0N/Avoid os::init_system_properties_values() {
0N/A// char arch[12];
0N/A// sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
0N/A
0N/A // The next steps are taken in the product version:
0N/A //
0N/A // Obtain the JAVA_HOME value from the location of libjvm[_g].so.
0N/A // This library should be located at:
0N/A // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so.
0N/A //
0N/A // If "/jre/lib/" appears at the right place in the path, then we
0N/A // assume libjvm[_g].so is installed in a JDK and we use this path.
0N/A //
0N/A // Otherwise exit with message: "Could not create the Java virtual machine."
0N/A //
0N/A // The following extra steps are taken in the debugging version:
0N/A //
0N/A // If "/jre/lib/" does NOT appear at the right place in the path
0N/A // instead of exit check for $JAVA_HOME environment variable.
0N/A //
0N/A // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
0N/A // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so
0N/A // it looks like libjvm[_g].so is installed there
0N/A // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so.
0N/A //
0N/A // Otherwise exit.
0N/A //
0N/A // Important note: if the location of libjvm.so changes this
0N/A // code needs to be changed accordingly.
0N/A
0N/A // The next few definitions allow the code to be verbatim:
3863N/A#define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
0N/A#define getenv(n) ::getenv(n)
0N/A
0N/A/*
0N/A * See ld(1):
0N/A * The linker uses the following search paths to locate required
0N/A * shared libraries:
0N/A * 1: ...
0N/A * ...
0N/A * 7: The default directories, normally /lib and /usr/lib.
0N/A */
509N/A#if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390))
509N/A#define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
509N/A#else
0N/A#define DEFAULT_LIBPATH "/lib:/usr/lib"
509N/A#endif
0N/A
0N/A#define EXTENSIONS_DIR "/lib/ext"
0N/A#define ENDORSED_DIR "/lib/endorsed"
0N/A#define REG_DIR "/usr/java/packages"
0N/A
0N/A {
0N/A /* sysclasspath, java_home, dll_dir */
0N/A {
0N/A char *home_path;
0N/A char *dll_path;
0N/A char *pslash;
0N/A char buf[MAXPATHLEN];
0N/A os::jvm_path(buf, sizeof(buf));
0N/A
0N/A // Found the full path to libjvm.so.
0N/A // Now cut the path to <java_home>/jre if we can.
0N/A *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */
0N/A pslash = strrchr(buf, '/');
0N/A if (pslash != NULL)
0N/A *pslash = '\0'; /* get rid of /{client|server|hotspot} */
0N/A dll_path = malloc(strlen(buf) + 1);
0N/A if (dll_path == NULL)
0N/A return;
0N/A strcpy(dll_path, buf);
0N/A Arguments::set_dll_dir(dll_path);
0N/A
0N/A if (pslash != NULL) {
0N/A pslash = strrchr(buf, '/');
0N/A if (pslash != NULL) {
0N/A *pslash = '\0'; /* get rid of /<arch> */
0N/A pslash = strrchr(buf, '/');
0N/A if (pslash != NULL)
0N/A *pslash = '\0'; /* get rid of /lib */
0N/A }
0N/A }
0N/A
0N/A home_path = malloc(strlen(buf) + 1);
0N/A if (home_path == NULL)
0N/A return;
0N/A strcpy(home_path, buf);
0N/A Arguments::set_java_home(home_path);
0N/A
0N/A if (!set_boot_path('/', ':'))
0N/A return;
0N/A }
0N/A
0N/A /*
0N/A * Where to look for native libraries
0N/A *
0N/A * Note: Due to a legacy implementation, most of the library path
0N/A * is set in the launcher. This was to accomodate linking restrictions
0N/A * on legacy Linux implementations (which are no longer supported).
0N/A * Eventually, all the library path setting will be done here.
0N/A *
0N/A * However, to prevent the proliferation of improperly built native
0N/A * libraries, the new path component /usr/java/packages is added here.
0N/A * Eventually, all the library path setting will be done here.
0N/A */
0N/A {
0N/A char *ld_library_path;
0N/A
0N/A /*
0N/A * Construct the invariant part of ld_library_path. Note that the
0N/A * space for the colon and the trailing null are provided by the
0N/A * nulls included by the sizeof operator (so actually we allocate
0N/A * a byte more than necessary).
0N/A */
0N/A ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
0N/A strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
0N/A sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
0N/A
0N/A /*
0N/A * Get the user setting of LD_LIBRARY_PATH, and prepended it. It
0N/A * should always exist (until the legacy problem cited above is
0N/A * addressed).
0N/A */
0N/A char *v = getenv("LD_LIBRARY_PATH");
0N/A if (v != NULL) {
0N/A char *t = ld_library_path;
0N/A /* That's +1 for the colon and +1 for the trailing '\0' */
0N/A ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
0N/A sprintf(ld_library_path, "%s:%s", v, t);
0N/A }
0N/A Arguments::set_library_path(ld_library_path);
0N/A }
0N/A
0N/A /*
0N/A * Extensions directories.
0N/A *
0N/A * Note that the space for the colon and the trailing null are provided
0N/A * by the nulls included by the sizeof operator (so actually one byte more
0N/A * than necessary is allocated).
0N/A */
0N/A {
0N/A char *buf = malloc(strlen(Arguments::get_java_home()) +
0N/A sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
0N/A sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
0N/A Arguments::get_java_home());
0N/A Arguments::set_ext_dirs(buf);
0N/A }
0N/A
0N/A /* Endorsed standards default directory. */
0N/A {
0N/A char * buf;
0N/A buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
0N/A sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
0N/A Arguments::set_endorsed_dirs(buf);
0N/A }
0N/A }
0N/A
0N/A#undef malloc
0N/A#undef getenv
0N/A#undef EXTENSIONS_DIR
0N/A#undef ENDORSED_DIR
0N/A
0N/A // Done
0N/A return;
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// breakpoint support
0N/A
0N/Avoid os::breakpoint() {
0N/A BREAKPOINT;
0N/A}
0N/A
0N/Aextern "C" void breakpoint() {
0N/A // use debugger to set breakpoint here
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// signal support
0N/A
0N/Adebug_only(static bool signal_sets_initialized = false);
0N/Astatic sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
0N/A
0N/Abool os::Linux::is_sig_ignored(int sig) {
0N/A struct sigaction oact;
0N/A sigaction(sig, (struct sigaction*)NULL, &oact);
0N/A void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)
0N/A : CAST_FROM_FN_PTR(void*, oact.sa_handler);
0N/A if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
0N/A return true;
0N/A else
0N/A return false;
0N/A}
0N/A
0N/Avoid os::Linux::signal_sets_init() {
0N/A // Should also have an assertion stating we are still single-threaded.
0N/A assert(!signal_sets_initialized, "Already initialized");
0N/A // Fill in signals that are necessarily unblocked for all threads in
0N/A // the VM. Currently, we unblock the following signals:
0N/A // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
0N/A // by -Xrs (=ReduceSignalUsage));
0N/A // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
0N/A // other threads. The "ReduceSignalUsage" boolean tells us not to alter
0N/A // the dispositions or masks wrt these signals.
0N/A // Programs embedding the VM that want to use the above signals for their
0N/A // own purposes must, at this time, use the "-Xrs" option to prevent
0N/A // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
0N/A // (See bug 4345157, and other related bugs).
0N/A // In reality, though, unblocking these signals is really a nop, since
0N/A // these signals are not blocked by default.
0N/A sigemptyset(&unblocked_sigs);
0N/A sigemptyset(&allowdebug_blocked_sigs);
0N/A sigaddset(&unblocked_sigs, SIGILL);
0N/A sigaddset(&unblocked_sigs, SIGSEGV);
0N/A sigaddset(&unblocked_sigs, SIGBUS);
0N/A sigaddset(&unblocked_sigs, SIGFPE);
0N/A sigaddset(&unblocked_sigs, SR_signum);
0N/A
0N/A if (!ReduceSignalUsage) {
0N/A if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
0N/A sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
0N/A sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
0N/A }
0N/A if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
0N/A sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
0N/A sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
0N/A }
0N/A if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
0N/A sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
0N/A sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
0N/A }
0N/A }
0N/A // Fill in signals that are blocked by all but the VM thread.
0N/A sigemptyset(&vm_sigs);
0N/A if (!ReduceSignalUsage)
0N/A sigaddset(&vm_sigs, BREAK_SIGNAL);
0N/A debug_only(signal_sets_initialized = true);
0N/A
0N/A}
0N/A
0N/A// These are signals that are unblocked while a thread is running Java.
0N/A// (For some reason, they get blocked by default.)
0N/Asigset_t* os::Linux::unblocked_signals() {
0N/A assert(signal_sets_initialized, "Not initialized");
0N/A return &unblocked_sigs;
0N/A}
0N/A
0N/A// These are the signals that are blocked while a (non-VM) thread is
0N/A// running Java. Only the VM thread handles these signals.
0N/Asigset_t* os::Linux::vm_signals() {
0N/A assert(signal_sets_initialized, "Not initialized");
0N/A return &vm_sigs;
0N/A}
0N/A
0N/A// These are signals that are blocked during cond_wait to allow debugger in
0N/Asigset_t* os::Linux::allowdebug_blocked_signals() {
0N/A assert(signal_sets_initialized, "Not initialized");
0N/A return &allowdebug_blocked_sigs;
0N/A}
0N/A
0N/Avoid os::Linux::hotspot_sigmask(Thread* thread) {
0N/A
0N/A //Save caller's signal mask before setting VM signal mask
0N/A sigset_t caller_sigmask;
0N/A pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
0N/A
0N/A OSThread* osthread = thread->osthread();
0N/A osthread->set_caller_sigmask(caller_sigmask);
0N/A
0N/A pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL);
0N/A
0N/A if (!ReduceSignalUsage) {
0N/A if (thread->is_VM_thread()) {
0N/A // Only the VM thread handles BREAK_SIGNAL ...
0N/A pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
0N/A } else {
0N/A // ... all other threads block BREAK_SIGNAL
0N/A pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
0N/A }
0N/A }
0N/A}
0N/A
0N/A//////////////////////////////////////////////////////////////////////////////
0N/A// detecting pthread library
0N/A
0N/Avoid os::Linux::libpthread_init() {
0N/A // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION
0N/A // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a
0N/A // generic name for earlier versions.
0N/A // Define macros here so we can build HotSpot on old systems.
0N/A# ifndef _CS_GNU_LIBC_VERSION
0N/A# define _CS_GNU_LIBC_VERSION 2
0N/A# endif
0N/A# ifndef _CS_GNU_LIBPTHREAD_VERSION
0N/A# define _CS_GNU_LIBPTHREAD_VERSION 3
0N/A# endif
0N/A
0N/A size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
0N/A if (n > 0) {
3863N/A char *str = (char *)malloc(n, mtInternal);
0N/A confstr(_CS_GNU_LIBC_VERSION, str, n);
0N/A os::Linux::set_glibc_version(str);
0N/A } else {
0N/A // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
0N/A static char _gnu_libc_version[32];
0N/A jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version),
0N/A "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release());
0N/A os::Linux::set_glibc_version(_gnu_libc_version);
0N/A }
0N/A
0N/A n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
0N/A if (n > 0) {
3863N/A char *str = (char *)malloc(n, mtInternal);
0N/A confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
0N/A // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells
0N/A // us "NPTL-0.29" even we are running with LinuxThreads. Check if this
199N/A // is the case. LinuxThreads has a hard limit on max number of threads.
199N/A // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value.
199N/A // On the other hand, NPTL does not have such a limit, sysconf()
199N/A // will return -1 and errno is not changed. Check if it is really NPTL.
0N/A if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 &&
199N/A strstr(str, "NPTL") &&
199N/A sysconf(_SC_THREAD_THREADS_MAX) > 0) {
199N/A free(str);
199N/A os::Linux::set_libpthread_version("linuxthreads");
199N/A } else {
199N/A os::Linux::set_libpthread_version(str);
0N/A }
0N/A } else {
199N/A // glibc before 2.3.2 only has LinuxThreads.
199N/A os::Linux::set_libpthread_version("linuxthreads");
0N/A }
0N/A
0N/A if (strstr(libpthread_version(), "NPTL")) {
0N/A os::Linux::set_is_NPTL();
0N/A } else {
0N/A os::Linux::set_is_LinuxThreads();
0N/A }
0N/A
0N/A // LinuxThreads have two flavors: floating-stack mode, which allows variable
0N/A // stack size; and fixed-stack mode. NPTL is always floating-stack.
0N/A if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) {
0N/A os::Linux::set_is_floating_stack();
0N/A }
0N/A}
0N/A
0N/A/////////////////////////////////////////////////////////////////////////////
0N/A// thread stack
0N/A
0N/A// Force Linux kernel to expand current thread stack. If "bottom" is close
0N/A// to the stack guard, caller should block all signals.
0N/A//
0N/A// MAP_GROWSDOWN:
0N/A// A special mmap() flag that is used to implement thread stacks. It tells
0N/A// kernel that the memory region should extend downwards when needed. This
0N/A// allows early versions of LinuxThreads to only mmap the first few pages
0N/A// when creating a new thread. Linux kernel will automatically expand thread
0N/A// stack as needed (on page faults).
0N/A//
0N/A// However, because the memory region of a MAP_GROWSDOWN stack can grow on
0N/A// demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
0N/A// region, it's hard to tell if the fault is due to a legitimate stack
0N/A// access or because of reading/writing non-exist memory (e.g. buffer
0N/A// overrun). As a rule, if the fault happens below current stack pointer,
0N/A// Linux kernel does not expand stack, instead a SIGSEGV is sent to the
0N/A// application (see Linux kernel fault.c).
0N/A//
0N/A// This Linux feature can cause SIGSEGV when VM bangs thread stack for
0N/A// stack overflow detection.
0N/A//
0N/A// Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
0N/A// not use this flag. However, the stack of initial thread is not created
0N/A// by pthread, it is still MAP_GROWSDOWN. Also it's possible (though
0N/A// unlikely) that user code can create a thread with MAP_GROWSDOWN stack
0N/A// and then attach the thread to JVM.
0N/A//
0N/A// To get around the problem and allow stack banging on Linux, we need to
0N/A// manually expand thread stack after receiving the SIGSEGV.
0N/A//
0N/A// There are two ways to expand thread stack to address "bottom", we used
0N/A// both of them in JVM before 1.5:
0N/A// 1. adjust stack pointer first so that it is below "bottom", and then
0N/A// touch "bottom"
0N/A// 2. mmap() the page in question
0N/A//
0N/A// Now alternate signal stack is gone, it's harder to use 2. For instance,
0N/A// if current sp is already near the lower end of page 101, and we need to
0N/A// call mmap() to map page 100, it is possible that part of the mmap() frame
0N/A// will be placed in page 100. When page 100 is mapped, it is zero-filled.
0N/A// That will destroy the mmap() frame and cause VM to crash.
0N/A//
0N/A// The following code works by adjusting sp first, then accessing the "bottom"
0N/A// page to force a page fault. Linux kernel will then automatically expand the
0N/A// stack mapping.
0N/A//
0N/A// _expand_stack_to() assumes its frame size is less than page size, which
0N/A// should always be true if the function is not inlined.
0N/A
0N/A#if __GNUC__ < 3 // gcc 2.x does not support noinline attribute
0N/A#define NOINLINE
0N/A#else
0N/A#define NOINLINE __attribute__ ((noinline))
0N/A#endif
0N/A
0N/Astatic void _expand_stack_to(address bottom) NOINLINE;
0N/A
0N/Astatic void _expand_stack_to(address bottom) {
0N/A address sp;
0N/A size_t size;
0N/A volatile char *p;
0N/A
0N/A // Adjust bottom to point to the largest address within the same page, it
0N/A // gives us a one-page buffer if alloca() allocates slightly more memory.
0N/A bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size());
0N/A bottom += os::Linux::page_size() - 1;
0N/A
0N/A // sp might be slightly above current stack pointer; if that's the case, we
0N/A // will alloca() a little more space than necessary, which is OK. Don't use
0N/A // os::current_stack_pointer(), as its result can be slightly below current
0N/A // stack pointer, causing us to not alloca enough to reach "bottom".
0N/A sp = (address)&sp;
0N/A
0N/A if (sp > bottom) {
0N/A size = sp - bottom;
0N/A p = (volatile char *)alloca(size);
0N/A assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");
0N/A p[0] = '\0';
0N/A }
0N/A}
0N/A
0N/Abool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
0N/A assert(t!=NULL, "just checking");
0N/A assert(t->osthread()->expanding_stack(), "expand should be set");
0N/A assert(t->stack_base() != NULL, "stack_base was not initialized");
0N/A
0N/A if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) {
0N/A sigset_t mask_all, old_sigset;
0N/A sigfillset(&mask_all);
0N/A pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
0N/A _expand_stack_to(addr);
0N/A pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);
0N/A return true;
0N/A }
0N/A return false;
0N/A}
0N/A
0N/A//////////////////////////////////////////////////////////////////////////////
0N/A// create new thread
0N/A
0N/Astatic address highest_vm_reserved_address();
0N/A
0N/A// check if it's safe to start a new thread
0N/Astatic bool _thread_safety_check(Thread* thread) {
0N/A if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) {
0N/A // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat)
0N/A // Heap is mmap'ed at lower end of memory space. Thread stacks are
0N/A // allocated (MAP_FIXED) from high address space. Every thread stack
0N/A // occupies a fixed size slot (usually 2Mbytes, but user can change
0N/A // it to other values if they rebuild LinuxThreads).
0N/A //
0N/A // Problem with MAP_FIXED is that mmap() can still succeed even part of
0N/A // the memory region has already been mmap'ed. That means if we have too
0N/A // many threads and/or very large heap, eventually thread stack will
0N/A // collide with heap.
0N/A //
0N/A // Here we try to prevent heap/stack collision by comparing current
0N/A // stack bottom with the highest address that has been mmap'ed by JVM
0N/A // plus a safety margin for memory maps created by native code.
0N/A //
0N/A // This feature can be disabled by setting ThreadSafetyMargin to 0
0N/A //
0N/A if (ThreadSafetyMargin > 0) {
0N/A address stack_bottom = os::current_stack_base() - os::current_stack_size();
0N/A
0N/A // not safe if our stack extends below the safety margin
0N/A return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address();
0N/A } else {
0N/A return true;
0N/A }
0N/A } else {
0N/A // Floating stack LinuxThreads or NPTL:
0N/A // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When
0N/A // there's not enough space left, pthread_create() will fail. If we come
0N/A // here, that means enough space has been reserved for stack.
0N/A return true;
0N/A }
0N/A}
0N/A
0N/A// Thread start routine for all newly created threads
0N/Astatic void *java_start(Thread *thread) {
0N/A // Try to randomize the cache line index of hot stack frames.
0N/A // This helps when threads of the same stack traces evict each other's
0N/A // cache lines. The threads can be either from the same JVM instance, or
0N/A // from different JVM instances. The benefit is especially true for
0N/A // processors with hyperthreading technology.
0N/A static int counter = 0;
0N/A int pid = os::current_process_id();
0N/A alloca(((pid ^ counter++) & 7) * 128);
0N/A
0N/A ThreadLocalStorage::set_thread(thread);
0N/A
0N/A OSThread* osthread = thread->osthread();
0N/A Monitor* sync = osthread->startThread_lock();
0N/A
0N/A // non floating stack LinuxThreads needs extra check, see above
0N/A if (!_thread_safety_check(thread)) {
0N/A // notify parent thread
0N/A MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
0N/A osthread->set_state(ZOMBIE);
0N/A sync->notify_all();
0N/A return NULL;
0N/A }
0N/A
0N/A // thread_id is kernel thread id (similar to Solaris LWP id)
0N/A osthread->set_thread_id(os::Linux::gettid());
0N/A
0N/A if (UseNUMA) {
0N/A int lgrp_id = os::numa_get_group_id();
0N/A if (lgrp_id != -1) {
0N/A thread->set_lgrp_id(lgrp_id);
0N/A }
0N/A }
0N/A // initialize signal mask for this thread
0N/A os::Linux::hotspot_sigmask(thread);
0N/A
0N/A // initialize floating point control register
0N/A os::Linux::init_thread_fpu_state();
0N/A
0N/A // handshaking with parent thread
0N/A {
0N/A MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
0N/A
0N/A // notify parent thread
0N/A osthread->set_state(INITIALIZED);
0N/A sync->notify_all();
0N/A
0N/A // wait until os::start_thread()
0N/A while (osthread->get_state() == INITIALIZED) {
0N/A sync->wait(Mutex::_no_safepoint_check_flag);
0N/A }
0N/A }
0N/A
0N/A // call one more level start routine
0N/A thread->run();
0N/A
0N/A return 0;
0N/A}
0N/A
0N/Abool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
0N/A assert(thread->osthread() == NULL, "caller responsible");
0N/A
0N/A // Allocate the OSThread object
0N/A OSThread* osthread = new OSThread(NULL, NULL);
0N/A if (osthread == NULL) {
0N/A return false;
0N/A }
0N/A
0N/A // set the correct thread state
0N/A osthread->set_thread_type(thr_type);
0N/A
0N/A // Initial state is ALLOCATED but not INITIALIZED
0N/A osthread->set_state(ALLOCATED);
0N/A
0N/A thread->set_osthread(osthread);
0N/A
0N/A // init thread attributes
0N/A pthread_attr_t attr;
0N/A pthread_attr_init(&attr);
0N/A pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
0N/A
0N/A // stack size
0N/A if (os::Linux::supports_variable_stack_size()) {
0N/A // calculate stack size if it's not specified by caller
0N/A if (stack_size == 0) {
0N/A stack_size = os::Linux::default_stack_size(thr_type);
0N/A
0N/A switch (thr_type) {
0N/A case os::java_thread:
1787N/A // Java threads use ThreadStackSize which default value can be
1787N/A // changed with the flag -Xss
1787N/A assert (JavaThread::stack_size_at_create() > 0, "this should be set");
1787N/A stack_size = JavaThread::stack_size_at_create();
0N/A break;
0N/A case os::compiler_thread:
0N/A if (CompilerThreadStackSize > 0) {
0N/A stack_size = (size_t)(CompilerThreadStackSize * K);
0N/A break;
0N/A } // else fall through:
0N/A // use VMThreadStackSize if CompilerThreadStackSize is not defined
0N/A case os::vm_thread:
0N/A case os::pgc_thread:
0N/A case os::cgc_thread:
0N/A case os::watcher_thread:
0N/A if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
0N/A break;
0N/A }
0N/A }
0N/A
0N/A stack_size = MAX2(stack_size, os::Linux::min_stack_allowed);
0N/A pthread_attr_setstacksize(&attr, stack_size);
0N/A } else {
0N/A // let pthread_create() pick the default value.
0N/A }
0N/A
0N/A // glibc guard page
0N/A pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type));
0N/A
0N/A ThreadState state;
0N/A
0N/A {
0N/A // Serialize thread creation if we are running with fixed stack LinuxThreads
0N/A bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack();
0N/A if (lock) {
0N/A os::Linux::createThread_lock()->lock_without_safepoint_check();
0N/A }
0N/A
0N/A pthread_t tid;
0N/A int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
0N/A
0N/A pthread_attr_destroy(&attr);
0N/A
0N/A if (ret != 0) {
0N/A if (PrintMiscellaneous && (Verbose || WizardMode)) {
0N/A perror("pthread_create()");
0N/A }
0N/A // Need to clean up stuff we've allocated so far
0N/A thread->set_osthread(NULL);
0N/A delete osthread;
0N/A if (lock) os::Linux::createThread_lock()->unlock();
0N/A return false;
0N/A }
0N/A
0N/A // Store pthread info into the OSThread
0N/A osthread->set_pthread_id(tid);
0N/A
0N/A // Wait until child thread is either initialized or aborted
0N/A {
0N/A Monitor* sync_with_child = osthread->startThread_lock();
0N/A MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
0N/A while ((state = osthread->get_state()) == ALLOCATED) {
0N/A sync_with_child->wait(Mutex::_no_safepoint_check_flag);
0N/A }
0N/A }
0N/A
0N/A if (lock) {
0N/A os::Linux::createThread_lock()->unlock();
0N/A }
0N/A }
0N/A
0N/A // Aborted due to thread limit being reached
0N/A if (state == ZOMBIE) {
0N/A thread->set_osthread(NULL);
0N/A delete osthread;
0N/A return false;
0N/A }
0N/A
0N/A // The thread is returned suspended (in state INITIALIZED),
0N/A // and is started higher up in the call chain
0N/A assert(state == INITIALIZED, "race condition");
0N/A return true;
0N/A}
0N/A
0N/A/////////////////////////////////////////////////////////////////////////////
0N/A// attach existing thread
0N/A
0N/A// bootstrap the main thread
0N/Abool os::create_main_thread(JavaThread* thread) {
0N/A assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
0N/A return create_attached_thread(thread);
0N/A}
0N/A
0N/Abool os::create_attached_thread(JavaThread* thread) {
0N/A#ifdef ASSERT
0N/A thread->verify_not_published();
0N/A#endif
0N/A
0N/A // Allocate the OSThread object
0N/A OSThread* osthread = new OSThread(NULL, NULL);
0N/A
0N/A if (osthread == NULL) {
0N/A return false;
0N/A }
0N/A
0N/A // Store pthread info into the OSThread
0N/A osthread->set_thread_id(os::Linux::gettid());
0N/A osthread->set_pthread_id(::pthread_self());
0N/A
0N/A // initialize floating point control register
0N/A os::Linux::init_thread_fpu_state();
0N/A
0N/A // Initial thread state is RUNNABLE
0N/A osthread->set_state(RUNNABLE);
0N/A
0N/A thread->set_osthread(osthread);
0N/A
0N/A if (UseNUMA) {
0N/A int lgrp_id = os::numa_get_group_id();
0N/A if (lgrp_id != -1) {
0N/A thread->set_lgrp_id(lgrp_id);
0N/A }
0N/A }
0N/A
0N/A if (os::Linux::is_initial_thread()) {
0N/A // If current thread is initial thread, its stack is mapped on demand,
0N/A // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
0N/A // the entire stack region to avoid SEGV in stack banging.
0N/A // It is also useful to get around the heap-stack-gap problem on SuSE
0N/A // kernel (see 4821821 for details). We first expand stack to the top
0N/A // of yellow zone, then enable stack yellow zone (order is significant,
0N/A // enabling yellow zone first will crash JVM on SuSE Linux), so there
0N/A // is no gap between the last two virtual memory regions.
0N/A
0N/A JavaThread *jt = (JavaThread *)thread;
0N/A address addr = jt->stack_yellow_zone_base();
0N/A assert(addr != NULL, "initialization problem?");
0N/A assert(jt->stack_available(addr) > 0, "stack guard should not be enabled");
0N/A
0N/A osthread->set_expanding_stack();
0N/A os::Linux::manually_expand_stack(jt, addr);
0N/A osthread->clear_expanding_stack();
0N/A }
0N/A
0N/A // initialize signal mask for this thread
0N/A // and save the caller's signal mask
0N/A os::Linux::hotspot_sigmask(thread);
0N/A
0N/A return true;
0N/A}
0N/A
0N/Avoid os::pd_start_thread(Thread* thread) {
0N/A OSThread * osthread = thread->osthread();
0N/A assert(osthread->get_state() != INITIALIZED, "just checking");
0N/A Monitor* sync_with_child = osthread->startThread_lock();
0N/A MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
0N/A sync_with_child->notify();
0N/A}
0N/A
0N/A// Free Linux resources related to the OSThread
0N/Avoid os::free_thread(OSThread* osthread) {
0N/A assert(osthread != NULL, "osthread not set");
0N/A
0N/A if (Thread::current()->osthread() == osthread) {
0N/A // Restore caller's signal mask
0N/A sigset_t sigmask = osthread->caller_sigmask();
0N/A pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
0N/A }
0N/A
0N/A delete osthread;
0N/A}
0N/A
0N/A//////////////////////////////////////////////////////////////////////////////
0N/A// thread local storage
0N/A
0N/Aint os::allocate_thread_local_storage() {
0N/A pthread_key_t key;
0N/A int rslt = pthread_key_create(&key, NULL);
0N/A assert(rslt == 0, "cannot allocate thread local storage");
0N/A return (int)key;
0N/A}
0N/A
0N/A// Note: This is currently not used by VM, as we don't destroy TLS key
0N/A// on VM exit.
0N/Avoid os::free_thread_local_storage(int index) {
0N/A int rslt = pthread_key_delete((pthread_key_t)index);
0N/A assert(rslt == 0, "invalid index");
0N/A}
0N/A
0N/Avoid os::thread_local_storage_at_put(int index, void* value) {
0N/A int rslt = pthread_setspecific((pthread_key_t)index, value);
0N/A assert(rslt == 0, "pthread_setspecific failed");
0N/A}
0N/A
0N/Aextern "C" Thread* get_thread() {
0N/A return ThreadLocalStorage::thread();
0N/A}
0N/A
0N/A//////////////////////////////////////////////////////////////////////////////
0N/A// initial thread
0N/A
0N/A// Check if current thread is the initial thread, similar to Solaris thr_main.
0N/Abool os::Linux::is_initial_thread(void) {
0N/A char dummy;
0N/A // If called before init complete, thread stack bottom will be null.
0N/A // Can be called if fatal error occurs before initialization.
0N/A if (initial_thread_stack_bottom() == NULL) return false;
0N/A assert(initial_thread_stack_bottom() != NULL &&
0N/A initial_thread_stack_size() != 0,
0N/A "os::init did not locate initial thread's stack region");
0N/A if ((address)&dummy >= initial_thread_stack_bottom() &&
0N/A (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size())
0N/A return true;
0N/A else return false;
0N/A}
0N/A
0N/A// Find the virtual memory area that contains addr
0N/Astatic bool find_vma(address addr, address* vma_low, address* vma_high) {
0N/A FILE *fp = fopen("/proc/self/maps", "r");
0N/A if (fp) {
0N/A address low, high;
0N/A while (!feof(fp)) {
0N/A if (fscanf(fp, "%p-%p", &low, &high) == 2) {
0N/A if (low <= addr && addr < high) {
0N/A if (vma_low) *vma_low = low;
0N/A if (vma_high) *vma_high = high;
0N/A fclose (fp);
0N/A return true;
0N/A }
0N/A }
0N/A for (;;) {
0N/A int ch = fgetc(fp);
0N/A if (ch == EOF || ch == (int)'\n') break;
0N/A }
0N/A }
0N/A fclose(fp);
0N/A }
0N/A return false;
0N/A}
0N/A
0N/A// Locate initial thread stack. This special handling of initial thread stack
0N/A// is needed because pthread_getattr_np() on most (all?) Linux distros returns
0N/A// bogus value for initial thread.
0N/Avoid os::Linux::capture_initial_stack(size_t max_size) {
0N/A // stack size is the easy part, get it from RLIMIT_STACK
0N/A size_t stack_size;
0N/A struct rlimit rlim;
0N/A getrlimit(RLIMIT_STACK, &rlim);
0N/A stack_size = rlim.rlim_cur;
0N/A
0N/A // 6308388: a bug in ld.so will relocate its own .data section to the
0N/A // lower end of primordial stack; reduce ulimit -s value a little bit
0N/A // so we won't install guard page on ld.so's data section.
0N/A stack_size -= 2 * page_size();
0N/A
0N/A // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat
0N/A // 7.1, in both cases we will get 2G in return value.
0N/A // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0,
0N/A // SuSE 7.2, Debian) can not handle alternate signal stack correctly
0N/A // for initial thread if its stack size exceeds 6M. Cap it at 2M,
0N/A // in case other parts in glibc still assumes 2M max stack size.
0N/A // FIXME: alt signal stack is gone, maybe we can relax this constraint?
0N/A#ifndef IA64
0N/A if (stack_size > 2 * K * K) stack_size = 2 * K * K;
0N/A#else
0N/A // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small
0N/A if (stack_size > 4 * K * K) stack_size = 4 * K * K;
0N/A#endif
0N/A
0N/A // Try to figure out where the stack base (top) is. This is harder.
0N/A //
0N/A // When an application is started, glibc saves the initial stack pointer in
0N/A // a global variable "__libc_stack_end", which is then used by system
0N/A // libraries. __libc_stack_end should be pretty close to stack top. The
0N/A // variable is available since the very early days. However, because it is
0N/A // a private interface, it could disappear in the future.
0N/A //
0N/A // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
0N/A // to __libc_stack_end, it is very close to stack top, but isn't the real
0N/A // stack top. Note that /proc may not exist if VM is running as a chroot
0N/A // program, so reading /proc/<pid>/stat could fail. Also the contents of
0N/A // /proc/<pid>/stat could change in the future (though unlikely).
0N/A //
0N/A // We try __libc_stack_end first. If that doesn't work, look for
0N/A // /proc/<pid>/stat. If neither of them works, we use current stack pointer
0N/A // as a hint, which should work well in most cases.
0N/A
0N/A uintptr_t stack_start;
0N/A
0N/A // try __libc_stack_end first
0N/A uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
0N/A if (p && *p) {
0N/A stack_start = *p;
0N/A } else {
0N/A // see if we can get the start_stack field from /proc/self/stat
0N/A FILE *fp;
0N/A int pid;
0N/A char state;
0N/A int ppid;
0N/A int pgrp;
0N/A int session;
0N/A int nr;
0N/A int tpgrp;
0N/A unsigned long flags;
0N/A unsigned long minflt;
0N/A unsigned long cminflt;
0N/A unsigned long majflt;
0N/A unsigned long cmajflt;
0N/A unsigned long utime;
0N/A unsigned long stime;
0N/A long cutime;
0N/A long cstime;
0N/A long prio;
0N/A long nice;
0N/A long junk;
0N/A long it_real;
0N/A uintptr_t start;
0N/A uintptr_t vsize;
1601N/A intptr_t rss;
1601N/A uintptr_t rsslim;
0N/A uintptr_t scodes;
0N/A uintptr_t ecode;
0N/A int i;
0N/A
0N/A // Figure what the primordial thread stack base is. Code is inspired
0N/A // by email from Hans Boehm. /proc/self/stat begins with current pid,
0N/A // followed by command name surrounded by parentheses, state, etc.
0N/A char stat[2048];
0N/A int statlen;
0N/A
0N/A fp = fopen("/proc/self/stat", "r");
0N/A if (fp) {
0N/A statlen = fread(stat, 1, 2047, fp);
0N/A stat[statlen] = '\0';
0N/A fclose(fp);
0N/A
0N/A // Skip pid and the command string. Note that we could be dealing with
0N/A // weird command names, e.g. user could decide to rename java launcher
0N/A // to "java 1.4.2 :)", then the stat file would look like
0N/A // 1234 (java 1.4.2 :)) R ... ...
0N/A // We don't really need to know the command string, just find the last
0N/A // occurrence of ")" and then start parsing from there. See bug 4726580.
0N/A char * s = strrchr(stat, ')');
0N/A
0N/A i = 0;
0N/A if (s) {
0N/A // Skip blank chars
0N/A do s++; while (isspace(*s));
0N/A
1601N/A#define _UFM UINTX_FORMAT
1601N/A#define _DFM INTX_FORMAT
1601N/A
1601N/A /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */
1601N/A /* 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 */
1601N/A 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,
0N/A &state, /* 3 %c */
0N/A &ppid, /* 4 %d */
0N/A &pgrp, /* 5 %d */
0N/A &session, /* 6 %d */
0N/A &nr, /* 7 %d */
0N/A &tpgrp, /* 8 %d */
0N/A &flags, /* 9 %lu */
0N/A &minflt, /* 10 %lu */
0N/A &cminflt, /* 11 %lu */
0N/A &majflt, /* 12 %lu */
0N/A &cmajflt, /* 13 %lu */
0N/A &utime, /* 14 %lu */
0N/A &stime, /* 15 %lu */
0N/A &cutime, /* 16 %ld */
0N/A &cstime, /* 17 %ld */
0N/A &prio, /* 18 %ld */
0N/A &nice, /* 19 %ld */
0N/A &junk, /* 20 %ld */
0N/A &it_real, /* 21 %ld */
1601N/A &start, /* 22 UINTX_FORMAT */
1601N/A &vsize, /* 23 UINTX_FORMAT */
1601N/A &rss, /* 24 INTX_FORMAT */
1601N/A &rsslim, /* 25 UINTX_FORMAT */
1601N/A &scodes, /* 26 UINTX_FORMAT */
1601N/A &ecode, /* 27 UINTX_FORMAT */
1601N/A &stack_start); /* 28 UINTX_FORMAT */
0N/A }
0N/A
1601N/A#undef _UFM
1601N/A#undef _DFM
1601N/A
0N/A if (i != 28 - 2) {
0N/A assert(false, "Bad conversion from /proc/self/stat");
0N/A // product mode - assume we are the initial thread, good luck in the
0N/A // embedded case.
0N/A warning("Can't detect initial thread stack location - bad conversion");
0N/A stack_start = (uintptr_t) &rlim;
0N/A }
0N/A } else {
0N/A // For some reason we can't open /proc/self/stat (for example, running on
0N/A // FreeBSD with a Linux emulator, or inside chroot), this should work for
0N/A // most cases, so don't abort:
0N/A warning("Can't detect initial thread stack location - no /proc/self/stat");
0N/A stack_start = (uintptr_t) &rlim;
0N/A }
0N/A }
0N/A
0N/A // Now we have a pointer (stack_start) very close to the stack top, the
0N/A // next thing to do is to figure out the exact location of stack top. We
0N/A // can find out the virtual memory area that contains stack_start by
0N/A // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
0N/A // and its upper limit is the real stack top. (again, this would fail if
0N/A // running inside chroot, because /proc may not exist.)
0N/A
0N/A uintptr_t stack_top;
0N/A address low, high;
0N/A if (find_vma((address)stack_start, &low, &high)) {
0N/A // success, "high" is the true stack top. (ignore "low", because initial
0N/A // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
0N/A stack_top = (uintptr_t)high;
0N/A } else {
0N/A // failed, likely because /proc/self/maps does not exist
0N/A warning("Can't detect initial thread stack location - find_vma failed");
0N/A // best effort: stack_start is normally within a few pages below the real
0N/A // stack top, use it as stack top, and reduce stack size so we won't put
0N/A // guard page outside stack.
0N/A stack_top = stack_start;
0N/A stack_size -= 16 * page_size();
0N/A }
0N/A
0N/A // stack_top could be partially down the page so align it
0N/A stack_top = align_size_up(stack_top, page_size());
0N/A
0N/A if (max_size && stack_size > max_size) {
0N/A _initial_thread_stack_size = max_size;
0N/A } else {
0N/A _initial_thread_stack_size = stack_size;
0N/A }
0N/A
0N/A _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size());
0N/A _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// time support
0N/A
0N/A// Time since start-up in seconds to a fine granularity.
0N/A// Used by VMSelfDestructTimer and the MemProfiler.
0N/Adouble os::elapsedTime() {
0N/A
0N/A return (double)(os::elapsed_counter()) * 0.000001;
0N/A}
0N/A
0N/Ajlong os::elapsed_counter() {
0N/A timeval time;
0N/A int status = gettimeofday(&time, NULL);
0N/A return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
0N/A}
0N/A
0N/Ajlong os::elapsed_frequency() {
0N/A return (1000 * 1000);
0N/A}
0N/A
342N/A// For now, we say that linux does not support vtime. I have no idea
342N/A// whether it can actually be made to (DLD, 9/13/05).
342N/A
342N/Abool os::supports_vtime() { return false; }
342N/Abool os::enable_vtime() { return false; }
342N/Abool os::vtime_enabled() { return false; }
342N/Adouble os::elapsedVTime() {
342N/A // better than nothing, but not much
342N/A return elapsedTime();
342N/A}
342N/A
61N/Ajlong os::javaTimeMillis() {
0N/A timeval time;
0N/A int status = gettimeofday(&time, NULL);
0N/A assert(status != -1, "linux error");
0N/A return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
0N/A}
0N/A
0N/A#ifndef CLOCK_MONOTONIC
0N/A#define CLOCK_MONOTONIC (1)
0N/A#endif
0N/A
0N/Avoid os::Linux::clock_init() {
0N/A // we do dlopen's in this particular order due to bug in linux
0N/A // dynamical loader (see 6348968) leading to crash on exit
0N/A void* handle = dlopen("librt.so.1", RTLD_LAZY);
0N/A if (handle == NULL) {
0N/A handle = dlopen("librt.so", RTLD_LAZY);
0N/A }
0N/A
0N/A if (handle) {
0N/A int (*clock_getres_func)(clockid_t, struct timespec*) =
0N/A (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
0N/A int (*clock_gettime_func)(clockid_t, struct timespec*) =
0N/A (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
0N/A if (clock_getres_func && clock_gettime_func) {
0N/A // See if monotonic clock is supported by the kernel. Note that some
0N/A // early implementations simply return kernel jiffies (updated every
0N/A // 1/100 or 1/1000 second). It would be bad to use such a low res clock
0N/A // for nano time (though the monotonic property is still nice to have).
0N/A // It's fixed in newer kernels, however clock_getres() still returns
0N/A // 1/HZ. We check if clock_getres() works, but will ignore its reported
0N/A // resolution for now. Hopefully as people move to new kernels, this
0N/A // won't be a problem.
0N/A struct timespec res;
0N/A struct timespec tp;
0N/A if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 &&
0N/A clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) {
0N/A // yes, monotonic clock is supported
0N/A _clock_gettime = clock_gettime_func;
0N/A } else {
0N/A // close librt if there is no monotonic clock
0N/A dlclose(handle);
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
0N/A#ifndef SYS_clock_getres
0N/A
0N/A#if defined(IA32) || defined(AMD64)
0N/A#define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229)
1601N/A#define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y)
0N/A#else
1601N/A#warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
1601N/A#define sys_clock_getres(x,y) -1
0N/A#endif
0N/A
1601N/A#else
1601N/A#define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y)
0N/A#endif
0N/A
0N/Avoid os::Linux::fast_thread_clock_init() {
0N/A if (!UseLinuxPosixThreadCPUClocks) {
0N/A return;
0N/A }
0N/A clockid_t clockid;
0N/A struct timespec tp;
0N/A int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
0N/A (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
0N/A
0N/A // Switch to using fast clocks for thread cpu time if
0N/A // the sys_clock_getres() returns 0 error code.
0N/A // Note, that some kernels may support the current thread
0N/A // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
0N/A // returned by the pthread_getcpuclockid().
0N/A // If the fast Posix clocks are supported then the sys_clock_getres()
0N/A // must return at least tp.tv_sec == 0 which means a resolution
0N/A // better than 1 sec. This is extra check for reliability.
0N/A
0N/A if(pthread_getcpuclockid_func &&
0N/A pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
0N/A sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
0N/A
0N/A _supports_fast_thread_cpu_time = true;
0N/A _pthread_getcpuclockid = pthread_getcpuclockid_func;
0N/A }
0N/A}
0N/A
0N/Ajlong os::javaTimeNanos() {
0N/A if (Linux::supports_monotonic_clock()) {
0N/A struct timespec tp;
0N/A int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
0N/A assert(status == 0, "gettime error");
0N/A jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
0N/A return result;
0N/A } else {
0N/A timeval time;
0N/A int status = gettimeofday(&time, NULL);
0N/A assert(status != -1, "linux error");
0N/A jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
0N/A return 1000 * usecs;
0N/A }
0N/A}
0N/A
0N/Avoid os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
0N/A if (Linux::supports_monotonic_clock()) {
0N/A info_ptr->max_value = ALL_64_BITS;
0N/A
0N/A // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
0N/A info_ptr->may_skip_backward = false; // not subject to resetting or drifting
0N/A info_ptr->may_skip_forward = false; // not subject to resetting or drifting
0N/A } else {
0N/A // gettimeofday - based on time in seconds since the Epoch thus does not wrap
0N/A info_ptr->max_value = ALL_64_BITS;
0N/A
0N/A // gettimeofday is a real time clock so it skips
0N/A info_ptr->may_skip_backward = true;
0N/A info_ptr->may_skip_forward = true;
0N/A }
0N/A
0N/A info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
0N/A}
0N/A
0N/A// Return the real, user, and system times in seconds from an
0N/A// arbitrary fixed point in the past.
0N/Abool os::getTimesSecs(double* process_real_time,
0N/A double* process_user_time,
0N/A double* process_system_time) {
0N/A struct tms ticks;
0N/A clock_t real_ticks = times(&ticks);
0N/A
0N/A if (real_ticks == (clock_t) (-1)) {
0N/A return false;
0N/A } else {
0N/A double ticks_per_second = (double) clock_tics_per_sec;
0N/A *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
0N/A *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
0N/A *process_real_time = ((double) real_ticks) / ticks_per_second;
0N/A
0N/A return true;
0N/A }
0N/A}
0N/A
0N/A
0N/Achar * os::local_time_string(char *buf, size_t buflen) {
0N/A struct tm t;
0N/A time_t long_time;
0N/A time(&long_time);
0N/A localtime_r(&long_time, &t);
0N/A jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
0N/A t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
0N/A t.tm_hour, t.tm_min, t.tm_sec);
0N/A return buf;
0N/A}
0N/A
548N/Astruct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
548N/A return localtime_r(clock, res);
548N/A}
548N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// runtime exit support
0N/A
0N/A// Note: os::shutdown() might be called very early during initialization, or
0N/A// called from signal handler. Before adding something to os::shutdown(), make
0N/A// sure it is async-safe and can handle partially initialized VM.
0N/Avoid os::shutdown() {
0N/A
0N/A // allow PerfMemory to attempt cleanup of any persistent resources
0N/A perfMemory_exit();
0N/A
0N/A // needs to remove object in file system
0N/A AttachListener::abort();
0N/A
0N/A // flush buffered output, finish log files
0N/A ostream_abort();
0N/A
0N/A // Check for abort hook
0N/A abort_hook_t abort_hook = Arguments::abort_hook();
0N/A if (abort_hook != NULL) {
0N/A abort_hook();
0N/A }
0N/A
0N/A}
0N/A
0N/A// Note: os::abort() might be called very early during initialization, or
0N/A// called from signal handler. Before adding something to os::abort(), make
0N/A// sure it is async-safe and can handle partially initialized VM.
0N/Avoid os::abort(bool dump_core) {
0N/A os::shutdown();
0N/A if (dump_core) {
0N/A#ifndef PRODUCT
0N/A fdStream out(defaultStream::output_fd());
0N/A out.print_raw("Current thread is ");
0N/A char buf[16];
0N/A jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
0N/A out.print_raw_cr(buf);
0N/A out.print_raw_cr("Dumping core ...");
0N/A#endif
0N/A ::abort(); // dump core
0N/A }
0N/A
0N/A ::exit(1);
0N/A}
0N/A
0N/A// Die immediately, no exit hook, no abort hook, no cleanup.
0N/Avoid os::die() {
0N/A // _exit() on LinuxThreads only kills current thread
0N/A ::abort();
0N/A}
0N/A
0N/A// unused on linux for now.
0N/Avoid os::set_error_file(const char *logfile) {}
0N/A
1887N/A
1887N/A// This method is a copy of JDK's sysGetLastErrorString
1887N/A// from src/solaris/hpi/src/system_md.c
1887N/A
1887N/Asize_t os::lasterror(char *buf, size_t len) {
1887N/A
1887N/A if (errno == 0) return 0;
1887N/A
1887N/A const char *s = ::strerror(errno);
1887N/A size_t n = ::strlen(s);
1887N/A if (n >= len) {
1887N/A n = len - 1;
1887N/A }
1887N/A ::strncpy(buf, s, n);
1887N/A buf[n] = '\0';
1887N/A return n;
1887N/A}
1887N/A
0N/Aintx os::current_thread_id() { return (intx)pthread_self(); }
0N/Aint os::current_process_id() {
0N/A
0N/A // Under the old linux thread library, linux gives each thread
0N/A // its own process id. Because of this each thread will return
0N/A // a different pid if this method were to return the result
0N/A // of getpid(2). Linux provides no api that returns the pid
0N/A // of the launcher thread for the vm. This implementation
0N/A // returns a unique pid, the pid of the launcher thread
0N/A // that starts the vm 'process'.
0N/A
0N/A // Under the NPTL, getpid() returns the same pid as the
0N/A // launcher thread rather than a unique pid per thread.
0N/A // Use gettid() if you want the old pre NPTL behaviour.
0N/A
0N/A // if you are looking for the result of a call to getpid() that
0N/A // returns a unique pid for the calling thread, then look at the
0N/A // OSThread::thread_id() method in osThread_linux.hpp file
0N/A
0N/A return (int)(_initial_pid ? _initial_pid : getpid());
0N/A}
0N/A
0N/A// DLL functions
0N/A
0N/Aconst char* os::dll_file_extension() { return ".so"; }
0N/A
2015N/A// This must be hard coded because it's the system's temporary
2015N/A// directory not the java application's temp directory, ala java.io.tmpdir.
2015N/Aconst char* os::get_temp_directory() { return "/tmp"; }
0N/A
691N/Astatic bool file_exists(const char* filename) {
691N/A struct stat statbuf;
691N/A if (filename == NULL || strlen(filename) == 0) {
691N/A return false;
691N/A }
691N/A return os::stat(filename, &statbuf) == 0;
691N/A}
691N/A
691N/Avoid os::dll_build_name(char* buffer, size_t buflen,
691N/A const char* pname, const char* fname) {
691N/A // Copied from libhpi
242N/A const size_t pnamelen = pname ? strlen(pname) : 0;
242N/A
691N/A // Quietly truncate on buffer overflow. Should be an error.
242N/A if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
242N/A *buffer = '\0';
242N/A return;
242N/A }
242N/A
242N/A if (pnamelen == 0) {
691N/A snprintf(buffer, buflen, "lib%s.so", fname);
691N/A } else if (strchr(pname, *os::path_separator()) != NULL) {
691N/A int n;
691N/A char** pelements = split_path(pname, &n);
691N/A for (int i = 0 ; i < n ; i++) {
691N/A // Really shouldn't be NULL, but check can't hurt
691N/A if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
691N/A continue; // skip the empty path values
691N/A }
691N/A snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
691N/A if (file_exists(buffer)) {
691N/A break;
691N/A }
691N/A }
691N/A // release the storage
691N/A for (int i = 0 ; i < n ; i++) {
691N/A if (pelements[i] != NULL) {
3863N/A FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
691N/A }
691N/A }
691N/A if (pelements != NULL) {
3863N/A FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
691N/A }
242N/A } else {
691N/A snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
242N/A }
242N/A}
242N/A
0N/Aconst char* os::get_current_directory(char *buf, int buflen) {
0N/A return getcwd(buf, buflen);
0N/A}
0N/A
0N/A// check if addr is inside libjvm[_g].so
0N/Abool os::address_is_in_vm(address addr) {
0N/A static address libjvm_base_addr;
0N/A Dl_info dlinfo;
0N/A
0N/A if (libjvm_base_addr == NULL) {
0N/A dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
0N/A libjvm_base_addr = (address)dlinfo.dli_fbase;
0N/A assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
0N/A }
0N/A
0N/A if (dladdr((void *)addr, &dlinfo)) {
0N/A if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
0N/A }
0N/A
0N/A return false;
0N/A}
0N/A
0N/Abool os::dll_address_to_function_name(address addr, char *buf,
0N/A int buflen, int *offset) {
0N/A Dl_info dlinfo;
0N/A
0N/A if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
1929N/A if (buf != NULL) {
1929N/A if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1929N/A jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1929N/A }
1929N/A }
1929N/A if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
0N/A return true;
1929N/A } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
1929N/A if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
3084N/A buf, buflen, offset, dlinfo.dli_fname)) {
1929N/A return true;
1929N/A }
0N/A }
1929N/A
1929N/A if (buf != NULL) buf[0] = '\0';
1929N/A if (offset != NULL) *offset = -1;
1929N/A return false;
0N/A}
0N/A
0N/Astruct _address_to_library_name {
0N/A address addr; // input : memory address
0N/A size_t buflen; // size of fname
0N/A char* fname; // output: library name
0N/A address base; // library base addr
0N/A};
0N/A
0N/Astatic int address_to_library_name_callback(struct dl_phdr_info *info,
0N/A size_t size, void *data) {
0N/A int i;
0N/A bool found = false;
0N/A address libbase = NULL;
0N/A struct _address_to_library_name * d = (struct _address_to_library_name *)data;
0N/A
0N/A // iterate through all loadable segments
0N/A for (i = 0; i < info->dlpi_phnum; i++) {
0N/A address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
0N/A if (info->dlpi_phdr[i].p_type == PT_LOAD) {
0N/A // base address of a library is the lowest address of its loaded
0N/A // segments.
0N/A if (libbase == NULL || libbase > segbase) {
0N/A libbase = segbase;
0N/A }
0N/A // see if 'addr' is within current segment
0N/A if (segbase <= d->addr &&
0N/A d->addr < segbase + info->dlpi_phdr[i].p_memsz) {
0N/A found = true;
0N/A }
0N/A }
0N/A }
0N/A
0N/A // dlpi_name is NULL or empty if the ELF file is executable, return 0
0N/A // so dll_address_to_library_name() can fall through to use dladdr() which
0N/A // can figure out executable name from argv[0].
0N/A if (found && info->dlpi_name && info->dlpi_name[0]) {
0N/A d->base = libbase;
0N/A if (d->fname) {
0N/A jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);
0N/A }
0N/A return 1;
0N/A }
0N/A return 0;
0N/A}
0N/A
0N/Abool os::dll_address_to_library_name(address addr, char* buf,
0N/A int buflen, int* offset) {
0N/A Dl_info dlinfo;
0N/A struct _address_to_library_name data;
0N/A
0N/A // There is a bug in old glibc dladdr() implementation that it could resolve
0N/A // to wrong library name if the .so file has a base address != NULL. Here
0N/A // we iterate through the program headers of all loaded libraries to find
0N/A // out which library 'addr' really belongs to. This workaround can be
0N/A // removed once the minimum requirement for glibc is moved to 2.3.x.
0N/A data.addr = addr;
0N/A data.fname = buf;
0N/A data.buflen = buflen;
0N/A data.base = NULL;
0N/A int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);
0N/A
0N/A if (rslt) {
0N/A // buf already contains library name
0N/A if (offset) *offset = addr - data.base;
0N/A return true;
0N/A } else if (dladdr((void*)addr, &dlinfo)){
0N/A if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
0N/A if (offset) *offset = addr - (address)dlinfo.dli_fbase;
0N/A return true;
0N/A } else {
0N/A if (buf) buf[0] = '\0';
0N/A if (offset) *offset = -1;
0N/A return false;
0N/A }
0N/A}
0N/A
0N/A // Loads .dll/.so and
0N/A // in case of error it checks if .dll/.so was built for the
0N/A // same architecture as Hotspot is running on
0N/A
4340N/A
4340N/A// Remember the stack's state. The Linux dynamic linker will change
4340N/A// the stack to 'executable' at most once, so we must safepoint only once.
4340N/Abool os::Linux::_stack_is_executable = false;
4340N/A
4340N/A// VM operation that loads a library. This is necessary if stack protection
4340N/A// of the Java stacks can be lost during loading the library. If we
4340N/A// do not stop the Java threads, they can stack overflow before the stacks
4340N/A// are protected again.
4340N/Aclass VM_LinuxDllLoad: public VM_Operation {
4340N/A private:
4340N/A const char *_filename;
4340N/A char *_ebuf;
4340N/A int _ebuflen;
4340N/A void *_lib;
4340N/A public:
4340N/A VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
4340N/A _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
4340N/A VMOp_Type type() const { return VMOp_LinuxDllLoad; }
4340N/A void doit() {
4340N/A _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
4340N/A os::Linux::_stack_is_executable = true;
4340N/A }
4340N/A void* loaded_library() { return _lib; }
4340N/A};
4340N/A
0N/Avoid * os::dll_load(const char *filename, char *ebuf, int ebuflen)
0N/A{
4340N/A void * result = NULL;
4340N/A bool load_attempted = false;
4340N/A
4340N/A // Check whether the library to load might change execution rights
4340N/A // of the stack. If they are changed, the protection of the stack
4340N/A // guard pages will be lost. We need a safepoint to fix this.
4340N/A //
4340N/A // See Linux man page execstack(8) for more info.
4340N/A if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
4340N/A ElfFile ef(filename);
4340N/A if (!ef.specifies_noexecstack()) {
4340N/A if (!is_init_completed()) {
4340N/A os::Linux::_stack_is_executable = true;
4340N/A // This is OK - No Java threads have been created yet, and hence no
4340N/A // stack guard pages to fix.
4340N/A //
4340N/A // This should happen only when you are building JDK7 using a very
4340N/A // old version of JDK6 (e.g., with JPRT) and running test_gamma.
4340N/A //
4340N/A // Dynamic loader will make all stacks executable after
4340N/A // this function returns, and will not do that again.
4340N/A assert(Threads::first() == NULL, "no Java threads should exist yet.");
4340N/A } else {
4340N/A warning("You have loaded library %s which might have disabled stack guard. "
4340N/A "The VM will try to fix the stack guard now.\n"
4340N/A "It's highly recommended that you fix the library with "
4340N/A "'execstack -c <libfile>', or link it with '-z noexecstack'.",
4340N/A filename);
4340N/A
4340N/A assert(Thread::current()->is_Java_thread(), "must be Java thread");
4340N/A JavaThread *jt = JavaThread::current();
4340N/A if (jt->thread_state() != _thread_in_native) {
4340N/A // This happens when a compiler thread tries to load a hsdis-<arch>.so file
4340N/A // that requires ExecStack. Cannot enter safe point. Let's give up.
4340N/A warning("Unable to fix stack guard. Giving up.");
4340N/A } else {
4340N/A if (!LoadExecStackDllInVMThread) {
4340N/A // This is for the case where the DLL has an static
4340N/A // constructor function that executes JNI code. We cannot
4340N/A // load such DLLs in the VMThread.
4340N/A result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
4340N/A }
4340N/A
4340N/A ThreadInVMfromNative tiv(jt);
4340N/A debug_only(VMNativeEntryWrapper vew;)
4340N/A
4340N/A VM_LinuxDllLoad op(filename, ebuf, ebuflen);
4340N/A VMThread::execute(&op);
4340N/A if (LoadExecStackDllInVMThread) {
4340N/A result = op.loaded_library();
4340N/A }
4340N/A load_attempted = true;
4340N/A }
4340N/A }
4340N/A }
4340N/A }
4340N/A
4340N/A if (!load_attempted) {
4340N/A result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
4340N/A }
4340N/A
0N/A if (result != NULL) {
0N/A // Successful loading
0N/A return result;
0N/A }
0N/A
0N/A Elf32_Ehdr elf_head;
0N/A int diag_msg_max_length=ebuflen-strlen(ebuf);
0N/A char* diag_msg_buf=ebuf+strlen(ebuf);
0N/A
0N/A if (diag_msg_max_length==0) {
0N/A // No more space in ebuf for additional diagnostics message
0N/A return NULL;
0N/A }
0N/A
0N/A
0N/A int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
0N/A
0N/A if (file_descriptor < 0) {
0N/A // Can't open library, report dlerror() message
0N/A return NULL;
0N/A }
0N/A
0N/A bool failed_to_read_elf_head=
0N/A (sizeof(elf_head)!=
0N/A (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
0N/A
0N/A ::close(file_descriptor);
0N/A if (failed_to_read_elf_head) {
0N/A // file i/o error - report dlerror() msg
0N/A return NULL;
0N/A }
0N/A
0N/A typedef struct {
0N/A Elf32_Half code; // Actual value as defined in elf.h
0N/A Elf32_Half compat_class; // Compatibility of archs at VM's sense
0N/A char elf_class; // 32 or 64 bit
0N/A char endianess; // MSB or LSB
0N/A char* name; // String representation
0N/A } arch_t;
0N/A
0N/A #ifndef EM_486
0N/A #define EM_486 6 /* Intel 80486 */
0N/A #endif
0N/A
0N/A static const arch_t arch_array[]={
0N/A {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
0N/A {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
0N/A {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
0N/A {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
0N/A {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
0N/A {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
0N/A {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
0N/A {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1010N/A {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1010N/A {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1010N/A {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1010N/A {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1010N/A {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1010N/A {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1010N/A {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1010N/A {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
0N/A };
0N/A
0N/A #if (defined IA32)
0N/A static Elf32_Half running_arch_code=EM_386;
0N/A #elif (defined AMD64)
0N/A static Elf32_Half running_arch_code=EM_X86_64;
0N/A #elif (defined IA64)
0N/A static Elf32_Half running_arch_code=EM_IA_64;
0N/A #elif (defined __sparc) && (defined _LP64)
0N/A static Elf32_Half running_arch_code=EM_SPARCV9;
0N/A #elif (defined __sparc) && (!defined _LP64)
0N/A static Elf32_Half running_arch_code=EM_SPARC;
0N/A #elif (defined __powerpc64__)
0N/A static Elf32_Half running_arch_code=EM_PPC64;
0N/A #elif (defined __powerpc__)
0N/A static Elf32_Half running_arch_code=EM_PPC;
1010N/A #elif (defined ARM)
1010N/A static Elf32_Half running_arch_code=EM_ARM;
1010N/A #elif (defined S390)
1010N/A static Elf32_Half running_arch_code=EM_S390;
1010N/A #elif (defined ALPHA)
1010N/A static Elf32_Half running_arch_code=EM_ALPHA;
1010N/A #elif (defined MIPSEL)
1010N/A static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1010N/A #elif (defined PARISC)
1010N/A static Elf32_Half running_arch_code=EM_PARISC;
1010N/A #elif (defined MIPS)
1010N/A static Elf32_Half running_arch_code=EM_MIPS;
1010N/A #elif (defined M68K)
1010N/A static Elf32_Half running_arch_code=EM_68K;
0N/A #else
0N/A #error Method os::dll_load requires that one of following is defined:\
1010N/A IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
0N/A #endif
0N/A
0N/A // Identify compatability class for VM's architecture and library's architecture
0N/A // Obtain string descriptions for architectures
0N/A
0N/A arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
0N/A int running_arch_index=-1;
0N/A
0N/A for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
0N/A if (running_arch_code == arch_array[i].code) {
0N/A running_arch_index = i;
0N/A }
0N/A if (lib_arch.code == arch_array[i].code) {
0N/A lib_arch.compat_class = arch_array[i].compat_class;
0N/A lib_arch.name = arch_array[i].name;
0N/A }
0N/A }
0N/A
0N/A assert(running_arch_index != -1,
0N/A "Didn't find running architecture code (running_arch_code) in arch_array");
0N/A if (running_arch_index == -1) {
0N/A // Even though running architecture detection failed
0N/A // we may still continue with reporting dlerror() message
0N/A return NULL;
0N/A }
0N/A
0N/A if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
0N/A ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
0N/A return NULL;
0N/A }
0N/A
1010N/A#ifndef S390
0N/A if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
0N/A ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
0N/A return NULL;
0N/A }
1010N/A#endif // !S390
0N/A
0N/A if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
0N/A if ( lib_arch.name!=NULL ) {
0N/A ::snprintf(diag_msg_buf, diag_msg_max_length-1,
0N/A " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
0N/A lib_arch.name, arch_array[running_arch_index].name);
0N/A } else {
0N/A ::snprintf(diag_msg_buf, diag_msg_max_length-1,
0N/A " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
0N/A lib_arch.code,
0N/A arch_array[running_arch_index].name);
0N/A }
0N/A }
0N/A
0N/A return NULL;
0N/A}
0N/A
4340N/Avoid * os::Linux::dlopen_helper(const char *filename, char *ebuf, int ebuflen) {
4340N/A void * result = ::dlopen(filename, RTLD_LAZY);
4340N/A if (result == NULL) {
4340N/A ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
4340N/A ebuf[ebuflen-1] = '\0';
4340N/A }
4340N/A return result;
4340N/A}
4340N/A
4340N/Avoid * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, int ebuflen) {
4340N/A void * result = NULL;
4340N/A if (LoadExecStackDllInVMThread) {
4340N/A result = dlopen_helper(filename, ebuf, ebuflen);
4340N/A }
4340N/A
4340N/A // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
4340N/A // library that requires an executable stack, or which does not have this
4340N/A // stack attribute set, dlopen changes the stack attribute to executable. The
4340N/A // read protection of the guard pages gets lost.
4340N/A //
4340N/A // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
4340N/A // may have been queued at the same time.
4340N/A
4340N/A if (!_stack_is_executable) {
4340N/A JavaThread *jt = Threads::first();
4340N/A
4340N/A while (jt) {
4340N/A if (!jt->stack_guard_zone_unused() && // Stack not yet fully initialized
4340N/A jt->stack_yellow_zone_enabled()) { // No pending stack overflow exceptions
4340N/A if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
4340N/A jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
4340N/A warning("Attempt to reguard stack yellow zone failed.");
4340N/A }
4340N/A }
4340N/A jt = jt->next();
4340N/A }
4340N/A }
4340N/A
4340N/A return result;
4340N/A}
4340N/A
242N/A/*
242N/A * glibc-2.0 libdl is not MT safe. If you are building with any glibc,
242N/A * chances are you might want to run the generated bits against glibc-2.0
242N/A * libdl.so, so always use locking for any version of glibc.
242N/A */
242N/Avoid* os::dll_lookup(void* handle, const char* name) {
242N/A pthread_mutex_lock(&dl_mutex);
242N/A void* res = dlsym(handle, name);
242N/A pthread_mutex_unlock(&dl_mutex);
242N/A return res;
242N/A}
0N/A
0N/A
1887N/Astatic bool _print_ascii_file(const char* filename, outputStream* st) {
1887N/A int fd = ::open(filename, O_RDONLY);
0N/A if (fd == -1) {
0N/A return false;
0N/A }
0N/A
0N/A char buf[32];
0N/A int bytes;
1887N/A while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
0N/A st->print_raw(buf, bytes);
0N/A }
0N/A
1887N/A ::close(fd);
0N/A
0N/A return true;
0N/A}
0N/A
0N/Avoid os::print_dll_info(outputStream *st) {
0N/A st->print_cr("Dynamic libraries:");
0N/A
0N/A char fname[32];
0N/A pid_t pid = os::Linux::gettid();
0N/A
0N/A jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
0N/A
0N/A if (!_print_ascii_file(fname, st)) {
0N/A st->print("Can not get library information for pid = %d\n", pid);
0N/A }
0N/A}
0N/A
3748N/Avoid os::print_os_info_brief(outputStream* st) {
3748N/A os::Linux::print_distro_info(st);
3748N/A
3748N/A os::Posix::print_uname_info(st);
3748N/A
3748N/A os::Linux::print_libversion_info(st);
3748N/A
3748N/A}
0N/A
0N/Avoid os::print_os_info(outputStream* st) {
0N/A st->print("OS:");
0N/A
3748N/A os::Linux::print_distro_info(st);
3748N/A
3748N/A os::Posix::print_uname_info(st);
3748N/A
3748N/A // Print warning if unsafe chroot environment detected
3748N/A if (unsafe_chroot_detected) {
3748N/A st->print("WARNING!! ");
3748N/A st->print_cr(unstable_chroot_error);
3748N/A }
3748N/A
3748N/A os::Linux::print_libversion_info(st);
3748N/A
3748N/A os::Posix::print_rlimit_info(st);
3748N/A
3748N/A os::Posix::print_load_average(st);
3748N/A
3748N/A os::Linux::print_full_memory_info(st);
3748N/A}
3748N/A
3748N/A// Try to identify popular distros.
3748N/A// Most Linux distributions have /etc/XXX-release file, which contains
3748N/A// the OS version string. Some have more than one /etc/XXX-release file
3748N/A// (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.),
3748N/A// so the order is important.
3748N/Avoid os::Linux::print_distro_info(outputStream* st) {
0N/A if (!_print_ascii_file("/etc/mandrake-release", st) &&
0N/A !_print_ascii_file("/etc/sun-release", st) &&
0N/A !_print_ascii_file("/etc/redhat-release", st) &&
0N/A !_print_ascii_file("/etc/SuSE-release", st) &&
0N/A !_print_ascii_file("/etc/turbolinux-release", st) &&
0N/A !_print_ascii_file("/etc/gentoo-release", st) &&
1601N/A !_print_ascii_file("/etc/debian_version", st) &&
1601N/A !_print_ascii_file("/etc/ltib-release", st) &&
1601N/A !_print_ascii_file("/etc/angstrom-version", st)) {
0N/A st->print("Linux");
0N/A }
0N/A st->cr();
3748N/A}
3748N/A
3748N/Avoid os::Linux::print_libversion_info(outputStream* st) {
0N/A // libc, pthread
0N/A st->print("libc:");
0N/A st->print(os::Linux::glibc_version()); st->print(" ");
0N/A st->print(os::Linux::libpthread_version()); st->print(" ");
0N/A if (os::Linux::is_LinuxThreads()) {
0N/A st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed");
0N/A }
0N/A st->cr();
3748N/A}
3748N/A
3748N/Avoid os::Linux::print_full_memory_info(outputStream* st) {
3748N/A st->print("\n/proc/meminfo:\n");
3748N/A _print_ascii_file("/proc/meminfo", st);
3748N/A st->cr();
2625N/A}
2625N/A
0N/Avoid os::print_memory_info(outputStream* st) {
0N/A
0N/A st->print("Memory:");
0N/A st->print(" %dk page", os::vm_page_size()>>10);
0N/A
0N/A // values in struct sysinfo are "unsigned long"
0N/A struct sysinfo si;
0N/A sysinfo(&si);
0N/A
0N/A st->print(", physical " UINT64_FORMAT "k",
0N/A os::physical_memory() >> 10);
0N/A st->print("(" UINT64_FORMAT "k free)",
0N/A os::available_memory() >> 10);
0N/A st->print(", swap " UINT64_FORMAT "k",
0N/A ((jlong)si.totalswap * si.mem_unit) >> 10);
0N/A st->print("(" UINT64_FORMAT "k free)",
0N/A ((jlong)si.freeswap * si.mem_unit) >> 10);
0N/A st->cr();
0N/A}
0N/A
3748N/Avoid os::pd_print_cpu_info(outputStream* st) {
3748N/A st->print("\n/proc/cpuinfo:\n");
3748N/A if (!_print_ascii_file("/proc/cpuinfo", st)) {
3748N/A st->print(" <Not Available>");
3748N/A }
3748N/A st->cr();
3748N/A}
3748N/A
0N/A// Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific
0N/A// but they're the same for all the linux arch that we support
0N/A// and they're the same for solaris but there's no common place to put this.
0N/Aconst char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
0N/A "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
0N/A "ILL_COPROC", "ILL_BADSTK" };
0N/A
0N/Aconst char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
0N/A "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
0N/A "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
0N/A
0N/Aconst char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
0N/A
0N/Aconst char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
0N/A
0N/Avoid os::print_siginfo(outputStream* st, void* siginfo) {
0N/A st->print("siginfo:");
0N/A
0N/A const int buflen = 100;
0N/A char buf[buflen];
0N/A siginfo_t *si = (siginfo_t*)siginfo;
0N/A st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
0N/A if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
0N/A st->print("si_errno=%s", buf);
0N/A } else {
0N/A st->print("si_errno=%d", si->si_errno);
0N/A }
0N/A const int c = si->si_code;
0N/A assert(c > 0, "unexpected si_code");
0N/A switch (si->si_signo) {
0N/A case SIGILL:
0N/A st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
0N/A st->print(", si_addr=" PTR_FORMAT, si->si_addr);
0N/A break;
0N/A case SIGFPE:
0N/A st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
0N/A st->print(", si_addr=" PTR_FORMAT, si->si_addr);
0N/A break;
0N/A case SIGSEGV:
0N/A st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
0N/A st->print(", si_addr=" PTR_FORMAT, si->si_addr);
0N/A break;
0N/A case SIGBUS:
0N/A st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
0N/A st->print(", si_addr=" PTR_FORMAT, si->si_addr);
0N/A break;
0N/A default:
0N/A st->print(", si_code=%d", si->si_code);
0N/A // no si_addr
0N/A }
0N/A
0N/A if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
0N/A UseSharedSpaces) {
0N/A FileMapInfo* mapinfo = FileMapInfo::current_info();
0N/A if (mapinfo->is_in_shared_space(si->si_addr)) {
0N/A st->print("\n\nError accessing class data sharing archive." \
0N/A " Mapped file inaccessible during execution, " \
0N/A " possible disk/network problem.");
0N/A }
0N/A }
0N/A st->cr();
0N/A}
0N/A
0N/A
0N/Astatic void print_signal_handler(outputStream* st, int sig,
0N/A char* buf, size_t buflen);
0N/A
0N/Avoid os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
0N/A st->print_cr("Signal Handlers:");
0N/A print_signal_handler(st, SIGSEGV, buf, buflen);
0N/A print_signal_handler(st, SIGBUS , buf, buflen);
0N/A print_signal_handler(st, SIGFPE , buf, buflen);
0N/A print_signal_handler(st, SIGPIPE, buf, buflen);
0N/A print_signal_handler(st, SIGXFSZ, buf, buflen);
0N/A print_signal_handler(st, SIGILL , buf, buflen);
0N/A print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
0N/A print_signal_handler(st, SR_signum, buf, buflen);
0N/A print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
0N/A print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
0N/A print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
0N/A print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
0N/A}
0N/A
0N/Astatic char saved_jvm_path[MAXPATHLEN] = {0};
0N/A
0N/A// Find the full path to the current module, libjvm.so or libjvm_g.so
1562N/Avoid os::jvm_path(char *buf, jint buflen) {
0N/A // Error checking.
1562N/A if (buflen < MAXPATHLEN) {
0N/A assert(false, "must use a large-enough buffer");
0N/A buf[0] = '\0';
0N/A return;
0N/A }
0N/A // Lazy resolve the path to current module.
0N/A if (saved_jvm_path[0] != 0) {
0N/A strcpy(buf, saved_jvm_path);
0N/A return;
0N/A }
0N/A
0N/A char dli_fname[MAXPATHLEN];
0N/A bool ret = dll_address_to_library_name(
0N/A CAST_FROM_FN_PTR(address, os::jvm_path),
0N/A dli_fname, sizeof(dli_fname), NULL);
0N/A assert(ret != 0, "cannot locate libjvm");
1601N/A char *rp = realpath(dli_fname, buf);
1601N/A if (rp == NULL)
513N/A return;
0N/A
2149N/A if (Arguments::created_by_gamma_launcher()) {
0N/A // Support for the gamma launcher. Typical value for buf is
0N/A // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". If "/jre/lib/" appears at
0N/A // the right place in the string, then assume we are installed in a JDK and
0N/A // we're done. Otherwise, check for a JAVA_HOME environment variable and fix
0N/A // up the path so it looks like libjvm.so is installed there (append a
0N/A // fake suffix hotspot/libjvm.so).
0N/A const char *p = buf + strlen(buf) - 1;
0N/A for (int count = 0; p > buf && count < 5; ++count) {
0N/A for (--p; p > buf && *p != '/'; --p)
0N/A /* empty */ ;
0N/A }
0N/A
0N/A if (strncmp(p, "/jre/lib/", 9) != 0) {
0N/A // Look for JAVA_HOME in the environment.
0N/A char* java_home_var = ::getenv("JAVA_HOME");
0N/A if (java_home_var != NULL && java_home_var[0] != 0) {
1562N/A char* jrelib_p;
1562N/A int len;
1562N/A
0N/A // Check the current module name "libjvm.so" or "libjvm_g.so".
0N/A p = strrchr(buf, '/');
0N/A assert(strstr(p, "/libjvm") == p, "invalid library name");
0N/A p = strstr(p, "_g") ? "_g" : "";
0N/A
1601N/A rp = realpath(java_home_var, buf);
1601N/A if (rp == NULL)
513N/A return;
1562N/A
1562N/A // determine if this is a legacy image or modules image
1562N/A // modules image doesn't have "jre" subdirectory
1562N/A len = strlen(buf);
1562N/A jrelib_p = buf + len;
1562N/A snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
1562N/A if (0 != access(buf, F_OK)) {
1562N/A snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
1562N/A }
1562N/A
0N/A if (0 == access(buf, F_OK)) {
0N/A // Use current module name "libjvm[_g].so" instead of
0N/A // "libjvm"debug_only("_g")".so" since for fastdebug version
0N/A // we should have "libjvm.so" but debug_only("_g") adds "_g"!
1562N/A len = strlen(buf);
1562N/A snprintf(buf + len, buflen-len, "/hotspot/libjvm%s.so", p);
0N/A } else {
0N/A // Go back to path of .so
1601N/A rp = realpath(dli_fname, buf);
1601N/A if (rp == NULL)
513N/A return;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A strcpy(saved_jvm_path, buf);
0N/A}
0N/A
0N/Avoid os::print_jni_name_prefix_on(outputStream* st, int args_size) {
0N/A // no prefix required, not even "_"
0N/A}
0N/A
0N/Avoid os::print_jni_name_suffix_on(outputStream* st, int args_size) {
0N/A // no suffix required
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// sun.misc.Signal support
0N/A
0N/Astatic volatile jint sigint_count = 0;
0N/A
0N/Astatic void
0N/AUserHandler(int sig, void *siginfo, void *context) {
0N/A // 4511530 - sem_post is serialized and handled by the manager thread. When
0N/A // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
0N/A // don't want to flood the manager thread with sem_post requests.
0N/A if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
0N/A return;
0N/A
0N/A // Ctrl-C is pressed during error reporting, likely because the error
0N/A // handler fails to abort. Let VM die immediately.
0N/A if (sig == SIGINT && is_error_reported()) {
0N/A os::die();
0N/A }
0N/A
0N/A os::signal_notify(sig);
0N/A}
0N/A
0N/Avoid* os::user_handler() {
0N/A return CAST_FROM_FN_PTR(void*, UserHandler);
0N/A}
0N/A
4433N/Aclass Semaphore : public StackObj {
4433N/A public:
4433N/A Semaphore();
4433N/A ~Semaphore();
4433N/A void signal();
4433N/A void wait();
4433N/A bool trywait();
4433N/A bool timedwait(unsigned int sec, int nsec);
4433N/A private:
4433N/A sem_t _semaphore;
4433N/A};
4433N/A
4433N/A
4433N/ASemaphore::Semaphore() {
4433N/A sem_init(&_semaphore, 0, 0);
4433N/A}
4433N/A
4433N/ASemaphore::~Semaphore() {
4433N/A sem_destroy(&_semaphore);
4433N/A}
4433N/A
4433N/Avoid Semaphore::signal() {
4433N/A sem_post(&_semaphore);
4433N/A}
4433N/A
4433N/Avoid Semaphore::wait() {
4433N/A sem_wait(&_semaphore);
4433N/A}
4433N/A
4433N/Abool Semaphore::trywait() {
4433N/A return sem_trywait(&_semaphore) == 0;
4433N/A}
4433N/A
4433N/Abool Semaphore::timedwait(unsigned int sec, int nsec) {
4433N/A struct timespec ts;
4433N/A unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
4433N/A
4433N/A while (1) {
4433N/A int result = sem_timedwait(&_semaphore, &ts);
4433N/A if (result == 0) {
4433N/A return true;
4433N/A } else if (errno == EINTR) {
4433N/A continue;
4433N/A } else if (errno == ETIMEDOUT) {
4433N/A return false;
4433N/A } else {
4433N/A return false;
4433N/A }
4433N/A }
4433N/A}
4433N/A
0N/Aextern "C" {
0N/A typedef void (*sa_handler_t)(int);
0N/A typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
0N/A}
0N/A
0N/Avoid* os::signal(int signal_number, void* handler) {
0N/A struct sigaction sigAct, oldSigAct;
0N/A
0N/A sigfillset(&(sigAct.sa_mask));
0N/A sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
0N/A sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
0N/A
0N/A if (sigaction(signal_number, &sigAct, &oldSigAct)) {
0N/A // -1 means registration failed
0N/A return (void *)-1;
0N/A }
0N/A
0N/A return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
0N/A}
0N/A
0N/Avoid os::signal_raise(int signal_number) {
0N/A ::raise(signal_number);
0N/A}
0N/A
0N/A/*
0N/A * The following code is moved from os.cpp for making this
0N/A * code platform specific, which it is by its very nature.
0N/A */
0N/A
0N/A// Will be modified when max signal is changed to be dynamic
0N/Aint os::sigexitnum_pd() {
0N/A return NSIG;
0N/A}
0N/A
0N/A// a counter for each possible signal value
0N/Astatic volatile jint pending_signals[NSIG+1] = { 0 };
0N/A
0N/A// Linux(POSIX) specific hand shaking semaphore.
0N/Astatic sem_t sig_sem;
4433N/Astatic Semaphore sr_semaphore;
0N/A
0N/Avoid os::signal_init_pd() {
0N/A // Initialize signal structures
0N/A ::memset((void*)pending_signals, 0, sizeof(pending_signals));
0N/A
0N/A // Initialize signal semaphore
0N/A ::sem_init(&sig_sem, 0, 0);
0N/A}
0N/A
0N/Avoid os::signal_notify(int sig) {
0N/A Atomic::inc(&pending_signals[sig]);
0N/A ::sem_post(&sig_sem);
0N/A}
0N/A
0N/Astatic int check_pending_signals(bool wait) {
0N/A Atomic::store(0, &sigint_count);
0N/A for (;;) {
0N/A for (int i = 0; i < NSIG + 1; i++) {
0N/A jint n = pending_signals[i];
0N/A if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
0N/A return i;
0N/A }
0N/A }
0N/A if (!wait) {
0N/A return -1;
0N/A }
0N/A JavaThread *thread = JavaThread::current();
0N/A ThreadBlockInVM tbivm(thread);
0N/A
0N/A bool threadIsSuspended;
0N/A do {
0N/A thread->set_suspend_equivalent();
0N/A // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
0N/A ::sem_wait(&sig_sem);
0N/A
0N/A // were we externally suspended while we were waiting?
0N/A threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
0N/A if (threadIsSuspended) {
0N/A //
0N/A // The semaphore has been incremented, but while we were waiting
0N/A // another thread suspended us. We don't want to continue running
0N/A // while suspended because that would surprise the thread that
0N/A // suspended us.
0N/A //
0N/A ::sem_post(&sig_sem);
0N/A
0N/A thread->java_suspend_self();
0N/A }
0N/A } while (threadIsSuspended);
0N/A }
0N/A}
0N/A
0N/Aint os::signal_lookup() {
0N/A return check_pending_signals(false);
0N/A}
0N/A
0N/Aint os::signal_wait() {
0N/A return check_pending_signals(true);
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// Virtual Memory
0N/A
0N/Aint os::vm_page_size() {
0N/A // Seems redundant as all get out
0N/A assert(os::Linux::page_size() != -1, "must call os::init");
0N/A return os::Linux::page_size();
0N/A}
0N/A
0N/A// Solaris allocates memory by pages.
0N/Aint os::vm_allocation_granularity() {
0N/A assert(os::Linux::page_size() != -1, "must call os::init");
0N/A return os::Linux::page_size();
0N/A}
0N/A
0N/A// Rationale behind this function:
0N/A// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
0N/A// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
0N/A// samples for JITted code. Here we create private executable mapping over the code cache
0N/A// and then we can use standard (well, almost, as mapping can change) way to provide
0N/A// info for the reporting script by storing timestamp and location of symbol
0N/Avoid linux_wrap_code(char* base, size_t size) {
0N/A static volatile jint cnt = 0;
0N/A
0N/A if (!UseOprofile) {
0N/A return;
0N/A }
0N/A
1417N/A char buf[PATH_MAX+1];
0N/A int num = Atomic::add(1, &cnt);
0N/A
1353N/A snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
1353N/A os::get_temp_directory(), os::current_process_id(), num);
0N/A unlink(buf);
0N/A
1887N/A int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
0N/A
0N/A if (fd != -1) {
1887N/A off_t rv = ::lseek(fd, size-2, SEEK_SET);
0N/A if (rv != (off_t)-1) {
1887N/A if (::write(fd, "", 1) == 1) {
0N/A mmap(base, size,
0N/A PROT_READ|PROT_WRITE|PROT_EXEC,
0N/A MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
0N/A }
0N/A }
1887N/A ::close(fd);
0N/A unlink(buf);
0N/A }
0N/A}
0N/A
4552N/Astatic bool recoverable_mmap_error(int err) {
4552N/A // See if the error is one we can let the caller handle. This
4552N/A // list of errno values comes from JBS-6843484. I can't find a
4552N/A // Linux man page that documents this specific set of errno
4552N/A // values so while this list currently matches Solaris, it may
4552N/A // change as we gain experience with this failure mode.
4552N/A switch (err) {
4552N/A case EBADF:
4552N/A case EINVAL:
4552N/A case ENOTSUP:
4552N/A // let the caller deal with these errors
4552N/A return true;
4552N/A
4552N/A default:
4552N/A // Any remaining errors on this OS can cause our reserved mapping
4552N/A // to be lost. That can cause confusion where different data
4552N/A // structures think they have the same memory mapped. The worst
4552N/A // scenario is if both the VM and a library think they have the
4552N/A // same memory mapped.
4552N/A return false;
4552N/A }
4552N/A}
4552N/A
4552N/Astatic void warn_fail_commit_memory(char* addr, size_t size, bool exec,
4552N/A int err) {
4552N/A warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
4552N/A ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
4552N/A strerror(err), err);
4552N/A}
4552N/A
4552N/Astatic void warn_fail_commit_memory(char* addr, size_t size,
4552N/A size_t alignment_hint, bool exec,
4552N/A int err) {
4552N/A warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
4552N/A ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, size,
4552N/A alignment_hint, exec, strerror(err), err);
4552N/A}
4552N/A
0N/A// NOTE: Linux kernel does not really reserve the pages for us.
0N/A// All it does is to check if there are enough free pages
0N/A// left at the time of mmap(). This could be a potential
0N/A// problem.
4552N/Aint os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
656N/A int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
656N/A uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
0N/A MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2719N/A if (res != (uintptr_t) MAP_FAILED) {
2719N/A if (UseNUMAInterleaving) {
2719N/A numa_make_global(addr, size);
2719N/A }
4552N/A return 0;
4552N/A }
4552N/A
4552N/A int err = errno; // save errno from mmap() call above
4552N/A
4552N/A if (!recoverable_mmap_error(err)) {
4552N/A warn_fail_commit_memory(addr, size, exec, err);
4552N/A vm_exit_out_of_memory(size, "committing reserved memory.");
4552N/A }
4552N/A
4552N/A return err;
4552N/A}
4552N/A
4552N/Abool os::pd_commit_memory(char* addr, size_t size, bool exec) {
4552N/A return os::Linux::commit_memory_impl(addr, size, exec) == 0;
4552N/A}
4552N/A
4552N/Avoid os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
4552N/A const char* mesg) {
4552N/A assert(mesg != NULL, "mesg must be specified");
4552N/A int err = os::Linux::commit_memory_impl(addr, size, exec);
4552N/A if (err != 0) {
4552N/A // the caller wants all commit errors to exit with the specified mesg:
4552N/A warn_fail_commit_memory(addr, size, exec, err);
4552N/A vm_exit_out_of_memory(size, mesg);
4552N/A }
0N/A}
0N/A
2383N/A// Define MAP_HUGETLB here so we can build HotSpot on old systems.
2383N/A#ifndef MAP_HUGETLB
2383N/A#define MAP_HUGETLB 0x40000
2383N/A#endif
2383N/A
2383N/A// Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2383N/A#ifndef MADV_HUGEPAGE
2383N/A#define MADV_HUGEPAGE 14
2383N/A#endif
2383N/A
4552N/Aint os::Linux::commit_memory_impl(char* addr, size_t size,
4552N/A size_t alignment_hint, bool exec) {
4552N/A int err;
2383N/A if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
2383N/A int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2383N/A uintptr_t res =
2383N/A (uintptr_t) ::mmap(addr, size, prot,
2383N/A MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS|MAP_HUGETLB,
2383N/A -1, 0);
2719N/A if (res != (uintptr_t) MAP_FAILED) {
2719N/A if (UseNUMAInterleaving) {
2719N/A numa_make_global(addr, size);
2719N/A }
4552N/A return 0;
4552N/A }
4552N/A
4552N/A err = errno; // save errno from mmap() call above
4552N/A
4552N/A if (!recoverable_mmap_error(err)) {
4552N/A // However, it is not clear that this loss of our reserved mapping
4552N/A // happens with large pages on Linux or that we cannot recover
4552N/A // from the loss. For now, we just issue a warning and we don't
4552N/A // call vm_exit_out_of_memory(). This issue is being tracked by
4552N/A // JBS-8007074.
4552N/A warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
4552N/A// vm_exit_out_of_memory(size, "committing reserved memory.");
2719N/A }
2747N/A // Fall through and try to use small pages
2747N/A }
2747N/A
4552N/A err = os::Linux::commit_memory_impl(addr, size, exec);
4552N/A if (err == 0) {
2747N/A realign_memory(addr, size, alignment_hint);
4552N/A }
4552N/A return err;
4552N/A}
4552N/A
4552N/Abool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
4552N/A bool exec) {
4552N/A return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
4552N/A}
4552N/A
4552N/Avoid os::pd_commit_memory_or_exit(char* addr, size_t size,
4552N/A size_t alignment_hint, bool exec,
4552N/A const char* mesg) {
4552N/A assert(mesg != NULL, "mesg must be specified");
4552N/A int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
4552N/A if (err != 0) {
4552N/A // the caller wants all commit errors to exit with the specified mesg:
4552N/A warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
4552N/A vm_exit_out_of_memory(size, mesg);
4552N/A }
0N/A}
0N/A
3863N/Avoid os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2383N/A if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
2383N/A // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2383N/A // be supported or the memory may already be backed by huge pages.
2383N/A ::madvise(addr, bytes, MADV_HUGEPAGE);
2383N/A }
2383N/A}
141N/A
3863N/Avoid os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
3608N/A // This method works by doing an mmap over an existing mmaping and effectively discarding
3608N/A // the existing pages. However it won't work for SHM-based large pages that cannot be
3608N/A // uncommitted at all. We don't do anything in this case to avoid creating a segment with
3608N/A // small pages on top of the SHM segment. This method always works for small pages, so we
3608N/A // allow that in any case.
3608N/A if (alignment_hint <= (size_t)os::vm_page_size() || !UseSHM) {
4552N/A commit_memory(addr, bytes, alignment_hint, !ExecMem);
3608N/A }
141N/A}
141N/A
462N/Avoid os::numa_make_global(char *addr, size_t bytes) {
462N/A Linux::numa_interleave_memory(addr, bytes);
462N/A}
141N/A
141N/Avoid os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
141N/A Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
141N/A}
141N/A
141N/Abool os::numa_topology_changed() { return false; }
141N/A
141N/Asize_t os::numa_get_groups_num() {
141N/A int max_node = Linux::numa_max_node();
141N/A return max_node > 0 ? max_node + 1 : 1;
141N/A}
141N/A
141N/Aint os::numa_get_group_id() {
141N/A int cpu_id = Linux::sched_getcpu();
141N/A if (cpu_id != -1) {
141N/A int lgrp_id = Linux::get_node_by_cpu(cpu_id);
141N/A if (lgrp_id != -1) {
141N/A return lgrp_id;
141N/A }
0N/A }
0N/A return 0;
0N/A}
0N/A
141N/Asize_t os::numa_get_leaf_groups(int *ids, size_t size) {
141N/A for (size_t i = 0; i < size; i++) {
141N/A ids[i] = i;
141N/A }
141N/A return size;
141N/A}
141N/A
0N/Abool os::get_page_info(char *start, page_info* info) {
0N/A return false;
0N/A}
0N/A
0N/Achar *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
0N/A return end;
0N/A}
0N/A
2651N/A
2651N/Aint os::Linux::sched_getcpu_syscall(void) {
2651N/A unsigned int cpu;
2651N/A int retval = -1;
2651N/A
2651N/A#if defined(IA32)
2721N/A# ifndef SYS_getcpu
2721N/A# define SYS_getcpu 318
2721N/A# endif
2651N/A retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2651N/A#elif defined(AMD64)
2721N/A// Unfortunately we have to bring all these macros here from vsyscall.h
2721N/A// to be able to compile on old linuxes.
2721N/A# define __NR_vgetcpu 2
2721N/A# define VSYSCALL_START (-10UL << 20)
2721N/A# define VSYSCALL_SIZE 1024
2721N/A# define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2651N/A typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2651N/A vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2651N/A retval = vgetcpu(&cpu, NULL, NULL);
2651N/A#endif
2651N/A
2651N/A return (retval == -1) ? retval : cpu;
2651N/A}
2651N/A
2072N/A// Something to do with the numa-aware allocator needs these symbols
2072N/Aextern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2072N/Aextern "C" JNIEXPORT void numa_error(char *where) { }
2072N/Aextern "C" JNIEXPORT int fork1() { return fork(); }
141N/A
763N/A
763N/A// If we are running with libnuma version > 2, then we should
763N/A// be trying to use symbols with versions 1.1
763N/A// If we are running with earlier version, which did not have symbol versions,
763N/A// we should use the base version.
763N/Avoid* os::Linux::libnuma_dlsym(void* handle, const char *name) {
763N/A void *f = dlvsym(handle, name, "libnuma_1.1");
763N/A if (f == NULL) {
763N/A f = dlsym(handle, name);
763N/A }
763N/A return f;
763N/A}
763N/A
462N/Abool os::Linux::libnuma_init() {
141N/A // sched_getcpu() should be in libc.
141N/A set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
141N/A dlsym(RTLD_DEFAULT, "sched_getcpu")));
141N/A
2651N/A // If it's not, try a direct syscall.
2651N/A if (sched_getcpu() == -1)
2651N/A set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, (void*)&sched_getcpu_syscall));
2651N/A
141N/A if (sched_getcpu() != -1) { // Does it work?
267N/A void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
141N/A if (handle != NULL) {
141N/A set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
763N/A libnuma_dlsym(handle, "numa_node_to_cpus")));
141N/A set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
763N/A libnuma_dlsym(handle, "numa_max_node")));
141N/A set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
763N/A libnuma_dlsym(handle, "numa_available")));
141N/A set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
763N/A libnuma_dlsym(handle, "numa_tonode_memory")));
462N/A set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
763N/A libnuma_dlsym(handle, "numa_interleave_memory")));
462N/A
462N/A
141N/A if (numa_available() != -1) {
763N/A set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
141N/A // Create a cpu -> node mapping
3863N/A _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
141N/A rebuild_cpu_to_node_map();
462N/A return true;
141N/A }
141N/A }
141N/A }
462N/A return false;
141N/A}
141N/A
141N/A// rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
141N/A// The table is later used in get_node_by_cpu().
141N/Avoid os::Linux::rebuild_cpu_to_node_map() {
462N/A const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
462N/A // in libnuma (possible values are starting from 16,
462N/A // and continuing up with every other power of 2, but less
462N/A // than the maximum number of CPUs supported by kernel), and
462N/A // is a subject to change (in libnuma version 2 the requirements
462N/A // are more reasonable) we'll just hardcode the number they use
462N/A // in the library.
462N/A const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
462N/A
462N/A size_t cpu_num = os::active_processor_count();
462N/A size_t cpu_map_size = NCPUS / BitsPerCLong;
462N/A size_t cpu_map_valid_size =
462N/A MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
462N/A
141N/A cpu_to_node()->clear();
141N/A cpu_to_node()->at_grow(cpu_num - 1);
462N/A size_t node_num = numa_get_groups_num();
462N/A
3863N/A unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
462N/A for (size_t i = 0; i < node_num; i++) {
141N/A if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
462N/A for (size_t j = 0; j < cpu_map_valid_size; j++) {
141N/A if (cpu_map[j] != 0) {
462N/A for (size_t k = 0; k < BitsPerCLong; k++) {
141N/A if (cpu_map[j] & (1UL << k)) {
462N/A cpu_to_node()->at_put(j * BitsPerCLong + k, i);
141N/A }
141N/A }
141N/A }
141N/A }
141N/A }
141N/A }
3863N/A FREE_C_HEAP_ARRAY(unsigned long, cpu_map, mtInternal);
141N/A}
141N/A
141N/Aint os::Linux::get_node_by_cpu(int cpu_id) {
141N/A if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
141N/A return cpu_to_node()->at(cpu_id);
141N/A }
141N/A return -1;
141N/A}
141N/A
141N/AGrowableArray<int>* os::Linux::_cpu_to_node;
141N/Aos::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
141N/Aos::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
141N/Aos::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
141N/Aos::Linux::numa_available_func_t os::Linux::_numa_available;
141N/Aos::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
462N/Aos::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
462N/Aunsigned long* os::Linux::_numa_all_nodes;
141N/A
3863N/Abool os::pd_uncommit_memory(char* addr, size_t size) {
1601N/A uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
1601N/A MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
1601N/A return res != (uintptr_t) MAP_FAILED;
0N/A}
0N/A
1320N/A// Linux uses a growable mapping for the stack, and if the mapping for
1320N/A// the stack guard pages is not removed when we detach a thread the
1320N/A// stack cannot grow beyond the pages where the stack guard was
1320N/A// mapped. If at some point later in the process the stack expands to
1320N/A// that point, the Linux kernel cannot expand the stack any further
1320N/A// because the guard pages are in the way, and a segfault occurs.
1320N/A//
1320N/A// However, it's essential not to split the stack region by unmapping
1320N/A// a region (leaving a hole) that's already part of the stack mapping,
1320N/A// so if the stack mapping has already grown beyond the guard pages at
1320N/A// the time we create them, we have to truncate the stack mapping.
1320N/A// So, we need to know the extent of the stack mapping when
1320N/A// create_stack_guard_pages() is called.
1320N/A
1320N/A// Find the bounds of the stack mapping. Return true for success.
1320N/A//
1320N/A// We only need this for stacks that are growable: at the time of
1320N/A// writing thread stacks don't use growable mappings (i.e. those
1320N/A// creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
1320N/A// only applies to the main thread.
2316N/A
2316N/Astatic
2316N/Abool get_stack_bounds(uintptr_t *bottom, uintptr_t *top) {
2316N/A
2316N/A char buf[128];
2316N/A int fd, sz;
2316N/A
2316N/A if ((fd = ::open("/proc/self/maps", O_RDONLY)) < 0) {
1320N/A return false;
2316N/A }
2316N/A
2316N/A const char kw[] = "[stack]";
2316N/A const int kwlen = sizeof(kw)-1;
2316N/A
2316N/A // Address part of /proc/self/maps couldn't be more than 128 bytes
2316N/A while ((sz = os::get_line_chars(fd, buf, sizeof(buf))) > 0) {
2316N/A if (sz > kwlen && ::memcmp(buf+sz-kwlen, kw, kwlen) == 0) {
2316N/A // Extract addresses
2316N/A if (sscanf(buf, "%" SCNxPTR "-%" SCNxPTR, bottom, top) == 2) {
2316N/A uintptr_t sp = (uintptr_t) __builtin_frame_address(0);
2316N/A if (sp >= *bottom && sp <= *top) {
2316N/A ::close(fd);
2316N/A return true;
2316N/A }
1320N/A }
2316N/A }
1320N/A }
2316N/A
2316N/A ::close(fd);
1320N/A return false;
1320N/A}
1320N/A
2316N/A
1320N/A// If the (growable) stack mapping already extends beyond the point
1320N/A// where we're going to put our guard pages, truncate the mapping at
1320N/A// that point by munmap()ping it. This ensures that when we later
1320N/A// munmap() the guard pages we don't leave a hole in the stack
1670N/A// mapping. This only affects the main/initial thread, but guard
1670N/A// against future OS changes
3863N/Abool os::pd_create_stack_guard_pages(char* addr, size_t size) {
1320N/A uintptr_t stack_extent, stack_base;
1670N/A bool chk_bounds = NOT_DEBUG(os::Linux::is_initial_thread()) DEBUG_ONLY(true);
1670N/A if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
1670N/A assert(os::Linux::is_initial_thread(),
1670N/A "growable stack in non-initial thread");
1320N/A if (stack_extent < (uintptr_t)addr)
1320N/A ::munmap((void*)stack_extent, (uintptr_t)addr - stack_extent);
1320N/A }
1320N/A
4552N/A return os::commit_memory(addr, size, !ExecMem);
1320N/A}
1320N/A
1320N/A// If this is a growable mapping, remove the guard pages entirely by
1670N/A// munmap()ping them. If not, just call uncommit_memory(). This only
1670N/A// affects the main/initial thread, but guard against future OS changes
1320N/Abool os::remove_stack_guard_pages(char* addr, size_t size) {
1320N/A uintptr_t stack_extent, stack_base;
1670N/A bool chk_bounds = NOT_DEBUG(os::Linux::is_initial_thread()) DEBUG_ONLY(true);
1670N/A if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
1670N/A assert(os::Linux::is_initial_thread(),
1670N/A "growable stack in non-initial thread");
1670N/A
1320N/A return ::munmap(addr, size) == 0;
1320N/A }
1320N/A
1320N/A return os::uncommit_memory(addr, size);
1320N/A}
1320N/A
0N/Astatic address _highest_vm_reserved_address = NULL;
0N/A
0N/A// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
0N/A// at 'requested_addr'. If there are existing memory mappings at the same
0N/A// location, however, they will be overwritten. If 'fixed' is false,
0N/A// 'requested_addr' is only treated as a hint, the return value may or
0N/A// may not start from the requested address. Unlike Linux mmap(), this
0N/A// function returns NULL to indicate failure.
0N/Astatic char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
0N/A char * addr;
0N/A int flags;
0N/A
0N/A flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
0N/A if (fixed) {
0N/A assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
0N/A flags |= MAP_FIXED;
0N/A }
0N/A
656N/A // Map uncommitted pages PROT_READ and PROT_WRITE, change access
656N/A // to PROT_EXEC if executable when we commit the page.
656N/A addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
0N/A flags, -1, 0);
0N/A
0N/A if (addr != MAP_FAILED) {
0N/A // anon_mmap() should only get called during VM initialization,
0N/A // don't need lock (actually we can skip locking even it can be called
0N/A // from multiple threads, because _highest_vm_reserved_address is just a
0N/A // hint about the upper limit of non-stack memory regions.)
0N/A if ((address)addr + bytes > _highest_vm_reserved_address) {
0N/A _highest_vm_reserved_address = (address)addr + bytes;
0N/A }
0N/A }
0N/A
0N/A return addr == MAP_FAILED ? NULL : addr;
0N/A}
0N/A
0N/A// Don't update _highest_vm_reserved_address, because there might be memory
0N/A// regions above addr + size. If so, releasing a memory region only creates
0N/A// a hole in the address space, it doesn't help prevent heap-stack collision.
0N/A//
0N/Astatic int anon_munmap(char * addr, size_t size) {
0N/A return ::munmap(addr, size) == 0;
0N/A}
0N/A
3863N/Achar* os::pd_reserve_memory(size_t bytes, char* requested_addr,
0N/A size_t alignment_hint) {
0N/A return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
0N/A}
0N/A
3863N/Abool os::pd_release_memory(char* addr, size_t size) {
0N/A return anon_munmap(addr, size);
0N/A}
0N/A
0N/Astatic address highest_vm_reserved_address() {
0N/A return _highest_vm_reserved_address;
0N/A}
0N/A
0N/Astatic bool linux_mprotect(char* addr, size_t size, int prot) {
0N/A // Linux wants the mprotect address argument to be page aligned.
0N/A char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size());
0N/A
0N/A // According to SUSv3, mprotect() should only be used with mappings
0N/A // established by mmap(), and mmap() always maps whole pages. Unaligned
0N/A // 'addr' likely indicates problem in the VM (e.g. trying to change
0N/A // protection of malloc'ed or statically allocated memory). Check the
0N/A // caller if you hit this assert.
0N/A assert(addr == bottom, "sanity check");
0N/A
0N/A size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
0N/A return ::mprotect(bottom, size, prot) == 0;
0N/A}
0N/A
237N/A// Set protections specified
237N/Abool os::protect_memory(char* addr, size_t bytes, ProtType prot,
237N/A bool is_committed) {
237N/A unsigned int p = 0;
237N/A switch (prot) {
237N/A case MEM_PROT_NONE: p = PROT_NONE; break;
237N/A case MEM_PROT_READ: p = PROT_READ; break;
237N/A case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
237N/A case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
237N/A default:
237N/A ShouldNotReachHere();
237N/A }
237N/A // is_committed is unused.
237N/A return linux_mprotect(addr, bytes, p);
0N/A}
0N/A
0N/Abool os::guard_memory(char* addr, size_t size) {
0N/A return linux_mprotect(addr, size, PROT_NONE);
0N/A}
0N/A
0N/Abool os::unguard_memory(char* addr, size_t size) {
477N/A return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
0N/A}
0N/A
2383N/Abool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2383N/A bool result = false;
2383N/A void *p = mmap (NULL, page_size, PROT_READ|PROT_WRITE,
2383N/A MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
2383N/A -1, 0);
2383N/A
4552N/A if (p != MAP_FAILED) {
2383N/A // We don't know if this really is a huge page or not.
2383N/A FILE *fp = fopen("/proc/self/maps", "r");
2383N/A if (fp) {
2383N/A while (!feof(fp)) {
2383N/A char chars[257];
2383N/A long x = 0;
2383N/A if (fgets(chars, sizeof(chars), fp)) {
2455N/A if (sscanf(chars, "%lx-%*x", &x) == 1
2383N/A && x == (long)p) {
2383N/A if (strstr (chars, "hugepage")) {
2383N/A result = true;
2383N/A break;
2383N/A }
2383N/A }
2383N/A }
2383N/A }
2383N/A fclose(fp);
2383N/A }
2383N/A munmap (p, page_size);
2383N/A if (result)
2383N/A return true;
2383N/A }
2383N/A
2383N/A if (warn) {
2383N/A warning("HugeTLBFS is not supported by the operating system.");
2383N/A }
2383N/A
2383N/A return result;
2383N/A}
2383N/A
2085N/A/*
2085N/A* Set the coredump_filter bits to include largepages in core dump (bit 6)
2085N/A*
2085N/A* From the coredump_filter documentation:
2085N/A*
2085N/A* - (bit 0) anonymous private memory
2085N/A* - (bit 1) anonymous shared memory
2085N/A* - (bit 2) file-backed private memory
2085N/A* - (bit 3) file-backed shared memory
2085N/A* - (bit 4) ELF header pages in file-backed private memory areas (it is
2085N/A* effective only if the bit 2 is cleared)
2085N/A* - (bit 5) hugetlb private memory
2085N/A* - (bit 6) hugetlb shared memory
2085N/A*/
2085N/Astatic void set_coredump_filter(void) {
2085N/A FILE *f;
2085N/A long cdm;
2085N/A
2085N/A if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
2085N/A return;
2085N/A }
2085N/A
2085N/A if (fscanf(f, "%lx", &cdm) != 1) {
2085N/A fclose(f);
2085N/A return;
2085N/A }
2085N/A
2085N/A rewind(f);
2085N/A
2085N/A if ((cdm & LARGEPAGES_BIT) == 0) {
2085N/A cdm |= LARGEPAGES_BIT;
2085N/A fprintf(f, "%#lx", cdm);
2085N/A }
2085N/A
2085N/A fclose(f);
2085N/A}
2085N/A
0N/A// Large page support
0N/A
0N/Astatic size_t _large_page_size = 0;
0N/A
2415N/Avoid os::large_page_init() {
2383N/A if (!UseLargePages) {
2383N/A UseHugeTLBFS = false;
2383N/A UseSHM = false;
2415N/A return;
2383N/A }
2383N/A
2383N/A if (FLAG_IS_DEFAULT(UseHugeTLBFS) && FLAG_IS_DEFAULT(UseSHM)) {
2415N/A // If UseLargePages is specified on the command line try both methods,
2415N/A // if it's default, then try only HugeTLBFS.
2415N/A if (FLAG_IS_DEFAULT(UseLargePages)) {
2415N/A UseHugeTLBFS = true;
2415N/A } else {
2415N/A UseHugeTLBFS = UseSHM = true;
2415N/A }
2383N/A }
0N/A
0N/A if (LargePageSizeInBytes) {
0N/A _large_page_size = LargePageSizeInBytes;
0N/A } else {
0N/A // large_page_size on Linux is used to round up heap size. x86 uses either
0N/A // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
0N/A // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
0N/A // page as large as 256M.
0N/A //
0N/A // Here we try to figure out page size by parsing /proc/meminfo and looking
0N/A // for a line with the following format:
0N/A // Hugepagesize: 2048 kB
0N/A //
0N/A // If we can't determine the value (e.g. /proc is not mounted, or the text
0N/A // format has been changed), we'll use the largest page size supported by
0N/A // the processor.
0N/A
1010N/A#ifndef ZERO
1601N/A _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M)
1601N/A ARM_ONLY(2 * M) PPC_ONLY(4 * M);
1010N/A#endif // ZERO
0N/A
0N/A FILE *fp = fopen("/proc/meminfo", "r");
0N/A if (fp) {
0N/A while (!feof(fp)) {
0N/A int x = 0;
0N/A char buf[16];
0N/A if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
0N/A if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
0N/A _large_page_size = x * K;
0N/A break;
0N/A }
0N/A } else {
0N/A // skip to next line
0N/A for (;;) {
0N/A int ch = fgetc(fp);
0N/A if (ch == EOF || ch == (int)'\n') break;
0N/A }
0N/A }
0N/A }
0N/A fclose(fp);
0N/A }
0N/A }
0N/A
2383N/A // print a warning if any large page related flag is specified on command line
2383N/A bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
2383N/A
0N/A const size_t default_page_size = (size_t)Linux::page_size();
0N/A if (_large_page_size > default_page_size) {
0N/A _page_sizes[0] = _large_page_size;
0N/A _page_sizes[1] = default_page_size;
0N/A _page_sizes[2] = 0;
0N/A }
2383N/A UseHugeTLBFS = UseHugeTLBFS &&
2383N/A Linux::hugetlbfs_sanity_check(warn_on_failure, _large_page_size);
2383N/A
2383N/A if (UseHugeTLBFS)
2383N/A UseSHM = false;
2383N/A
2383N/A UseLargePages = UseHugeTLBFS || UseSHM;
2383N/A
2085N/A set_coredump_filter();
0N/A}
0N/A
0N/A#ifndef SHM_HUGETLB
0N/A#define SHM_HUGETLB 04000
0N/A#endif
0N/A
656N/Achar* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
656N/A // "exec" is passed in but not used. Creating the shared image for
656N/A // the code cache doesn't have an SHM_X executable permission to check.
2383N/A assert(UseLargePages && UseSHM, "only for SHM large pages");
0N/A
0N/A key_t key = IPC_PRIVATE;
0N/A char *addr;
0N/A
0N/A bool warn_on_failure = UseLargePages &&
0N/A (!FLAG_IS_DEFAULT(UseLargePages) ||
0N/A !FLAG_IS_DEFAULT(LargePageSizeInBytes)
0N/A );
0N/A char msg[128];
0N/A
0N/A // Create a large shared memory region to attach to based on size.
0N/A // Currently, size is the total size of the heap
0N/A int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
0N/A if (shmid == -1) {
0N/A // Possible reasons for shmget failure:
0N/A // 1. shmmax is too small for Java heap.
0N/A // > check shmmax value: cat /proc/sys/kernel/shmmax
0N/A // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
0N/A // 2. not enough large page memory.
0N/A // > check available large pages: cat /proc/meminfo
0N/A // > increase amount of large pages:
0N/A // echo new_value > /proc/sys/vm/nr_hugepages
0N/A // Note 1: different Linux may use different name for this property,
0N/A // e.g. on Redhat AS-3 it is "hugetlb_pool".
0N/A // Note 2: it's possible there's enough physical memory available but
0N/A // they are so fragmented after a long run that they can't
0N/A // coalesce into large pages. Try to reserve large pages when
0N/A // the system is still "fresh".
0N/A if (warn_on_failure) {
0N/A jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
0N/A warning(msg);
0N/A }
0N/A return NULL;
0N/A }
0N/A
0N/A // attach to the region
1457N/A addr = (char*)shmat(shmid, req_addr, 0);
0N/A int err = errno;
0N/A
0N/A // Remove shmid. If shmat() is successful, the actual shared memory segment
0N/A // will be deleted when it's detached by shmdt() or when the process
0N/A // terminates. If shmat() is not successful this will remove the shared
0N/A // segment immediately.
0N/A shmctl(shmid, IPC_RMID, NULL);
0N/A
0N/A if ((intptr_t)addr == -1) {
0N/A if (warn_on_failure) {
0N/A jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
0N/A warning(msg);
0N/A }
0N/A return NULL;
0N/A }
0N/A
2719N/A if ((addr != NULL) && UseNUMAInterleaving) {
2719N/A numa_make_global(addr, bytes);
2719N/A }
2719N/A
4299N/A // The memory is committed
4559N/A MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
4299N/A
0N/A return addr;
0N/A}
0N/A
0N/Abool os::release_memory_special(char* base, size_t bytes) {
4559N/A MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
0N/A // detaching the SHM segment will also delete it, see reserve_memory_special()
0N/A int rslt = shmdt(base);
4299N/A if (rslt == 0) {
4559N/A tkr.record((address)base, bytes);
4299N/A return true;
4299N/A } else {
4559N/A tkr.discard();
4299N/A return false;
4299N/A }
0N/A}
0N/A
0N/Asize_t os::large_page_size() {
0N/A return _large_page_size;
0N/A}
0N/A
2383N/A// HugeTLBFS allows application to commit large page memory on demand;
2383N/A// with SysV SHM the entire memory region must be allocated as shared
2383N/A// memory.
0N/Abool os::can_commit_large_page_memory() {
2383N/A return UseHugeTLBFS;
0N/A}
0N/A
79N/Abool os::can_execute_large_page_memory() {
2383N/A return UseHugeTLBFS;
79N/A}
79N/A
0N/A// Reserve memory at an arbitrary address, only if that area is
0N/A// available (and not reserved for something else).
0N/A
3863N/Achar* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
0N/A const int max_tries = 10;
0N/A char* base[max_tries];
0N/A size_t size[max_tries];
0N/A const size_t gap = 0x000000;
0N/A
0N/A // Assert only that the size is a multiple of the page size, since
0N/A // that's all that mmap requires, and since that's all we really know
0N/A // about at this low abstraction level. If we need higher alignment,
0N/A // we can either pass an alignment to this method or verify alignment
0N/A // in one of the methods further up the call chain. See bug 5044738.
0N/A assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
0N/A
0N/A // Repeatedly allocate blocks until the block is allocated at the
0N/A // right spot. Give up after max_tries. Note that reserve_memory() will
0N/A // automatically update _highest_vm_reserved_address if the call is
0N/A // successful. The variable tracks the highest memory address every reserved
0N/A // by JVM. It is used to detect heap-stack collision if running with
0N/A // fixed-stack LinuxThreads. Because here we may attempt to reserve more
0N/A // space than needed, it could confuse the collision detecting code. To
0N/A // solve the problem, save current _highest_vm_reserved_address and
0N/A // calculate the correct value before return.
0N/A address old_highest = _highest_vm_reserved_address;
0N/A
0N/A // Linux mmap allows caller to pass an address as hint; give it a try first,
0N/A // if kernel honors the hint then we can return immediately.
0N/A char * addr = anon_mmap(requested_addr, bytes, false);
0N/A if (addr == requested_addr) {
0N/A return requested_addr;
0N/A }
0N/A
0N/A if (addr != NULL) {
0N/A // mmap() is successful but it fails to reserve at the requested address
0N/A anon_munmap(addr, bytes);
0N/A }
0N/A
0N/A int i;
0N/A for (i = 0; i < max_tries; ++i) {
0N/A base[i] = reserve_memory(bytes);
0N/A
0N/A if (base[i] != NULL) {
0N/A // Is this the block we wanted?
0N/A if (base[i] == requested_addr) {
0N/A size[i] = bytes;
0N/A break;
0N/A }
0N/A
0N/A // Does this overlap the block we wanted? Give back the overlapped
0N/A // parts and try again.
0N/A
0N/A size_t top_overlap = requested_addr + (bytes + gap) - base[i];
0N/A if (top_overlap >= 0 && top_overlap < bytes) {
0N/A unmap_memory(base[i], top_overlap);
0N/A base[i] += top_overlap;
0N/A size[i] = bytes - top_overlap;
0N/A } else {
0N/A size_t bottom_overlap = base[i] + bytes - requested_addr;
0N/A if (bottom_overlap >= 0 && bottom_overlap < bytes) {
0N/A unmap_memory(requested_addr, bottom_overlap);
0N/A size[i] = bytes - bottom_overlap;
0N/A } else {
0N/A size[i] = bytes;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A // Give back the unused reserved pieces.
0N/A
0N/A for (int j = 0; j < i; ++j) {
0N/A if (base[j] != NULL) {
0N/A unmap_memory(base[j], size[j]);
0N/A }
0N/A }
0N/A
0N/A if (i < max_tries) {
0N/A _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
0N/A return requested_addr;
0N/A } else {
0N/A _highest_vm_reserved_address = old_highest;
0N/A return NULL;
0N/A }
0N/A}
0N/A
0N/Asize_t os::read(int fd, void *buf, unsigned int nBytes) {
0N/A return ::read(fd, buf, nBytes);
0N/A}
0N/A
0N/A// TODO-FIXME: reconcile Solaris' os::sleep with the linux variation.
0N/A// Solaris uses poll(), linux uses park().
0N/A// Poll() is likely a better choice, assuming that Thread.interrupt()
0N/A// generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
0N/A// SIGSEGV, see 4355769.
0N/A
0N/Aint os::sleep(Thread* thread, jlong millis, bool interruptible) {
0N/A assert(thread == Thread::current(), "thread consistency check");
0N/A
0N/A ParkEvent * const slp = thread->_SleepEvent ;
0N/A slp->reset() ;
0N/A OrderAccess::fence() ;
0N/A
0N/A if (interruptible) {
0N/A jlong prevtime = javaTimeNanos();
0N/A
0N/A for (;;) {
0N/A if (os::is_interrupted(thread, true)) {
0N/A return OS_INTRPT;
0N/A }
0N/A
0N/A jlong newtime = javaTimeNanos();
0N/A
0N/A if (newtime - prevtime < 0) {
0N/A // time moving backwards, should only happen if no monotonic clock
0N/A // not a guarantee() because JVM should not abort on kernel/glibc bugs
0N/A assert(!Linux::supports_monotonic_clock(), "time moving backwards");
0N/A } else {
2988N/A millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
0N/A }
0N/A
0N/A if(millis <= 0) {
0N/A return OS_OK;
0N/A }
0N/A
0N/A prevtime = newtime;
0N/A
0N/A {
0N/A assert(thread->is_Java_thread(), "sanity check");
0N/A JavaThread *jt = (JavaThread *) thread;
0N/A ThreadBlockInVM tbivm(jt);
0N/A OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
0N/A
0N/A jt->set_suspend_equivalent();
0N/A // cleared by handle_special_suspend_equivalent_condition() or
0N/A // java_suspend_self() via check_and_wait_while_suspended()
0N/A
0N/A slp->park(millis);
0N/A
0N/A // were we externally suspended while we were waiting?
0N/A jt->check_and_wait_while_suspended();
0N/A }
0N/A }
0N/A } else {
0N/A OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
0N/A jlong prevtime = javaTimeNanos();
0N/A
0N/A for (;;) {
0N/A // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
0N/A // the 1st iteration ...
0N/A jlong newtime = javaTimeNanos();
0N/A
0N/A if (newtime - prevtime < 0) {
0N/A // time moving backwards, should only happen if no monotonic clock
0N/A // not a guarantee() because JVM should not abort on kernel/glibc bugs
0N/A assert(!Linux::supports_monotonic_clock(), "time moving backwards");
0N/A } else {
2988N/A millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
0N/A }
0N/A
0N/A if(millis <= 0) break ;
0N/A
0N/A prevtime = newtime;
0N/A slp->park(millis);
0N/A }
0N/A return OS_OK ;
0N/A }
0N/A}
0N/A
0N/Aint os::naked_sleep() {
0N/A // %% make the sleep time an integer flag. for now use 1 millisec.
0N/A return os::sleep(Thread::current(), 1, false);
0N/A}
0N/A
0N/A// Sleep forever; naked call to OS-specific sleep; use with CAUTION
0N/Avoid os::infinite_sleep() {
0N/A while (true) { // sleep forever ...
0N/A ::sleep(100); // ... 100 seconds at a time
0N/A }
0N/A}
0N/A
0N/A// Used to convert frequent JVM_Yield() to nops
0N/Abool os::dont_yield() {
0N/A return DontYieldALot;
0N/A}
0N/A
0N/Avoid os::yield() {
0N/A sched_yield();
0N/A}
0N/A
0N/Aos::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
0N/A
0N/Avoid os::yield_all(int attempts) {
0N/A // Yields to all threads, including threads with lower priorities
0N/A // Threads on Linux are all with same priority. The Solaris style
0N/A // os::yield_all() with nanosleep(1ms) is not necessary.
0N/A sched_yield();
0N/A}
0N/A
0N/A// Called from the tight loops to possibly influence time-sharing heuristics
0N/Avoid os::loop_breaker(int attempts) {
0N/A os::yield_all(attempts);
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// thread priority support
0N/A
0N/A// Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
0N/A// only supports dynamic priority, static priority must be zero. For real-time
0N/A// applications, Linux supports SCHED_RR which allows static priority (1-99).
0N/A// However, for large multi-threaded applications, SCHED_RR is not only slower
0N/A// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
0N/A// of 5 runs - Sep 2005).
0N/A//
0N/A// The following code actually changes the niceness of kernel-thread/LWP. It
0N/A// has an assumption that setpriority() only modifies one kernel-thread/LWP,
0N/A// not the entire user process, and user level threads are 1:1 mapped to kernel
0N/A// threads. It has always been the case, but could change in the future. For
0N/A// this reason, the code should not be used as default (ThreadPriorityPolicy=0).
0N/A// It is only used when ThreadPriorityPolicy=1 and requires root privilege.
0N/A
3137N/Aint os::java_to_os_priority[CriticalPriority + 1] = {
0N/A 19, // 0 Entry should never be used
0N/A
0N/A 4, // 1 MinPriority
0N/A 3, // 2
0N/A 2, // 3
0N/A
0N/A 1, // 4
0N/A 0, // 5 NormPriority
0N/A -1, // 6
0N/A
0N/A -2, // 7
0N/A -3, // 8
0N/A -4, // 9 NearMaxPriority
0N/A
3137N/A -5, // 10 MaxPriority
3137N/A
3137N/A -5 // 11 CriticalPriority
0N/A};
0N/A
0N/Astatic int prio_init() {
0N/A if (ThreadPriorityPolicy == 1) {
0N/A // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
0N/A // if effective uid is not root. Perhaps, a more elegant way of doing
0N/A // this is to test CAP_SYS_NICE capability, but that will require libcap.so
0N/A if (geteuid() != 0) {
0N/A if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
0N/A warning("-XX:ThreadPriorityPolicy requires root privilege on Linux");
0N/A }
0N/A ThreadPriorityPolicy = 0;
0N/A }
0N/A }
3137N/A if (UseCriticalJavaThreadPriority) {
3137N/A os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
3137N/A }
0N/A return 0;
0N/A}
0N/A
0N/AOSReturn os::set_native_priority(Thread* thread, int newpri) {
0N/A if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
0N/A
0N/A int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
0N/A return (ret == 0) ? OS_OK : OS_ERR;
0N/A}
0N/A
0N/AOSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
0N/A if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
0N/A *priority_ptr = java_to_os_priority[NormPriority];
0N/A return OS_OK;
0N/A }
0N/A
0N/A errno = 0;
0N/A *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
0N/A return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
0N/A}
0N/A
0N/A// Hint to the underlying OS that a task switch would not be good.
0N/A// Void return because it's a hint and can fail.
0N/Avoid os::hint_no_preempt() {}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// suspend/resume support
0N/A
0N/A// the low-level signal-based suspend/resume support is a remnant from the
0N/A// old VM-suspension that used to be for java-suspension, safepoints etc,
0N/A// within hotspot. Now there is a single use-case for this:
0N/A// - calling get_thread_pc() on the VMThread by the flat-profiler task
0N/A// that runs in the watcher thread.
0N/A// The remaining code is greatly simplified from the more general suspension
0N/A// code that used to be used.
0N/A//
0N/A// The protocol is quite simple:
0N/A// - suspend:
0N/A// - sends a signal to the target thread
0N/A// - polls the suspend state of the osthread using a yield loop
0N/A// - target thread signal handler (SR_handler) sets suspend state
0N/A// and blocks in sigsuspend until continued
0N/A// - resume:
0N/A// - sets target osthread state to continue
0N/A// - sends signal to end the sigsuspend loop in the SR_handler
0N/A//
0N/A// Note that the SR_lock plays no role in this suspend/resume protocol.
0N/A//
0N/A
0N/Astatic void resume_clear_context(OSThread *osthread) {
0N/A osthread->set_ucontext(NULL);
0N/A osthread->set_siginfo(NULL);
0N/A}
0N/A
0N/Astatic void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
0N/A osthread->set_ucontext(context);
0N/A osthread->set_siginfo(siginfo);
0N/A}
0N/A
0N/A//
0N/A// Handler function invoked when a thread's execution is suspended or
0N/A// resumed. We have to be careful that only async-safe functions are
0N/A// called here (Note: most pthread functions are not async safe and
0N/A// should be avoided.)
0N/A//
0N/A// Note: sigwait() is a more natural fit than sigsuspend() from an
0N/A// interface point of view, but sigwait() prevents the signal hander
0N/A// from being run. libpthread would get very confused by not having
0N/A// its signal handlers run and prevents sigwait()'s use with the
0N/A// mutex granting granting signal.
0N/A//
4141N/A// Currently only ever called on the VMThread and JavaThreads (PC sampling)
0N/A//
0N/Astatic void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
0N/A // Save and restore errno to avoid confusing native code with EINTR
0N/A // after sigsuspend.
0N/A int old_errno = errno;
0N/A
0N/A Thread* thread = Thread::current();
0N/A OSThread* osthread = thread->osthread();
4141N/A assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
4141N/A
4141N/A os::SuspendResume::State current = osthread->sr.state();
4141N/A if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
0N/A suspend_save_context(osthread, siginfo, context);
0N/A
4141N/A // attempt to switch the state, we assume we had a SUSPEND_REQUEST
4141N/A os::SuspendResume::State state = osthread->sr.suspended();
4141N/A if (state == os::SuspendResume::SR_SUSPENDED) {
4141N/A sigset_t suspend_set; // signals for sigsuspend()
4141N/A
4141N/A // get current set of blocked signals and unblock resume signal
4141N/A pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
4141N/A sigdelset(&suspend_set, SR_signum);
4141N/A
4433N/A sr_semaphore.signal();
4141N/A // wait here until we are resumed
4141N/A while (1) {
4141N/A sigsuspend(&suspend_set);
4141N/A
4141N/A os::SuspendResume::State result = osthread->sr.running();
4141N/A if (result == os::SuspendResume::SR_RUNNING) {
4433N/A sr_semaphore.signal();
4141N/A break;
4141N/A }
4141N/A }
4141N/A
4141N/A } else if (state == os::SuspendResume::SR_RUNNING) {
4141N/A // request was cancelled, continue
4141N/A } else {
4141N/A ShouldNotReachHere();
4141N/A }
0N/A
0N/A resume_clear_context(osthread);
4141N/A } else if (current == os::SuspendResume::SR_RUNNING) {
4141N/A // request was cancelled, continue
4141N/A } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
4141N/A // ignore
0N/A } else {
4433N/A // ignore
0N/A }
0N/A
0N/A errno = old_errno;
0N/A}
0N/A
0N/A
0N/Astatic int SR_initialize() {
0N/A struct sigaction act;
0N/A char *s;
0N/A /* Get signal number to use for suspend/resume */
0N/A if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
0N/A int sig = ::strtol(s, 0, 10);
0N/A if (sig > 0 || sig < _NSIG) {
0N/A SR_signum = sig;
0N/A }
0N/A }
0N/A
0N/A assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
0N/A "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
0N/A
0N/A sigemptyset(&SR_sigset);
0N/A sigaddset(&SR_sigset, SR_signum);
0N/A
0N/A /* Set up signal handler for suspend/resume */
0N/A act.sa_flags = SA_RESTART|SA_SIGINFO;
0N/A act.sa_handler = (void (*)(int)) SR_handler;
0N/A
0N/A // SR_signum is blocked by default.
0N/A // 4528190 - We also need to block pthread restart signal (32 on all
0N/A // supported Linux platforms). Note that LinuxThreads need to block
0N/A // this signal for all threads to work properly. So we don't have
0N/A // to use hard-coded signal number when setting up the mask.
0N/A pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
0N/A
0N/A if (sigaction(SR_signum, &act, 0) == -1) {
0N/A return -1;
0N/A }
0N/A
0N/A // Save signal flag
0N/A os::Linux::set_our_sigflags(SR_signum, act.sa_flags);
0N/A return 0;
0N/A}
0N/A
0N/Astatic int SR_finalize() {
0N/A return 0;
0N/A}
0N/A
4141N/Astatic int sr_notify(OSThread* osthread) {
4141N/A int status = pthread_kill(osthread->pthread_id(), SR_signum);
4141N/A assert_status(status == 0, status, "pthread_kill");
4141N/A return status;
4141N/A}
4141N/A
4141N/A// "Randomly" selected value for how long we want to spin
4141N/A// before bailing out on suspending a thread, also how often
4141N/A// we send a signal to a thread we want to resume
4141N/Astatic const int RANDOMLY_LARGE_INTEGER = 1000000;
4141N/Astatic const int RANDOMLY_LARGE_INTEGER2 = 100;
0N/A
0N/A// returns true on success and false on error - really an error is fatal
0N/A// but this seems the normal response to library errors
0N/Astatic bool do_suspend(OSThread* osthread) {
4141N/A assert(osthread->sr.is_running(), "thread should be running");
4433N/A assert(!sr_semaphore.trywait(), "semaphore has invalid state");
4433N/A
0N/A // mark as suspended and send signal
4141N/A if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
4141N/A // failed to switch, state wasn't running?
4141N/A ShouldNotReachHere();
4141N/A return false;
4141N/A }
4141N/A
4141N/A if (sr_notify(osthread) != 0) {
4433N/A ShouldNotReachHere();
4141N/A }
4141N/A
4141N/A // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
4433N/A while (true) {
4433N/A if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4433N/A break;
4433N/A } else {
4433N/A // timeout
4141N/A os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
4141N/A if (cancelled == os::SuspendResume::SR_RUNNING) {
4141N/A return false;
4141N/A } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
4433N/A // make sure that we consume the signal on the semaphore as well
4433N/A sr_semaphore.wait();
4433N/A break;
4141N/A } else {
4141N/A ShouldNotReachHere();
4141N/A return false;
4141N/A }
4141N/A }
4141N/A }
4141N/A
4141N/A guarantee(osthread->sr.is_suspended(), "Must be suspended");
4141N/A return true;
0N/A}
0N/A
0N/Astatic void do_resume(OSThread* osthread) {
0N/A assert(osthread->sr.is_suspended(), "thread should be suspended");
4433N/A assert(!sr_semaphore.trywait(), "invalid semaphore state");
4141N/A
4141N/A if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
4141N/A // failed to switch to WAKEUP_REQUEST
4141N/A ShouldNotReachHere();
4141N/A return;
4141N/A }
4141N/A
4433N/A while (true) {
4141N/A if (sr_notify(osthread) == 0) {
4433N/A if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4433N/A if (osthread->sr.is_running()) {
4433N/A return;
4141N/A }
4141N/A }
4141N/A } else {
4141N/A ShouldNotReachHere();
0N/A }
0N/A }
4141N/A
4141N/A guarantee(osthread->sr.is_running(), "Must be running!");
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// interrupt support
0N/A
0N/Avoid os::interrupt(Thread* thread) {
0N/A assert(Thread::current() == thread || Threads_lock->owned_by_self(),
0N/A "possibility of dangling Thread pointer");
0N/A
0N/A OSThread* osthread = thread->osthread();
0N/A
0N/A if (!osthread->interrupted()) {
0N/A osthread->set_interrupted(true);
0N/A // More than one thread can get here with the same value of osthread,
0N/A // resulting in multiple notifications. We do, however, want the store
0N/A // to interrupted() to be visible to other threads before we execute unpark().
0N/A OrderAccess::fence();
0N/A ParkEvent * const slp = thread->_SleepEvent ;
0N/A if (slp != NULL) slp->unpark() ;
0N/A }
0N/A
0N/A // For JSR166. Unpark even if interrupt status already was set
0N/A if (thread->is_Java_thread())
0N/A ((JavaThread*)thread)->parker()->unpark();
0N/A
0N/A ParkEvent * ev = thread->_ParkEvent ;
0N/A if (ev != NULL) ev->unpark() ;
0N/A
0N/A}
0N/A
0N/Abool os::is_interrupted(Thread* thread, bool clear_interrupted) {
0N/A assert(Thread::current() == thread || Threads_lock->owned_by_self(),
0N/A "possibility of dangling Thread pointer");
0N/A
0N/A OSThread* osthread = thread->osthread();
0N/A
0N/A bool interrupted = osthread->interrupted();
0N/A
0N/A if (interrupted && clear_interrupted) {
0N/A osthread->set_interrupted(false);
0N/A // consider thread->_SleepEvent->reset() ... optional optimization
0N/A }
0N/A
0N/A return interrupted;
0N/A}
0N/A
0N/A///////////////////////////////////////////////////////////////////////////////////
0N/A// signal handling (except suspend/resume)
0N/A
0N/A// This routine may be used by user applications as a "hook" to catch signals.
0N/A// The user-defined signal handler must pass unrecognized signals to this
0N/A// routine, and if it returns true (non-zero), then the signal handler must
0N/A// return immediately. If the flag "abort_if_unrecognized" is true, then this
0N/A// routine will never retun false (zero), but instead will execute a VM panic
0N/A// routine kill the process.
0N/A//
0N/A// If this routine returns false, it is OK to call it again. This allows
0N/A// the user-defined signal handler to perform checks either before or after
0N/A// the VM performs its own checks. Naturally, the user code would be making
0N/A// a serious error if it tried to handle an exception (such as a null check
0N/A// or breakpoint) that the VM was generating for its own correct operation.
0N/A//
0N/A// This routine may recognize any of the following kinds of signals:
0N/A// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
0N/A// It should be consulted by handlers for any of those signals.
0N/A//
0N/A// The caller of this routine must pass in the three arguments supplied
0N/A// to the function referred to in the "sa_sigaction" (not the "sa_handler")
0N/A// field of the structure passed to sigaction(). This routine assumes that
0N/A// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
0N/A//
0N/A// Note that the VM will print warnings if it detects conflicting signal
0N/A// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
0N/A//
2072N/Aextern "C" JNIEXPORT int
0N/AJVM_handle_linux_signal(int signo, siginfo_t* siginfo,
0N/A void* ucontext, int abort_if_unrecognized);
0N/A
0N/Avoid signalHandler(int sig, siginfo_t* info, void* uc) {
0N/A assert(info != NULL && uc != NULL, "it must be old kernel");
0N/A JVM_handle_linux_signal(sig, info, uc, true);
0N/A}
0N/A
0N/A
0N/A// This boolean allows users to forward their own non-matching signals
0N/A// to JVM_handle_linux_signal, harmlessly.
0N/Abool os::Linux::signal_handlers_are_installed = false;
0N/A
0N/A// For signal-chaining
0N/Astruct sigaction os::Linux::sigact[MAXSIGNUM];
0N/Aunsigned int os::Linux::sigs = 0;
0N/Abool os::Linux::libjsig_is_loaded = false;
0N/Atypedef struct sigaction *(*get_signal_t)(int);
0N/Aget_signal_t os::Linux::get_signal_action = NULL;
0N/A
0N/Astruct sigaction* os::Linux::get_chained_signal_action(int sig) {
0N/A struct sigaction *actp = NULL;
0N/A
0N/A if (libjsig_is_loaded) {
0N/A // Retrieve the old signal handler from libjsig
0N/A actp = (*get_signal_action)(sig);
0N/A }
0N/A if (actp == NULL) {
0N/A // Retrieve the preinstalled signal handler from jvm
0N/A actp = get_preinstalled_handler(sig);
0N/A }
0N/A
0N/A return actp;
0N/A}
0N/A
0N/Astatic bool call_chained_handler(struct sigaction *actp, int sig,
0N/A siginfo_t *siginfo, void *context) {
0N/A // Call the old signal handler
0N/A if (actp->sa_handler == SIG_DFL) {
0N/A // It's more reasonable to let jvm treat it as an unexpected exception
0N/A // instead of taking the default action.
0N/A return false;
0N/A } else if (actp->sa_handler != SIG_IGN) {
0N/A if ((actp->sa_flags & SA_NODEFER) == 0) {
0N/A // automaticlly block the signal
0N/A sigaddset(&(actp->sa_mask), sig);
0N/A }
0N/A
0N/A sa_handler_t hand;
0N/A sa_sigaction_t sa;
0N/A bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
0N/A // retrieve the chained handler
0N/A if (siginfo_flag_set) {
0N/A sa = actp->sa_sigaction;
0N/A } else {
0N/A hand = actp->sa_handler;
0N/A }
0N/A
0N/A if ((actp->sa_flags & SA_RESETHAND) != 0) {
0N/A actp->sa_handler = SIG_DFL;
0N/A }
0N/A
0N/A // try to honor the signal mask
0N/A sigset_t oset;
0N/A pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
0N/A
0N/A // call into the chained handler
0N/A if (siginfo_flag_set) {
0N/A (*sa)(sig, siginfo, context);
0N/A } else {
0N/A (*hand)(sig);
0N/A }
0N/A
0N/A // restore the signal mask
0N/A pthread_sigmask(SIG_SETMASK, &oset, 0);
0N/A }
0N/A // Tell jvm's signal handler the signal is taken care of.
0N/A return true;
0N/A}
0N/A
0N/Abool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) {
0N/A bool chained = false;
0N/A // signal-chaining
0N/A if (UseSignalChaining) {
0N/A struct sigaction *actp = get_chained_signal_action(sig);
0N/A if (actp != NULL) {
0N/A chained = call_chained_handler(actp, sig, siginfo, context);
0N/A }
0N/A }
0N/A return chained;
0N/A}
0N/A
0N/Astruct sigaction* os::Linux::get_preinstalled_handler(int sig) {
0N/A if ((( (unsigned int)1 << sig ) & sigs) != 0) {
0N/A return &sigact[sig];
0N/A }
0N/A return NULL;
0N/A}
0N/A
0N/Avoid os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
0N/A assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
0N/A sigact[sig] = oldAct;
0N/A sigs |= (unsigned int)1 << sig;
0N/A}
0N/A
0N/A// for diagnostic
0N/Aint os::Linux::sigflags[MAXSIGNUM];
0N/A
0N/Aint os::Linux::get_our_sigflags(int sig) {
0N/A assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
0N/A return sigflags[sig];
0N/A}
0N/A
0N/Avoid os::Linux::set_our_sigflags(int sig, int flags) {
0N/A assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
0N/A sigflags[sig] = flags;
0N/A}
0N/A
0N/Avoid os::Linux::set_signal_handler(int sig, bool set_installed) {
0N/A // Check for overwrite.
0N/A struct sigaction oldAct;
0N/A sigaction(sig, (struct sigaction*)NULL, &oldAct);
0N/A
0N/A void* oldhand = oldAct.sa_sigaction
0N/A ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
0N/A : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
0N/A if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
0N/A oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
0N/A oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
0N/A if (AllowUserSignalHandlers || !set_installed) {
0N/A // Do not overwrite; user takes responsibility to forward to us.
0N/A return;
0N/A } else if (UseSignalChaining) {
0N/A // save the old handler in jvm
0N/A save_preinstalled_handler(sig, oldAct);
0N/A // libjsig also interposes the sigaction() call below and saves the
0N/A // old sigaction on it own.
0N/A } else {
1410N/A fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
1410N/A "%#lx for signal %d.", (long)oldhand, sig));
0N/A }
0N/A }
0N/A
0N/A struct sigaction sigAct;
0N/A sigfillset(&(sigAct.sa_mask));
0N/A sigAct.sa_handler = SIG_DFL;
0N/A if (!set_installed) {
0N/A sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
0N/A } else {
0N/A sigAct.sa_sigaction = signalHandler;
0N/A sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
0N/A }
0N/A // Save flags, which are set by ours
0N/A assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
0N/A sigflags[sig] = sigAct.sa_flags;
0N/A
0N/A int ret = sigaction(sig, &sigAct, &oldAct);
0N/A assert(ret == 0, "check");
0N/A
0N/A void* oldhand2 = oldAct.sa_sigaction
0N/A ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
0N/A : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
0N/A assert(oldhand2 == oldhand, "no concurrent signal handler installation");
0N/A}
0N/A
0N/A// install signal handlers for signals that HotSpot needs to
0N/A// handle in order to support Java-level exception handling.
0N/A
0N/Avoid os::Linux::install_signal_handlers() {
0N/A if (!signal_handlers_are_installed) {
0N/A signal_handlers_are_installed = true;
0N/A
0N/A // signal-chaining
0N/A typedef void (*signal_setting_t)();
0N/A signal_setting_t begin_signal_setting = NULL;
0N/A signal_setting_t end_signal_setting = NULL;
0N/A begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
0N/A dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
0N/A if (begin_signal_setting != NULL) {
0N/A end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
0N/A dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
0N/A get_signal_action = CAST_TO_FN_PTR(get_signal_t,
0N/A dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
0N/A libjsig_is_loaded = true;
0N/A assert(UseSignalChaining, "should enable signal-chaining");
0N/A }
0N/A if (libjsig_is_loaded) {
0N/A // Tell libjsig jvm is setting signal handlers
0N/A (*begin_signal_setting)();
0N/A }
0N/A
0N/A set_signal_handler(SIGSEGV, true);
0N/A set_signal_handler(SIGPIPE, true);
0N/A set_signal_handler(SIGBUS, true);
0N/A set_signal_handler(SIGILL, true);
0N/A set_signal_handler(SIGFPE, true);
0N/A set_signal_handler(SIGXFSZ, true);
0N/A
0N/A if (libjsig_is_loaded) {
0N/A // Tell libjsig jvm finishes setting signal handlers
0N/A (*end_signal_setting)();
0N/A }
0N/A
0N/A // We don't activate signal checker if libjsig is in place, we trust ourselves
2792N/A // and if UserSignalHandler is installed all bets are off.
2792N/A // Log that signal checking is off only if -verbose:jni is specified.
0N/A if (CheckJNICalls) {
0N/A if (libjsig_is_loaded) {
2792N/A if (PrintJNIResolving) {
2792N/A tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
2792N/A }
0N/A check_signals = false;
0N/A }
0N/A if (AllowUserSignalHandlers) {
2792N/A if (PrintJNIResolving) {
2792N/A tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
2792N/A }
0N/A check_signals = false;
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
0N/A// This is the fastest way to get thread cpu time on Linux.
0N/A// Returns cpu time (user+sys) for any thread, not only for current.
0N/A// POSIX compliant clocks are implemented in the kernels 2.6.16+.
0N/A// It might work on 2.6.10+ with a special kernel/glibc patch.
0N/A// For reference, please, see IEEE Std 1003.1-2004:
0N/A// http://www.unix.org/single_unix_specification
0N/A
0N/Ajlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
0N/A struct timespec tp;
0N/A int rc = os::Linux::clock_gettime(clockid, &tp);
0N/A assert(rc == 0, "clock_gettime is expected to return 0 code");
0N/A
2988N/A return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
0N/A}
0N/A
0N/A/////
0N/A// glibc on Linux platform uses non-documented flag
0N/A// to indicate, that some special sort of signal
0N/A// trampoline is used.
0N/A// We will never set this flag, and we should
0N/A// ignore this flag in our diagnostic
0N/A#ifdef SIGNIFICANT_SIGNAL_MASK
0N/A#undef SIGNIFICANT_SIGNAL_MASK
0N/A#endif
0N/A#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
0N/A
0N/Astatic const char* get_signal_handler_name(address handler,
0N/A char* buf, int buflen) {
0N/A int offset;
0N/A bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
0N/A if (found) {
0N/A // skip directory names
0N/A const char *p1, *p2;
0N/A p1 = buf;
0N/A size_t len = strlen(os::file_separator());
0N/A while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
0N/A jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
0N/A } else {
0N/A jio_snprintf(buf, buflen, PTR_FORMAT, handler);
0N/A }
0N/A return buf;
0N/A}
0N/A
0N/Astatic void print_signal_handler(outputStream* st, int sig,
0N/A char* buf, size_t buflen) {
0N/A struct sigaction sa;
0N/A
0N/A sigaction(sig, NULL, &sa);
0N/A
0N/A // See comment for SIGNIFICANT_SIGNAL_MASK define
0N/A sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
0N/A
0N/A st->print("%s: ", os::exception_name(sig, buf, buflen));
0N/A
0N/A address handler = (sa.sa_flags & SA_SIGINFO)
0N/A ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
0N/A : CAST_FROM_FN_PTR(address, sa.sa_handler);
0N/A
0N/A if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
0N/A st->print("SIG_DFL");
0N/A } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
0N/A st->print("SIG_IGN");
0N/A } else {
0N/A st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
0N/A }
0N/A
0N/A st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
0N/A
0N/A address rh = VMError::get_resetted_sighandler(sig);
0N/A // May be, handler was resetted by VMError?
0N/A if(rh != NULL) {
0N/A handler = rh;
0N/A sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
0N/A }
0N/A
0N/A st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags);
0N/A
0N/A // Check: is it our handler?
0N/A if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
0N/A handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
0N/A // It is our signal handler
0N/A // check for flags, reset system-used one!
0N/A if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) {
0N/A st->print(
0N/A ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
0N/A os::Linux::get_our_sigflags(sig));
0N/A }
0N/A }
0N/A st->cr();
0N/A}
0N/A
0N/A
0N/A#define DO_SIGNAL_CHECK(sig) \
0N/A if (!sigismember(&check_signal_done, sig)) \
0N/A os::Linux::check_signal_handler(sig)
0N/A
0N/A// This method is a periodic task to check for misbehaving JNI applications
0N/A// under CheckJNI, we can add any periodic checks here
0N/A
0N/Avoid os::run_periodic_checks() {
0N/A
0N/A if (check_signals == false) return;
0N/A
0N/A // SEGV and BUS if overridden could potentially prevent
0N/A // generation of hs*.log in the event of a crash, debugging
0N/A // such a case can be very challenging, so we absolutely
0N/A // check the following for a good measure:
0N/A DO_SIGNAL_CHECK(SIGSEGV);
0N/A DO_SIGNAL_CHECK(SIGILL);
0N/A DO_SIGNAL_CHECK(SIGFPE);
0N/A DO_SIGNAL_CHECK(SIGBUS);
0N/A DO_SIGNAL_CHECK(SIGPIPE);
0N/A DO_SIGNAL_CHECK(SIGXFSZ);
0N/A
0N/A
0N/A // ReduceSignalUsage allows the user to override these handlers
0N/A // see comments at the very top and jvm_solaris.h
0N/A if (!ReduceSignalUsage) {
0N/A DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
0N/A DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
0N/A DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
0N/A DO_SIGNAL_CHECK(BREAK_SIGNAL);
0N/A }
0N/A
0N/A DO_SIGNAL_CHECK(SR_signum);
0N/A DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
0N/A}
0N/A
0N/Atypedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
0N/A
0N/Astatic os_sigaction_t os_sigaction = NULL;
0N/A
0N/Avoid os::Linux::check_signal_handler(int sig) {
0N/A char buf[O_BUFLEN];
0N/A address jvmHandler = NULL;
0N/A
0N/A
0N/A struct sigaction act;
0N/A if (os_sigaction == NULL) {
0N/A // only trust the default sigaction, in case it has been interposed
0N/A os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
0N/A if (os_sigaction == NULL) return;
0N/A }
0N/A
0N/A os_sigaction(sig, (struct sigaction*)NULL, &act);
0N/A
0N/A
0N/A act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
0N/A
0N/A address thisHandler = (act.sa_flags & SA_SIGINFO)
0N/A ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
0N/A : CAST_FROM_FN_PTR(address, act.sa_handler) ;
0N/A
0N/A
0N/A switch(sig) {
0N/A case SIGSEGV:
0N/A case SIGBUS:
0N/A case SIGFPE:
0N/A case SIGPIPE:
0N/A case SIGILL:
0N/A case SIGXFSZ:
0N/A jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
0N/A break;
0N/A
0N/A case SHUTDOWN1_SIGNAL:
0N/A case SHUTDOWN2_SIGNAL:
0N/A case SHUTDOWN3_SIGNAL:
0N/A case BREAK_SIGNAL:
0N/A jvmHandler = (address)user_handler();
0N/A break;
0N/A
0N/A case INTERRUPT_SIGNAL:
0N/A jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
0N/A break;
0N/A
0N/A default:
0N/A if (sig == SR_signum) {
0N/A jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
0N/A } else {
0N/A return;
0N/A }
0N/A break;
0N/A }
0N/A
0N/A if (thisHandler != jvmHandler) {
0N/A tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
0N/A tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
0N/A tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
0N/A // No need to check this sig any longer
0N/A sigaddset(&check_signal_done, sig);
0N/A } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) {
0N/A tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
0N/A tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig));
0N/A tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);
0N/A // No need to check this sig any longer
0N/A sigaddset(&check_signal_done, sig);
0N/A }
0N/A
0N/A // Dump all the signal
0N/A if (sigismember(&check_signal_done, sig)) {
0N/A print_signal_handlers(tty, buf, O_BUFLEN);
0N/A }
0N/A}
0N/A
0N/Aextern void report_error(char* file_name, int line_no, char* title, char* format, ...);
0N/A
0N/Aextern bool signal_name(int signo, char* buf, size_t len);
0N/A
0N/Aconst char* os::exception_name(int exception_code, char* buf, size_t size) {
0N/A if (0 < exception_code && exception_code <= SIGRTMAX) {
0N/A // signal
0N/A if (!signal_name(exception_code, buf, size)) {
0N/A jio_snprintf(buf, size, "SIG%d", exception_code);
0N/A }
0N/A return buf;
0N/A } else {
0N/A return NULL;
0N/A }
0N/A}
0N/A
0N/A// this is called _before_ the most of global arguments have been parsed
0N/Avoid os::init(void) {
0N/A char dummy; /* used to get a guess on initial stack address */
0N/A// first_hrtime = gethrtime();
0N/A
0N/A // With LinuxThreads the JavaMain thread pid (primordial thread)
0N/A // is different than the pid of the java launcher thread.
0N/A // So, on Linux, the launcher thread pid is passed to the VM
0N/A // via the sun.java.launcher.pid property.
0N/A // Use this property instead of getpid() if it was correctly passed.
0N/A // See bug 6351349.
0N/A pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
0N/A
0N/A _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
0N/A
0N/A clock_tics_per_sec = sysconf(_SC_CLK_TCK);
0N/A
0N/A init_random(1234567);
0N/A
0N/A ThreadCritical::initialize();
0N/A
0N/A Linux::set_page_size(sysconf(_SC_PAGESIZE));
0N/A if (Linux::page_size() == -1) {
1410N/A fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)",
1410N/A strerror(errno)));
0N/A }
0N/A init_page_sizes((size_t) Linux::page_size());
0N/A
0N/A Linux::initialize_system_info();
0N/A
0N/A // main_thread points to the aboriginal thread
0N/A Linux::_main_thread = pthread_self();
0N/A
0N/A Linux::clock_init();
0N/A initial_time_count = os::elapsed_counter();
242N/A pthread_mutex_init(&dl_mutex, NULL);
4531N/A
4531N/A // If the pagesize of the VM is greater than 8K determine the appropriate
4531N/A // number of initial guard pages. The user can change this with the
4531N/A // command line arguments, if needed.
4531N/A if (vm_page_size() > (int)Linux::vm_default_page_size()) {
4531N/A StackYellowPages = 1;
4531N/A StackRedPages = 1;
4531N/A StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
4531N/A }
0N/A}
0N/A
0N/A// To install functions for atexit system call
0N/Aextern "C" {
0N/A static void perfMemory_exit_helper() {
0N/A perfMemory_exit();
0N/A }
0N/A}
0N/A
0N/A// this is called _after_ the global arguments have been parsed
0N/Ajint os::init_2(void)
0N/A{
0N/A Linux::fast_thread_clock_init();
0N/A
0N/A // Allocate a single page and mark it as readable for safepoint polling
0N/A address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
0N/A guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
0N/A
0N/A os::set_polling_page( polling_page );
0N/A
0N/A#ifndef PRODUCT
0N/A if(Verbose && PrintMiscellaneous)
0N/A tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
0N/A#endif
0N/A
0N/A if (!UseMembar) {
0N/A address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4552N/A guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
0N/A os::set_memory_serialize_page( mem_serialize_page );
0N/A
0N/A#ifndef PRODUCT
0N/A if(Verbose && PrintMiscellaneous)
0N/A tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
0N/A#endif
0N/A }
0N/A
2415N/A os::large_page_init();
0N/A
0N/A // initialize suspend/resume support - must do this before signal_sets_init()
0N/A if (SR_initialize() != 0) {
0N/A perror("SR_initialize failed");
0N/A return JNI_ERR;
0N/A }
0N/A
0N/A Linux::signal_sets_init();
0N/A Linux::install_signal_handlers();
0N/A
1787N/A // Check minimum allowable stack size for thread creation and to initialize
1787N/A // the java system classes, including StackOverflowError - depends on page
1787N/A // size. Add a page for compiler2 recursion in main thread.
1787N/A // Add in 2*BytesPerWord times page size to account for VM stack during
1787N/A // class initialization depending on 32 or 64 bit VM.
1787N/A os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
4531N/A (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() +
4531N/A (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size());
1787N/A
0N/A size_t threadStackSizeInBytes = ThreadStackSize * K;
0N/A if (threadStackSizeInBytes != 0 &&
1787N/A threadStackSizeInBytes < os::Linux::min_stack_allowed) {
0N/A tty->print_cr("\nThe stack size specified is too small, "
0N/A "Specify at least %dk",
1787N/A os::Linux::min_stack_allowed/ K);
0N/A return JNI_ERR;
0N/A }
0N/A
0N/A // Make the stack size a multiple of the page size so that
0N/A // the yellow/red zones can be guarded.
0N/A JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
0N/A vm_page_size()));
0N/A
0N/A Linux::capture_initial_stack(JavaThread::stack_size_at_create());
0N/A
0N/A Linux::libpthread_init();
0N/A if (PrintMiscellaneous && (Verbose || WizardMode)) {
0N/A tty->print_cr("[HotSpot is running with %s, %s(%s)]\n",
0N/A Linux::glibc_version(), Linux::libpthread_version(),
0N/A Linux::is_floating_stack() ? "floating stack" : "fixed stack");
0N/A }
0N/A
141N/A if (UseNUMA) {
462N/A if (!Linux::libnuma_init()) {
462N/A UseNUMA = false;
462N/A } else {
462N/A if ((Linux::numa_max_node() < 1)) {
462N/A // There's only one node(they start from 0), disable NUMA.
462N/A UseNUMA = false;
462N/A }
462N/A }
2389N/A // With SHM large pages we cannot uncommit a page, so there's not way
2389N/A // we can make the adaptive lgrp chunk resizing work. If the user specified
2389N/A // both UseNUMA and UseLargePages (or UseSHM) on the command line - warn and
2389N/A // disable adaptive resizing.
2389N/A if (UseNUMA && UseLargePages && UseSHM) {
2389N/A if (!FLAG_IS_DEFAULT(UseNUMA)) {
2389N/A if (FLAG_IS_DEFAULT(UseLargePages) && FLAG_IS_DEFAULT(UseSHM)) {
2389N/A UseLargePages = false;
2389N/A } else {
2389N/A warning("UseNUMA is not fully compatible with SHM large pages, disabling adaptive resizing");
2389N/A UseAdaptiveSizePolicy = false;
2389N/A UseAdaptiveNUMAChunkSizing = false;
2389N/A }
2389N/A } else {
2389N/A UseNUMA = false;
2389N/A }
2389N/A }
462N/A if (!UseNUMA && ForceNUMA) {
462N/A UseNUMA = true;
462N/A }
141N/A }
141N/A
0N/A if (MaxFDLimit) {
0N/A // set the number of file descriptors to max. print out error
0N/A // if getrlimit/setrlimit fails but continue regardless.
0N/A struct rlimit nbr_files;
0N/A int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
0N/A if (status != 0) {
0N/A if (PrintMiscellaneous && (Verbose || WizardMode))
0N/A perror("os::init_2 getrlimit failed");
0N/A } else {
0N/A nbr_files.rlim_cur = nbr_files.rlim_max;
0N/A status = setrlimit(RLIMIT_NOFILE, &nbr_files);
0N/A if (status != 0) {
0N/A if (PrintMiscellaneous && (Verbose || WizardMode))
0N/A perror("os::init_2 setrlimit failed");
0N/A }
0N/A }
0N/A }
0N/A
0N/A // Initialize lock used to serialize thread creation (see os::create_thread)
0N/A Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
0N/A
0N/A // at-exit methods are called in the reverse order of their registration.
0N/A // atexit functions are called on return from main or as a result of a
0N/A // call to exit(3C). There can be only 32 of these functions registered
0N/A // and atexit() does not set errno.
0N/A
0N/A if (PerfAllowAtExitRegistration) {
0N/A // only register atexit functions if PerfAllowAtExitRegistration is set.
0N/A // atexit functions can be delayed until process exit time, which
0N/A // can be problematic for embedded VM situations. Embedded VMs should
0N/A // call DestroyJavaVM() to assure that VM resources are released.
0N/A
0N/A // note: perfMemory_exit_helper atexit function may be removed in
0N/A // the future if the appropriate cleanup code can be added to the
0N/A // VM_Exit VMOperation's doit method.
0N/A if (atexit(perfMemory_exit_helper) != 0) {
0N/A warning("os::init2 atexit(perfMemory_exit_helper) failed");
0N/A }
0N/A }
0N/A
0N/A // initialize thread priority policy
0N/A prio_init();
0N/A
0N/A return JNI_OK;
0N/A}
0N/A
1601N/A// this is called at the end of vm_initialization
2627N/Avoid os::init_3(void)
2627N/A{
2627N/A#ifdef JAVASE_EMBEDDED
2627N/A // Start the MemNotifyThread
2627N/A if (LowMemoryProtection) {
2627N/A MemNotifyThread::start();
2627N/A }
2627N/A return;
2627N/A#endif
2627N/A}
1601N/A
0N/A// Mark the polling page as unreadable
0N/Avoid os::make_polling_page_unreadable(void) {
0N/A if( !guard_memory((char*)_polling_page, Linux::page_size()) )
0N/A fatal("Could not disable polling page");
0N/A};
0N/A
0N/A// Mark the polling page as readable
0N/Avoid os::make_polling_page_readable(void) {
237N/A if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
0N/A fatal("Could not enable polling page");
237N/A }
0N/A};
0N/A
0N/Aint os::active_processor_count() {
0N/A // Linux doesn't yet have a (official) notion of processor sets,
0N/A // so just return the number of online processors.
0N/A int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
0N/A assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
0N/A return online_cpus;
0N/A}
0N/A
2842N/Avoid os::set_native_thread_name(const char *name) {
2842N/A // Not yet implemented.
2842N/A return;
2842N/A}
2842N/A
0N/Abool os::distribute_processes(uint length, uint* distribution) {
0N/A // Not yet implemented.
0N/A return false;
0N/A}
0N/A
0N/Abool os::bind_to_processor(uint processor_id) {
0N/A // Not yet implemented.
0N/A return false;
0N/A}
0N/A
0N/A///
0N/A
4141N/Avoid os::SuspendedThreadTask::internal_do_task() {
4141N/A if (do_suspend(_thread->osthread())) {
4141N/A SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
4141N/A do_task(context);
4141N/A do_resume(_thread->osthread());
4141N/A }
4141N/A}
4141N/A
4141N/Aclass PcFetcher : public os::SuspendedThreadTask {
4141N/Apublic:
4141N/A PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
4141N/A ExtendedPC result();
4141N/Aprotected:
4141N/A void do_task(const os::SuspendedThreadTaskContext& context);
4141N/Aprivate:
4141N/A ExtendedPC _epc;
4141N/A};
4141N/A
4141N/AExtendedPC PcFetcher::result() {
4141N/A guarantee(is_done(), "task is not done yet.");
4141N/A return _epc;
4141N/A}
4141N/A
4141N/Avoid PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
4141N/A Thread* thread = context.thread();
4141N/A OSThread* osthread = thread->osthread();
4141N/A if (osthread->ucontext() != NULL) {
4141N/A _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext());
4141N/A } else {
4141N/A // NULL context is unexpected, double-check this is the VMThread
4141N/A guarantee(thread->is_VM_thread(), "can only be called for VMThread");
4141N/A }
4141N/A}
4141N/A
0N/A// Suspends the target using the signal mechanism and then grabs the PC before
0N/A// resuming the target. Used by the flat-profiler only
0N/AExtendedPC os::get_thread_pc(Thread* thread) {
0N/A // Make sure that it is called by the watcher for the VMThread
0N/A assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
0N/A assert(thread->is_VM_thread(), "Can only be called for VMThread");
0N/A
4141N/A PcFetcher fetcher(thread);
4141N/A fetcher.run();
4141N/A return fetcher.result();
0N/A}
0N/A
0N/Aint os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
0N/A{
0N/A if (is_NPTL()) {
0N/A return pthread_cond_timedwait(_cond, _mutex, _abstime);
0N/A } else {
0N/A#ifndef IA64
0N/A // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control
0N/A // word back to default 64bit precision if condvar is signaled. Java
0N/A // wants 53bit precision. Save and restore current value.
0N/A int fpu = get_fpu_control_word();
0N/A#endif // IA64
0N/A int status = pthread_cond_timedwait(_cond, _mutex, _abstime);
0N/A#ifndef IA64
0N/A set_fpu_control_word(fpu);
0N/A#endif // IA64
0N/A return status;
0N/A }
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// debug support
0N/A
0N/Astatic address same_page(address x, address y) {
0N/A int page_bits = -os::vm_page_size();
0N/A if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
0N/A return x;
0N/A else if (x > y)
0N/A return (address)(intptr_t(y) | ~page_bits) + 1;
0N/A else
0N/A return (address)(intptr_t(y) & page_bits);
0N/A}
0N/A
1601N/Abool os::find(address addr, outputStream* st) {
0N/A Dl_info dlinfo;
0N/A memset(&dlinfo, 0, sizeof(dlinfo));
0N/A if (dladdr(addr, &dlinfo)) {
1601N/A st->print(PTR_FORMAT ": ", addr);
0N/A if (dlinfo.dli_sname != NULL) {
1601N/A st->print("%s+%#x", dlinfo.dli_sname,
0N/A addr - (intptr_t)dlinfo.dli_saddr);
0N/A } else if (dlinfo.dli_fname) {
1601N/A st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
0N/A } else {
1601N/A st->print("<absolute address>");
0N/A }
0N/A if (dlinfo.dli_fname) {
1601N/A st->print(" in %s", dlinfo.dli_fname);
0N/A }
0N/A if (dlinfo.dli_fbase) {
1601N/A st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
0N/A }
1601N/A st->cr();
0N/A
0N/A if (Verbose) {
0N/A // decode some bytes around the PC
0N/A address begin = same_page(addr-40, addr);
0N/A address end = same_page(addr+40, addr);
0N/A address lowest = (address) dlinfo.dli_sname;
0N/A if (!lowest) lowest = (address) dlinfo.dli_fbase;
0N/A if (begin < lowest) begin = lowest;
0N/A Dl_info dlinfo2;
0N/A if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
0N/A && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
0N/A end = (address) dlinfo2.dli_saddr;
1601N/A Disassembler::decode(begin, end, st);
0N/A }
0N/A return true;
0N/A }
0N/A return false;
0N/A}
0N/A
0N/A////////////////////////////////////////////////////////////////////////////////
0N/A// misc
0N/A
0N/A// This does not do anything on Linux. This is basically a hook for being
0N/A// able to use structured exception handling (thread-local exception filters)
0N/A// on, e.g., Win32.
0N/Avoid
0N/Aos::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
0N/A JavaCallArguments* args, Thread* thread) {
0N/A f(value, method, args, thread);
0N/A}
0N/A
0N/Avoid os::print_statistics() {
0N/A}
0N/A
0N/Aint os::message_box(const char* title, const char* message) {
0N/A int i;
0N/A fdStream err(defaultStream::error_fd());
0N/A for (i = 0; i < 78; i++) err.print_raw("=");
0N/A err.cr();
0N/A err.print_raw_cr(title);
0N/A for (i = 0; i < 78; i++) err.print_raw("-");
0N/A err.cr();
0N/A err.print_raw_cr(message);
0N/A for (i = 0; i < 78; i++) err.print_raw("=");
0N/A err.cr();
0N/A
0N/A char buf[16];
0N/A // Prevent process from exiting upon "read error" without consuming all CPU
0N/A while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
0N/A
0N/A return buf[0] == 'y' || buf[0] == 'Y';
0N/A}
0N/A
0N/Aint os::stat(const char *path, struct stat *sbuf) {
0N/A char pathbuf[MAX_PATH];
0N/A if (strlen(path) > MAX_PATH - 1) {
0N/A errno = ENAMETOOLONG;
0N/A return -1;
0N/A }
1887N/A os::native_path(strcpy(pathbuf, path));
0N/A return ::stat(pathbuf, sbuf);
0N/A}
0N/A
0N/Abool os::check_heap(bool force) {
0N/A return true;
0N/A}
0N/A
0N/Aint local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
0N/A return ::vsnprintf(buf, count, format, args);
0N/A}
0N/A
0N/A// Is a (classpath) directory empty?
0N/Abool os::dir_is_empty(const char* path) {
0N/A DIR *dir = NULL;
0N/A struct dirent *ptr;
0N/A
0N/A dir = opendir(path);
0N/A if (dir == NULL) return true;
0N/A
0N/A /* Scan the directory */
0N/A bool result = true;
0N/A char buf[sizeof(struct dirent) + MAX_PATH];
0N/A while (result && (ptr = ::readdir(dir)) != NULL) {
0N/A if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
0N/A result = false;
0N/A }
0N/A }
0N/A closedir(dir);
0N/A return result;
0N/A}
0N/A
1887N/A// This code originates from JDK's sysOpen and open64_w
1887N/A// from src/solaris/hpi/src/system_md.c
1887N/A
1887N/A#ifndef O_DELETE
1887N/A#define O_DELETE 0x10000
1887N/A#endif
1887N/A
1887N/A// Open a file. Unlink the file immediately after open returns
1887N/A// if the specified oflag has the O_DELETE flag set.
1887N/A// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
1887N/A
1887N/Aint os::open(const char *path, int oflag, int mode) {
1887N/A
1887N/A if (strlen(path) > MAX_PATH - 1) {
1887N/A errno = ENAMETOOLONG;
1887N/A return -1;
1887N/A }
1887N/A int fd;
1887N/A int o_delete = (oflag & O_DELETE);
1887N/A oflag = oflag & ~O_DELETE;
1887N/A
1887N/A fd = ::open64(path, oflag, mode);
1887N/A if (fd == -1) return -1;
1887N/A
1887N/A //If the open succeeded, the file might still be a directory
1887N/A {
1887N/A struct stat64 buf64;
1887N/A int ret = ::fstat64(fd, &buf64);
1887N/A int st_mode = buf64.st_mode;
1887N/A
1887N/A if (ret != -1) {
1887N/A if ((st_mode & S_IFMT) == S_IFDIR) {
1887N/A errno = EISDIR;
1887N/A ::close(fd);
1887N/A return -1;
1887N/A }
1887N/A } else {
1887N/A ::close(fd);
1887N/A return -1;
1887N/A }
1887N/A }
1887N/A
1887N/A /*
1887N/A * All file descriptors that are opened in the JVM and not
1887N/A * specifically destined for a subprocess should have the
1887N/A * close-on-exec flag set. If we don't set it, then careless 3rd
1887N/A * party native code might fork and exec without closing all
1887N/A * appropriate file descriptors (e.g. as we do in closeDescriptors in
1887N/A * UNIXProcess.c), and this in turn might:
1887N/A *
1887N/A * - cause end-of-file to fail to be detected on some file
1887N/A * descriptors, resulting in mysterious hangs, or
1887N/A *
1887N/A * - might cause an fopen in the subprocess to fail on a system
1887N/A * suffering from bug 1085341.
1887N/A *
1887N/A * (Yes, the default setting of the close-on-exec flag is a Unix
1887N/A * design flaw)
1887N/A *
1887N/A * See:
1887N/A * 1085341: 32-bit stdio routines should support file descriptors >255
1887N/A * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
1887N/A * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
1887N/A */
1887N/A#ifdef FD_CLOEXEC
1887N/A {
1887N/A int flags = ::fcntl(fd, F_GETFD);
1887N/A if (flags != -1)
1887N/A ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
1887N/A }
1887N/A#endif
1887N/A
1887N/A if (o_delete != 0) {
1887N/A ::unlink(path);
1887N/A }
1887N/A return fd;
1887N/A}
1887N/A
1887N/A
0N/A// create binary file, rewriting existing file if required
0N/Aint os::create_binary_file(const char* path, bool rewrite_existing) {
0N/A int oflags = O_WRONLY | O_CREAT;
0N/A if (!rewrite_existing) {
0N/A oflags |= O_EXCL;
0N/A }
0N/A return ::open64(path, oflags, S_IREAD | S_IWRITE);
0N/A}
0N/A
0N/A// return current position of file pointer
0N/Ajlong os::current_file_offset(int fd) {
0N/A return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
0N/A}
0N/A
0N/A// move file pointer to the specified offset
0N/Ajlong os::seek_to_file_offset(int fd, jlong offset) {
0N/A return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
0N/A}
0N/A
1887N/A// This code originates from JDK's sysAvailable
1887N/A// from src/solaris/hpi/src/native_threads/src/sys_api_td.c
1887N/A
1887N/Aint os::available(int fd, jlong *bytes) {
1887N/A jlong cur, end;
1887N/A int mode;
1887N/A struct stat64 buf64;
1887N/A
1887N/A if (::fstat64(fd, &buf64) >= 0) {
1887N/A mode = buf64.st_mode;
1887N/A if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
1887N/A /*
1887N/A * XXX: is the following call interruptible? If so, this might
1887N/A * need to go through the INTERRUPT_IO() wrapper as for other
1887N/A * blocking, interruptible calls in this file.
1887N/A */
1887N/A int n;
1887N/A if (::ioctl(fd, FIONREAD, &n) >= 0) {
1887N/A *bytes = n;
1887N/A return 1;
1887N/A }
1887N/A }
1887N/A }
1887N/A if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
1887N/A return 0;
1887N/A } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
1887N/A return 0;
1887N/A } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
1887N/A return 0;
1887N/A }
1887N/A *bytes = end - cur;
1887N/A return 1;
1887N/A}
1887N/A
1940N/Aint os::socket_available(int fd, jint *pbytes) {
1940N/A // Linux doc says EINTR not returned, unlike Solaris
1940N/A int ret = ::ioctl(fd, FIONREAD, pbytes);
1940N/A
1940N/A //%% note ioctl can return 0 when successful, JVM_SocketAvailable
1940N/A // is expected to return 0 on failure and 1 on success to the jdk.
1940N/A return (ret < 0) ? 0 : 1;
1940N/A}
1940N/A
0N/A// Map a block of memory.
3863N/Achar* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
0N/A char *addr, size_t bytes, bool read_only,
0N/A bool allow_exec) {
0N/A int prot;
3328N/A int flags = MAP_PRIVATE;
0N/A
0N/A if (read_only) {
0N/A prot = PROT_READ;
0N/A } else {
0N/A prot = PROT_READ | PROT_WRITE;
0N/A }
0N/A
0N/A if (allow_exec) {
0N/A prot |= PROT_EXEC;
0N/A }
0N/A
0N/A if (addr != NULL) {
0N/A flags |= MAP_FIXED;
0N/A }
0N/A
0N/A char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
0N/A fd, file_offset);
0N/A if (mapped_address == MAP_FAILED) {
0N/A return NULL;
0N/A }
0N/A return mapped_address;
0N/A}
0N/A
0N/A
0N/A// Remap a block of memory.
3863N/Achar* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
0N/A char *addr, size_t bytes, bool read_only,
0N/A bool allow_exec) {
0N/A // same as map_memory() on this OS
0N/A return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
0N/A allow_exec);
0N/A}
0N/A
0N/A
0N/A// Unmap a block of memory.
3863N/Abool os::pd_unmap_memory(char* addr, size_t bytes) {
0N/A return munmap(addr, bytes) == 0;
0N/A}
0N/A
0N/Astatic jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
0N/A
0N/Astatic clockid_t thread_cpu_clockid(Thread* thread) {
0N/A pthread_t tid = thread->osthread()->pthread_id();
0N/A clockid_t clockid;
0N/A
0N/A // Get thread clockid
0N/A int rc = os::Linux::pthread_getcpuclockid(tid, &clockid);
0N/A assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
0N/A return clockid;
0N/A}
0N/A
0N/A// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
0N/A// are used by JVM M&M and JVMTI to get user+sys or user CPU time
0N/A// of a thread.
0N/A//
0N/A// current_thread_cpu_time() and thread_cpu_time(Thread*) returns
0N/A// the fast estimate available on the platform.
0N/A
0N/Ajlong os::current_thread_cpu_time() {
0N/A if (os::Linux::supports_fast_thread_cpu_time()) {
0N/A return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
0N/A } else {
0N/A // return user + sys since the cost is the same
0N/A return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
0N/A }
0N/A}
0N/A
0N/Ajlong os::thread_cpu_time(Thread* thread) {
0N/A // consistent with what current_thread_cpu_time() returns
0N/A if (os::Linux::supports_fast_thread_cpu_time()) {
0N/A return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
0N/A } else {
0N/A return slow_thread_cpu_time(thread, true /* user + sys */);
0N/A }
0N/A}
0N/A
0N/Ajlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
0N/A if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
0N/A return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
0N/A } else {
0N/A return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
0N/A }
0N/A}
0N/A
0N/Ajlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
0N/A if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
0N/A return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
0N/A } else {
0N/A return slow_thread_cpu_time(thread, user_sys_cpu_time);
0N/A }
0N/A}
0N/A
0N/A//
0N/A// -1 on error.
0N/A//
0N/A
0N/Astatic jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
0N/A static bool proc_pid_cpu_avail = true;
0N/A static bool proc_task_unchecked = true;
0N/A static const char *proc_stat_path = "/proc/%d/stat";
0N/A pid_t tid = thread->osthread()->thread_id();
0N/A int i;
0N/A char *s;
0N/A char stat[2048];
0N/A int statlen;
0N/A char proc_name[64];
0N/A int count;
0N/A long sys_time, user_time;
0N/A char string[64];
1601N/A char cdummy;
0N/A int idummy;
0N/A long ldummy;
0N/A FILE *fp;
0N/A
0N/A // We first try accessing /proc/<pid>/cpu since this is faster to
0N/A // process. If this file is not present (linux kernels 2.5 and above)
0N/A // then we open /proc/<pid>/stat.
0N/A if ( proc_pid_cpu_avail ) {
0N/A sprintf(proc_name, "/proc/%d/cpu", tid);
0N/A fp = fopen(proc_name, "r");
0N/A if ( fp != NULL ) {
0N/A count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time);
0N/A fclose(fp);
0N/A if ( count != 3 ) return -1;
0N/A
0N/A if (user_sys_cpu_time) {
0N/A return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
0N/A } else {
0N/A return (jlong)user_time * (1000000000 / clock_tics_per_sec);
0N/A }
0N/A }
0N/A else proc_pid_cpu_avail = false;
0N/A }
0N/A
0N/A // The /proc/<tid>/stat aggregates per-process usage on
0N/A // new Linux kernels 2.6+ where NPTL is supported.
0N/A // The /proc/self/task/<tid>/stat still has the per-thread usage.
0N/A // See bug 6328462.
0N/A // There can be no directory /proc/self/task on kernels 2.4 with NPTL
0N/A // and possibly in some other cases, so we check its availability.
0N/A if (proc_task_unchecked && os::Linux::is_NPTL()) {
0N/A // This is executed only once
0N/A proc_task_unchecked = false;
0N/A fp = fopen("/proc/self/task", "r");
0N/A if (fp != NULL) {
0N/A proc_stat_path = "/proc/self/task/%d/stat";
0N/A fclose(fp);
0N/A }
0N/A }
0N/A
0N/A sprintf(proc_name, proc_stat_path, tid);
0N/A fp = fopen(proc_name, "r");
0N/A if ( fp == NULL ) return -1;
0N/A statlen = fread(stat, 1, 2047, fp);
0N/A stat[statlen] = '\0';
0N/A fclose(fp);
0N/A
0N/A // Skip pid and the command string. Note that we could be dealing with
0N/A // weird command names, e.g. user could decide to rename java launcher
0N/A // to "java 1.4.2 :)", then the stat file would look like
0N/A // 1234 (java 1.4.2 :)) R ... ...
0N/A // We don't really need to know the command string, just find the last
0N/A // occurrence of ")" and then start parsing from there. See bug 4726580.
0N/A s = strrchr(stat, ')');
0N/A i = 0;
0N/A if (s == NULL ) return -1;
0N/A
0N/A // Skip blank chars
0N/A do s++; while (isspace(*s));
0N/A
1601N/A count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
1601N/A &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
0N/A &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
0N/A &user_time, &sys_time);
1601N/A if ( count != 13 ) return -1;
0N/A if (user_sys_cpu_time) {
0N/A return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
0N/A } else {
0N/A return (jlong)user_time * (1000000000 / clock_tics_per_sec);
0N/A }
0N/A}
0N/A
0N/Avoid os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
0N/A info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
0N/A info_ptr->may_skip_backward = false; // elapsed time not wall time
0N/A info_ptr->may_skip_forward = false; // elapsed time not wall time
0N/A info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
0N/A}
0N/A
0N/Avoid os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
0N/A info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
0N/A info_ptr->may_skip_backward = false; // elapsed time not wall time
0N/A info_ptr->may_skip_forward = false; // elapsed time not wall time
0N/A info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
0N/A}
0N/A
0N/Abool os::is_thread_cpu_time_supported() {
0N/A return true;
0N/A}
0N/A
0N/A// System loadavg support. Returns -1 if load average cannot be obtained.
0N/A// Linux doesn't yet have a (official) notion of processor sets,
0N/A// so just return the system wide load average.
0N/Aint os::loadavg(double loadavg[], int nelem) {
0N/A return ::getloadavg(loadavg, nelem);
0N/A}
0N/A
0N/Avoid os::pause() {
0N/A char filename[MAX_PATH];
0N/A if (PauseAtStartupFile && PauseAtStartupFile[0]) {
0N/A jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
0N/A } else {
0N/A jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
0N/A }
0N/A
0N/A int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
0N/A if (fd != -1) {
0N/A struct stat buf;
1887N/A ::close(fd);
0N/A while (::stat(filename, &buf) == 0) {
0N/A (void)::poll(NULL, 0, 100);
0N/A }
0N/A } else {
0N/A jio_fprintf(stderr,
0N/A "Could not open pause file '%s', continuing immediately.\n", filename);
0N/A }
0N/A}
0N/A
0N/A
0N/A// Refer to the comments in os_solaris.cpp park-unpark.
0N/A//
0N/A// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
0N/A// hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
0N/A// For specifics regarding the bug see GLIBC BUGID 261237 :
0N/A// http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
0N/A// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
0N/A// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
0N/A// is used. (The simple C test-case provided in the GLIBC bug report manifests the
0N/A// hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
0N/A// and monitorenter when we're using 1-0 locking. All those operations may result in
0N/A// calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
0N/A// of libpthread avoids the problem, but isn't practical.
0N/A//
0N/A// Possible remedies:
0N/A//
0N/A// 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
0N/A// This is palliative and probabilistic, however. If the thread is preempted
0N/A// between the call to compute_abstime() and pthread_cond_timedwait(), more
0N/A// than the minimum period may have passed, and the abstime may be stale (in the
0N/A// past) resultin in a hang. Using this technique reduces the odds of a hang
0N/A// but the JVM is still vulnerable, particularly on heavily loaded systems.
0N/A//
0N/A// 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
0N/A// of the usual flag-condvar-mutex idiom. The write side of the pipe is set
0N/A// NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
0N/A// reduces to poll()+read(). This works well, but consumes 2 FDs per extant
0N/A// thread.
0N/A//
0N/A// 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
0N/A// that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
0N/A// a timeout request to the chron thread and then blocking via pthread_cond_wait().
0N/A// This also works well. In fact it avoids kernel-level scalability impediments
0N/A// on certain platforms that don't handle lots of active pthread_cond_timedwait()
0N/A// timers in a graceful fashion.
0N/A//
0N/A// 4. When the abstime value is in the past it appears that control returns
0N/A// correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
0N/A// Subsequent timedwait/wait calls may hang indefinitely. Given that, we
0N/A// can avoid the problem by reinitializing the condvar -- by cond_destroy()
0N/A// followed by cond_init() -- after all calls to pthread_cond_timedwait().
0N/A// It may be possible to avoid reinitialization by checking the return
0N/A// value from pthread_cond_timedwait(). In addition to reinitializing the
0N/A// condvar we must establish the invariant that cond_signal() is only called
0N/A// within critical sections protected by the adjunct mutex. This prevents
0N/A// cond_signal() from "seeing" a condvar that's in the midst of being
0N/A// reinitialized or that is corrupt. Sadly, this invariant obviates the
0N/A// desirable signal-after-unlock optimization that avoids futile context switching.
0N/A//
0N/A// I'm also concerned that some versions of NTPL might allocate an auxilliary
0N/A// structure when a condvar is used or initialized. cond_destroy() would
0N/A// release the helper structure. Our reinitialize-after-timedwait fix
0N/A// put excessive stress on malloc/free and locks protecting the c-heap.
0N/A//
0N/A// We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
0N/A// It may be possible to refine (4) by checking the kernel and NTPL verisons
0N/A// and only enabling the work-around for vulnerable environments.
0N/A
0N/A// utility to compute the abstime argument to timedwait:
0N/A// millis is the relative timeout time
0N/A// abstime will be the absolute timeout time
0N/A// TODO: replace compute_abstime() with unpackTime()
0N/A
0N/Astatic struct timespec* compute_abstime(timespec* abstime, jlong millis) {
0N/A if (millis < 0) millis = 0;
0N/A struct timeval now;
0N/A int status = gettimeofday(&now, NULL);
0N/A assert(status == 0, "gettimeofday");
0N/A jlong seconds = millis / 1000;
0N/A millis %= 1000;
0N/A if (seconds > 50000000) { // see man cond_timedwait(3T)
0N/A seconds = 50000000;
0N/A }
0N/A abstime->tv_sec = now.tv_sec + seconds;
0N/A long usec = now.tv_usec + millis * 1000;
0N/A if (usec >= 1000000) {
0N/A abstime->tv_sec += 1;
0N/A usec -= 1000000;
0N/A }
0N/A abstime->tv_nsec = usec * 1000;
0N/A return abstime;
0N/A}
0N/A
0N/A
0N/A// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
0N/A// Conceptually TryPark() should be equivalent to park(0).
0N/A
0N/Aint os::PlatformEvent::TryPark() {
0N/A for (;;) {
0N/A const int v = _Event ;
0N/A guarantee ((v == 0) || (v == 1), "invariant") ;
0N/A if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;
0N/A }
0N/A}
0N/A
0N/Avoid os::PlatformEvent::park() { // AKA "down()"
0N/A // Invariant: Only the thread associated with the Event/PlatformEvent
0N/A // may call park().
0N/A // TODO: assert that _Assoc != NULL or _Assoc == Self
0N/A int v ;
0N/A for (;;) {
0N/A v = _Event ;
0N/A if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
0N/A }
0N/A guarantee (v >= 0, "invariant") ;
0N/A if (v == 0) {
0N/A // Do this the hard way by blocking ...
0N/A int status = pthread_mutex_lock(_mutex);
0N/A assert_status(status == 0, status, "mutex_lock");
0N/A guarantee (_nParked == 0, "invariant") ;
0N/A ++ _nParked ;
0N/A while (_Event < 0) {
0N/A status = pthread_cond_wait(_cond, _mutex);
0N/A // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
0N/A // Treat this the same as if the wait was interrupted
0N/A if (status == ETIME) { status = EINTR; }
0N/A assert_status(status == 0 || status == EINTR, status, "cond_wait");
0N/A }
0N/A -- _nParked ;
0N/A
0N/A _Event = 0 ;
0N/A status = pthread_mutex_unlock(_mutex);
0N/A assert_status(status == 0, status, "mutex_unlock");
4278N/A // Paranoia to ensure our locked and lock-free paths interact
4278N/A // correctly with each other.
4278N/A OrderAccess::fence();
0N/A }
0N/A guarantee (_Event >= 0, "invariant") ;
0N/A}
0N/A
0N/Aint os::PlatformEvent::park(jlong millis) {
0N/A guarantee (_nParked == 0, "invariant") ;
0N/A
0N/A int v ;
0N/A for (;;) {
0N/A v = _Event ;
0N/A if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
0N/A }
0N/A guarantee (v >= 0, "invariant") ;
0N/A if (v != 0) return OS_OK ;
0N/A
0N/A // We do this the hard way, by blocking the thread.
0N/A // Consider enforcing a minimum timeout value.
0N/A struct timespec abst;
0N/A compute_abstime(&abst, millis);
0N/A
0N/A int ret = OS_TIMEOUT;
0N/A int status = pthread_mutex_lock(_mutex);
0N/A assert_status(status == 0, status, "mutex_lock");
0N/A guarantee (_nParked == 0, "invariant") ;
0N/A ++_nParked ;
0N/A
0N/A // Object.wait(timo) will return because of
0N/A // (a) notification
0N/A // (b) timeout
0N/A // (c) thread.interrupt
0N/A //
0N/A // Thread.interrupt and object.notify{All} both call Event::set.
0N/A // That is, we treat thread.interrupt as a special case of notification.
0N/A // The underlying Solaris implementation, cond_timedwait, admits
0N/A // spurious/premature wakeups, but the JLS/JVM spec prevents the
0N/A // JVM from making those visible to Java code. As such, we must
0N/A // filter out spurious wakeups. We assume all ETIME returns are valid.
0N/A //
0N/A // TODO: properly differentiate simultaneous notify+interrupt.
0N/A // In that case, we should propagate the notify to another waiter.
0N/A
0N/A while (_Event < 0) {
0N/A status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst);
0N/A if (status != 0 && WorkAroundNPTLTimedWaitHang) {
0N/A pthread_cond_destroy (_cond);
0N/A pthread_cond_init (_cond, NULL) ;
0N/A }
0N/A assert_status(status == 0 || status == EINTR ||
0N/A status == ETIME || status == ETIMEDOUT,
0N/A status, "cond_timedwait");
0N/A if (!FilterSpuriousWakeups) break ; // previous semantics
0N/A if (status == ETIME || status == ETIMEDOUT) break ;
0N/A // We consume and ignore EINTR and spurious wakeups.
0N/A }
0N/A --_nParked ;
0N/A if (_Event >= 0) {
0N/A ret = OS_OK;
0N/A }
0N/A _Event = 0 ;
0N/A status = pthread_mutex_unlock(_mutex);
0N/A assert_status(status == 0, status, "mutex_unlock");
0N/A assert (_nParked == 0, "invariant") ;
4278N/A // Paranoia to ensure our locked and lock-free paths interact
4278N/A // correctly with each other.
4278N/A OrderAccess::fence();
0N/A return ret;
0N/A}
0N/A
0N/Avoid os::PlatformEvent::unpark() {
4278N/A // Transitions for _Event:
4278N/A // 0 :=> 1
4278N/A // 1 :=> 1
4278N/A // -1 :=> either 0 or 1; must signal target thread
4278N/A // That is, we can safely transition _Event from -1 to either
4278N/A // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
4278N/A // unpark() calls.
4278N/A // See also: "Semaphores in Plan 9" by Mullender & Cox
4278N/A //
4278N/A // Note: Forcing a transition from "-1" to "1" on an unpark() means
4278N/A // that it will take two back-to-back park() calls for the owning
4278N/A // thread to block. This has the benefit of forcing a spurious return
4278N/A // from the first park() call after an unpark() call which will help
4278N/A // shake out uses of park() and unpark() without condition variables.
4278N/A
4278N/A if (Atomic::xchg(1, &_Event) >= 0) return;
4278N/A
4278N/A // Wait for the thread associated with the event to vacate
4278N/A int status = pthread_mutex_lock(_mutex);
4278N/A assert_status(status == 0, status, "mutex_lock");
4278N/A int AnyWaiters = _nParked;
4278N/A assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
4278N/A if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
4278N/A AnyWaiters = 0;
4278N/A pthread_cond_signal(_cond);
4278N/A }
4278N/A status = pthread_mutex_unlock(_mutex);
4278N/A assert_status(status == 0, status, "mutex_unlock");
4278N/A if (AnyWaiters != 0) {
4278N/A status = pthread_cond_signal(_cond);
4278N/A assert_status(status == 0, status, "cond_signal");
0N/A }
0N/A
0N/A // Note that we signal() _after dropping the lock for "immortal" Events.
0N/A // This is safe and avoids a common class of futile wakeups. In rare
0N/A // circumstances this can cause a thread to return prematurely from
0N/A // cond_{timed}wait() but the spurious wakeup is benign and the victim will
0N/A // simply re-test the condition and re-park itself.
0N/A}
0N/A
0N/A
0N/A// JSR166
0N/A// -------------------------------------------------------
0N/A
0N/A/*
0N/A * The solaris and linux implementations of park/unpark are fairly
0N/A * conservative for now, but can be improved. They currently use a
0N/A * mutex/condvar pair, plus a a count.
0N/A * Park decrements count if > 0, else does a condvar wait. Unpark
0N/A * sets count to 1 and signals condvar. Only one thread ever waits
0N/A * on the condvar. Contention seen when trying to park implies that someone
0N/A * is unparking you, so don't wait. And spurious returns are fine, so there
0N/A * is no need to track notifications.
0N/A */
0N/A
0N/A#define MAX_SECS 100000000
0N/A/*
0N/A * This code is common to linux and solaris and will be moved to a
0N/A * common place in dolphin.
0N/A *
0N/A * The passed in time value is either a relative time in nanoseconds
0N/A * or an absolute time in milliseconds. Either way it has to be unpacked
0N/A * into suitable seconds and nanoseconds components and stored in the
0N/A * given timespec structure.
0N/A * Given time is a 64-bit value and the time_t used in the timespec is only
0N/A * a signed-32-bit value (except on 64-bit Linux) we have to watch for
0N/A * overflow if times way in the future are given. Further on Solaris versions
0N/A * prior to 10 there is a restriction (see cond_timedwait) that the specified
0N/A * number of seconds, in abstime, is less than current_time + 100,000,000.
0N/A * As it will be 28 years before "now + 100000000" will overflow we can
0N/A * ignore overflow and just impose a hard-limit on seconds using the value
0N/A * of "now + 100,000,000". This places a limit on the timeout of about 3.17
0N/A * years from "now".
0N/A */
0N/A
0N/Astatic void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
0N/A assert (time > 0, "convertTime");
0N/A
0N/A struct timeval now;
0N/A int status = gettimeofday(&now, NULL);
0N/A assert(status == 0, "gettimeofday");
0N/A
0N/A time_t max_secs = now.tv_sec + MAX_SECS;
0N/A
0N/A if (isAbsolute) {
0N/A jlong secs = time / 1000;
0N/A if (secs > max_secs) {
0N/A absTime->tv_sec = max_secs;
0N/A }
0N/A else {
0N/A absTime->tv_sec = secs;
0N/A }
0N/A absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
0N/A }
0N/A else {
0N/A jlong secs = time / NANOSECS_PER_SEC;
0N/A if (secs >= MAX_SECS) {
0N/A absTime->tv_sec = max_secs;
0N/A absTime->tv_nsec = 0;
0N/A }
0N/A else {
0N/A absTime->tv_sec = now.tv_sec + secs;
0N/A absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
0N/A if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
0N/A absTime->tv_nsec -= NANOSECS_PER_SEC;
0N/A ++absTime->tv_sec; // note: this must be <= max_secs
0N/A }
0N/A }
0N/A }
0N/A assert(absTime->tv_sec >= 0, "tv_sec < 0");
0N/A assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
0N/A assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
0N/A assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
0N/A}
0N/A
0N/Avoid Parker::park(bool isAbsolute, jlong time) {
4278N/A // Ideally we'd do something useful while spinning, such
4278N/A // as calling unpackTime().
4278N/A
0N/A // Optional fast-path check:
0N/A // Return immediately if a permit is available.
4278N/A // We depend on Atomic::xchg() having full barrier semantics
4278N/A // since we are doing a lock-free update to _counter.
4278N/A if (Atomic::xchg(0, &_counter) > 0) return;
0N/A
0N/A Thread* thread = Thread::current();
0N/A assert(thread->is_Java_thread(), "Must be JavaThread");
0N/A JavaThread *jt = (JavaThread *)thread;
0N/A
0N/A // Optional optimization -- avoid state transitions if there's an interrupt pending.
0N/A // Check interrupt before trying to wait
0N/A if (Thread::is_interrupted(thread, false)) {
0N/A return;
0N/A }
0N/A
0N/A // Next, demultiplex/decode time arguments
0N/A timespec absTime;
1785N/A if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
0N/A return;
0N/A }
0N/A if (time > 0) {
0N/A unpackTime(&absTime, isAbsolute, time);
0N/A }
0N/A
0N/A
0N/A // Enter safepoint region
0N/A // Beware of deadlocks such as 6317397.
0N/A // The per-thread Parker:: mutex is a classic leaf-lock.
0N/A // In particular a thread must never block on the Threads_lock while
0N/A // holding the Parker:: mutex. If safepoints are pending both the
0N/A // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
0N/A ThreadBlockInVM tbivm(jt);
0N/A
0N/A // Don't wait if cannot get lock since interference arises from
0N/A // unblocking. Also. check interrupt before trying wait
0N/A if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
0N/A return;
0N/A }
0N/A
0N/A int status ;
0N/A if (_counter > 0) { // no wait needed
0N/A _counter = 0;
0N/A status = pthread_mutex_unlock(_mutex);
0N/A assert (status == 0, "invariant") ;
4278N/A // Paranoia to ensure our locked and lock-free paths interact
4278N/A // correctly with each other and Java-level accesses.
1117N/A OrderAccess::fence();
0N/A return;
0N/A }
0N/A
0N/A#ifdef ASSERT
0N/A // Don't catch signals while blocked; let the running threads have the signals.
0N/A // (This allows a debugger to break into the running thread.)
0N/A sigset_t oldsigs;
0N/A sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals();
0N/A pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
0N/A#endif
0N/A
0N/A OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
0N/A jt->set_suspend_equivalent();
0N/A // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
0N/A
0N/A if (time == 0) {
0N/A status = pthread_cond_wait (_cond, _mutex) ;
0N/A } else {
0N/A status = os::Linux::safe_cond_timedwait (_cond, _mutex, &absTime) ;
0N/A if (status != 0 && WorkAroundNPTLTimedWaitHang) {
0N/A pthread_cond_destroy (_cond) ;
0N/A pthread_cond_init (_cond, NULL);
0N/A }
0N/A }
0N/A assert_status(status == 0 || status == EINTR ||
0N/A status == ETIME || status == ETIMEDOUT,
0N/A status, "cond_timedwait");
0N/A
0N/A#ifdef ASSERT
0N/A pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
0N/A#endif
0N/A
0N/A _counter = 0 ;
0N/A status = pthread_mutex_unlock(_mutex) ;
0N/A assert_status(status == 0, status, "invariant") ;
4278N/A // Paranoia to ensure our locked and lock-free paths interact
4278N/A // correctly with each other and Java-level accesses.
4278N/A OrderAccess::fence();
4278N/A
0N/A // If externally suspended while waiting, re-suspend
0N/A if (jt->handle_special_suspend_equivalent_condition()) {
0N/A jt->java_suspend_self();
0N/A }
0N/A}
0N/A
0N/Avoid Parker::unpark() {
0N/A int s, status ;
0N/A status = pthread_mutex_lock(_mutex);
0N/A assert (status == 0, "invariant") ;
0N/A s = _counter;
0N/A _counter = 1;
0N/A if (s < 1) {
0N/A if (WorkAroundNPTLTimedWaitHang) {
0N/A status = pthread_cond_signal (_cond) ;
0N/A assert (status == 0, "invariant") ;
0N/A status = pthread_mutex_unlock(_mutex);
0N/A assert (status == 0, "invariant") ;
0N/A } else {
0N/A status = pthread_mutex_unlock(_mutex);
0N/A assert (status == 0, "invariant") ;
0N/A status = pthread_cond_signal (_cond) ;
0N/A assert (status == 0, "invariant") ;
0N/A }
0N/A } else {
0N/A pthread_mutex_unlock(_mutex);
0N/A assert (status == 0, "invariant") ;
0N/A }
0N/A}
0N/A
0N/A
0N/Aextern char** environ;
0N/A
0N/A#ifndef __NR_fork
0N/A#define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57)
0N/A#endif
0N/A
0N/A#ifndef __NR_execve
0N/A#define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59)
0N/A#endif
0N/A
0N/A// Run the specified command in a separate process. Return its exit value,
0N/A// or -1 on failure (e.g. can't fork a new process).
0N/A// Unlike system(), this function can be called from signal handler. It
0N/A// doesn't block SIGINT et al.
0N/Aint os::fork_and_exec(char* cmd) {
199N/A const char * argv[4] = {"sh", "-c", cmd, NULL};
0N/A
0N/A // fork() in LinuxThreads/NPTL is not async-safe. It needs to run
0N/A // pthread_atfork handlers and reset pthread library. All we need is a
0N/A // separate process to execve. Make a direct syscall to fork process.
0N/A // On IA64 there's no fork syscall, we have to use fork() and hope for
0N/A // the best...
0N/A pid_t pid = NOT_IA64(syscall(__NR_fork);)
0N/A IA64_ONLY(fork();)
0N/A
0N/A if (pid < 0) {
0N/A // fork failed
0N/A return -1;
0N/A
0N/A } else if (pid == 0) {
0N/A // child process
0N/A
0N/A // execve() in LinuxThreads will call pthread_kill_other_threads_np()
0N/A // first to kill every thread on the thread list. Because this list is
0N/A // not reset by fork() (see notes above), execve() will instead kill
0N/A // every thread in the parent process. We know this is the only thread
0N/A // in the new process, so make a system call directly.
0N/A // IA64 should use normal execve() from glibc to match the glibc fork()
0N/A // above.
0N/A NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);)
199N/A IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);)
0N/A
0N/A // execve failed
0N/A _exit(-1);
0N/A
0N/A } else {
0N/A // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
0N/A // care about the actual exit code, for now.
0N/A
0N/A int status;
0N/A
0N/A // Wait for the child process to exit. This returns immediately if
0N/A // the child has already exited. */
0N/A while (waitpid(pid, &status, 0) < 0) {
0N/A switch (errno) {
0N/A case ECHILD: return 0;
0N/A case EINTR: break;
0N/A default: return -1;
0N/A }
0N/A }
0N/A
0N/A if (WIFEXITED(status)) {
0N/A // The child exited normally; get its exit code.
0N/A return WEXITSTATUS(status);
0N/A } else if (WIFSIGNALED(status)) {
0N/A // The child exited because of a signal
0N/A // The best value to return is 0x80 + signal number,
0N/A // because that is what all Unix shells do, and because
0N/A // it allows callers to distinguish between process exit and
0N/A // process death by signal.
0N/A return 0x80 + WTERMSIG(status);
0N/A } else {
0N/A // Unknown exit code; pass it through
0N/A return status;
0N/A }
0N/A }
0N/A}
1601N/A
1601N/A// is_headless_jre()
1601N/A//
2928N/A// Test for the existence of xawt/libmawt.so or libawt_xawt.so
1601N/A// in order to report if we are running in a headless jre
1601N/A//
2928N/A// Since JDK8 xawt/libmawt.so was moved into the same directory
2928N/A// as libawt.so, and renamed libawt_xawt.so
2928N/A//
1601N/Abool os::is_headless_jre() {
1601N/A struct stat statbuf;
1601N/A char buf[MAXPATHLEN];
1601N/A char libmawtpath[MAXPATHLEN];
1601N/A const char *xawtstr = "/xawt/libmawt.so";
2928N/A const char *new_xawtstr = "/libawt_xawt.so";
1601N/A char *p;
1601N/A
1601N/A // Get path to libjvm.so
1601N/A os::jvm_path(buf, sizeof(buf));
1601N/A
1601N/A // Get rid of libjvm.so
1601N/A p = strrchr(buf, '/');
1601N/A if (p == NULL) return false;
1601N/A else *p = '\0';
1601N/A
1601N/A // Get rid of client or server
1601N/A p = strrchr(buf, '/');
1601N/A if (p == NULL) return false;
1601N/A else *p = '\0';
1601N/A
1601N/A // check xawt/libmawt.so
1601N/A strcpy(libmawtpath, buf);
1601N/A strcat(libmawtpath, xawtstr);
1601N/A if (::stat(libmawtpath, &statbuf) == 0) return false;
1601N/A
2928N/A // check libawt_xawt.so
1601N/A strcpy(libmawtpath, buf);
2928N/A strcat(libmawtpath, new_xawtstr);
1601N/A if (::stat(libmawtpath, &statbuf) == 0) return false;
1601N/A
1601N/A return true;
1601N/A}
1601N/A
3866N/A// Get the default path to the core file
3866N/A// Returns the length of the string
3866N/Aint os::get_core_path(char* buffer, size_t bufferSize) {
3866N/A const char* p = get_current_directory(buffer, bufferSize);
3866N/A
3866N/A if (p == NULL) {
3866N/A assert(p != NULL, "failed to get current directory");
3866N/A return 0;
3866N/A }
3866N/A
3866N/A return strlen(buffer);
3866N/A}
2627N/A
2627N/A#ifdef JAVASE_EMBEDDED
2627N/A//
2627N/A// A thread to watch the '/dev/mem_notify' device, which will tell us when the OS is running low on memory.
2627N/A//
2627N/AMemNotifyThread* MemNotifyThread::_memnotify_thread = NULL;
2627N/A
2627N/A// ctor
2627N/A//
2627N/AMemNotifyThread::MemNotifyThread(int fd): Thread() {
2627N/A assert(memnotify_thread() == NULL, "we can only allocate one MemNotifyThread");
2627N/A _fd = fd;
2627N/A
2627N/A if (os::create_thread(this, os::os_thread)) {
2627N/A _memnotify_thread = this;
2627N/A os::set_priority(this, NearMaxPriority);
2627N/A os::start_thread(this);
2627N/A }
2627N/A}
2627N/A
2627N/A// Where all the work gets done
2627N/A//
2627N/Avoid MemNotifyThread::run() {
2627N/A assert(this == memnotify_thread(), "expected the singleton MemNotifyThread");
2627N/A
2627N/A // Set up the select arguments
2627N/A fd_set rfds;
2627N/A if (_fd != -1) {
2627N/A FD_ZERO(&rfds);
2627N/A FD_SET(_fd, &rfds);
2627N/A }
2627N/A
2627N/A // Now wait for the mem_notify device to wake up
2627N/A while (1) {
2627N/A // Wait for the mem_notify device to signal us..
2627N/A int rc = select(_fd+1, _fd != -1 ? &rfds : NULL, NULL, NULL, NULL);
2627N/A if (rc == -1) {
2627N/A perror("select!\n");
2627N/A break;
2627N/A } else if (rc) {
2627N/A //ssize_t free_before = os::available_memory();
2627N/A //tty->print ("Notified: Free: %dK \n",os::available_memory()/1024);
2627N/A
2627N/A // The kernel is telling us there is not much memory left...
2627N/A // try to do something about that
2627N/A
2627N/A // If we are not already in a GC, try one.
2627N/A if (!Universe::heap()->is_gc_active()) {
2627N/A Universe::heap()->collect(GCCause::_allocation_failure);
2627N/A
2627N/A //ssize_t free_after = os::available_memory();
2627N/A //tty->print ("Post-Notify: Free: %dK\n",free_after/1024);
2627N/A //tty->print ("GC freed: %dK\n", (free_after - free_before)/1024);
2627N/A }
2627N/A // We might want to do something like the following if we find the GC's are not helping...
2627N/A // Universe::heap()->size_policy()->set_gc_time_limit_exceeded(true);
2627N/A }
2627N/A }
2627N/A}
2627N/A
2627N/A//
2627N/A// See if the /dev/mem_notify device exists, and if so, start a thread to monitor it.
2627N/A//
2627N/Avoid MemNotifyThread::start() {
2627N/A int fd;
2627N/A fd = open ("/dev/mem_notify", O_RDONLY, 0);
2627N/A if (fd < 0) {
2627N/A return;
2627N/A }
2627N/A
2627N/A if (memnotify_thread() == NULL) {
2627N/A new MemNotifyThread(fd);
2627N/A }
2627N/A}
4433N/A
2627N/A#endif // JAVASE_EMBEDDED