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