os_bsd.cpp revision 4820:a837fa3d3f86
10SN/A/*
2157SN/A * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
30SN/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
40SN/A *
50SN/A * This code is free software; you can redistribute it and/or modify it
60SN/A * under the terms of the GNU General Public License version 2 only, as
7157SN/A * published by the Free Software Foundation.
80SN/A *
9157SN/A * This code is distributed in the hope that it will be useful, but WITHOUT
100SN/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
110SN/A * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
120SN/A * version 2 for more details (a copy is included in the LICENSE file that
130SN/A * accompanied this code).
140SN/A *
150SN/A * You should have received a copy of the GNU General Public License version
160SN/A * 2 along with this work; if not, write to the Free Software Foundation,
170SN/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
180SN/A *
190SN/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
200SN/A * or visit www.oracle.com if you need additional information or have any
21157SN/A * questions.
22157SN/A *
23157SN/A */
240SN/A
250SN/A// no precompiled headers
260SN/A#include "classfile/classLoader.hpp"
270SN/A#include "classfile/systemDictionary.hpp"
280SN/A#include "classfile/vmSymbols.hpp"
290SN/A#include "code/icBuffer.hpp"
300SN/A#include "code/vtableStubs.hpp"
310SN/A#include "compiler/compileBroker.hpp"
320SN/A#include "compiler/disassembler.hpp"
330SN/A#include "interpreter/interpreter.hpp"
340SN/A#include "jvm_bsd.h"
350SN/A#include "memory/allocation.inline.hpp"
360SN/A#include "memory/filemap.hpp"
370SN/A#include "mutex_bsd.inline.hpp"
380SN/A#include "oops/oop.inline.hpp"
390SN/A#include "os_share_bsd.hpp"
400SN/A#include "prims/jniFastGetField.hpp"
410SN/A#include "prims/jvm.h"
420SN/A#include "prims/jvm_misc.hpp"
430SN/A#include "runtime/arguments.hpp"
440SN/A#include "runtime/extendedPC.hpp"
450SN/A#include "runtime/globals.hpp"
460SN/A#include "runtime/interfaceSupport.hpp"
470SN/A#include "runtime/java.hpp"
480SN/A#include "runtime/javaCalls.hpp"
490SN/A#include "runtime/mutexLocker.hpp"
500SN/A#include "runtime/objectMonitor.hpp"
510SN/A#include "runtime/osThread.hpp"
520SN/A#include "runtime/perfMemory.hpp"
530SN/A#include "runtime/sharedRuntime.hpp"
540SN/A#include "runtime/statSampler.hpp"
550SN/A#include "runtime/stubRoutines.hpp"
560SN/A#include "runtime/thread.inline.hpp"
570SN/A#include "runtime/threadCritical.hpp"
580SN/A#include "runtime/timer.hpp"
590SN/A#include "services/attachListener.hpp"
600SN/A#include "services/memTracker.hpp"
610SN/A#include "services/runtimeService.hpp"
620SN/A#include "utilities/decoder.hpp"
630SN/A#include "utilities/defaultStream.hpp"
640SN/A#include "utilities/events.hpp"
650SN/A#include "utilities/growableArray.hpp"
660SN/A#include "utilities/vmError.hpp"
670SN/A
680SN/A// put OS-includes here
690SN/A# include <sys/types.h>
700SN/A# include <sys/mman.h>
710SN/A# include <sys/stat.h>
720SN/A# include <sys/select.h>
730SN/A# include <pthread.h>
740SN/A# include <signal.h>
750SN/A# include <errno.h>
760SN/A# include <dlfcn.h>
770SN/A# include <stdio.h>
780SN/A# include <unistd.h>
790SN/A# include <sys/resource.h>
800SN/A# include <pthread.h>
810SN/A# include <sys/stat.h>
820SN/A# include <sys/time.h>
830SN/A# include <sys/times.h>
840SN/A# include <sys/utsname.h>
850SN/A# include <sys/socket.h>
860SN/A# include <sys/wait.h>
870SN/A# include <time.h>
880SN/A# include <pwd.h>
890SN/A# include <poll.h>
900SN/A# include <semaphore.h>
910SN/A# include <fcntl.h>
920SN/A# include <string.h>
930SN/A# include <sys/param.h>
940SN/A# include <sys/sysctl.h>
950SN/A# include <sys/ipc.h>
960SN/A# include <sys/shm.h>
970SN/A#ifndef __APPLE__
980SN/A# include <link.h>
990SN/A#endif
1000SN/A# include <stdint.h>
1010SN/A# include <inttypes.h>
1020SN/A# include <sys/ioctl.h>
1030SN/A
1040SN/A#if defined(__FreeBSD__) || defined(__NetBSD__)
1050SN/A# include <elf.h>
1060SN/A#endif
1070SN/A
1080SN/A#ifdef __APPLE__
1090SN/A# include <mach/mach.h> // semaphore_* API
1100SN/A# include <mach-o/dyld.h>
1110SN/A# include <sys/proc_info.h>
1120SN/A# include <objc/objc-auto.h>
1130SN/A#endif
1140SN/A
1150SN/A#ifndef MAP_ANONYMOUS
1160SN/A#define MAP_ANONYMOUS MAP_ANON
1170SN/A#endif
1180SN/A
1190SN/A#define MAX_PATH    (2 * K)
1200SN/A
1210SN/A// for timer info max values which include all bits
1220SN/A#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
1230SN/A
1240SN/A#define LARGEPAGES_BIT (1 << 6)
1250SN/A////////////////////////////////////////////////////////////////////////////////
1260SN/A// global variables
1270SN/Ajulong os::Bsd::_physical_memory = 0;
1280SN/A
1290SN/A
1300SN/Aint (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
1310SN/Apthread_t os::Bsd::_main_thread;
1320SN/Aint os::Bsd::_page_size = -1;
1330SN/A
1340SN/Astatic jlong initial_time_count=0;
1350SN/A
1360SN/Astatic int clock_tics_per_sec = 100;
1370SN/A
1380SN/A// For diagnostics to print a message once. see run_periodic_checks
1390SN/Astatic sigset_t check_signal_done;
1400SN/Astatic bool check_signals = true;
1410SN/A
1420SN/Astatic pid_t _initial_pid = 0;
1430SN/A
1440SN/A/* Signal number used to suspend/resume a thread */
1450SN/A
1460SN/A/* do not use any signal number less than SIGSEGV, see 4355769 */
1470SN/Astatic int SR_signum = SIGUSR2;
1480SN/Asigset_t SR_sigset;
1490SN/A
1500SN/A
1510SN/A////////////////////////////////////////////////////////////////////////////////
1520SN/A// utility functions
1530SN/A
1540SN/Astatic int SR_initialize();
1550SN/A
1560SN/Ajulong os::available_memory() {
1570SN/A  return Bsd::available_memory();
1580SN/A}
1590SN/A
1600SN/Ajulong os::Bsd::available_memory() {
1610SN/A  // XXXBSD: this is just a stopgap implementation
1620SN/A  return physical_memory() >> 2;
1630SN/A}
1640SN/A
1650SN/Ajulong os::physical_memory() {
1660SN/A  return Bsd::physical_memory();
1670SN/A}
1680SN/A
1690SN/A////////////////////////////////////////////////////////////////////////////////
1700SN/A// environment support
1710SN/A
1720SN/Abool os::getenv(const char* name, char* buf, int len) {
1730SN/A  const char* val = ::getenv(name);
1740SN/A  if (val != NULL && strlen(val) < (size_t)len) {
1750SN/A    strcpy(buf, val);
1760SN/A    return true;
1770SN/A  }
1780SN/A  if (len > 0) buf[0] = 0;  // return a null string
1790SN/A  return false;
1800SN/A}
1810SN/A
1820SN/A
1830SN/A// Return true if user is running as root.
1840SN/A
1850SN/Abool os::have_special_privileges() {
1860SN/A  static bool init = false;
1870SN/A  static bool privileges = false;
1880SN/A  if (!init) {
1890SN/A    privileges = (getuid() != geteuid()) || (getgid() != getegid());
1900SN/A    init = true;
1910SN/A  }
1920SN/A  return privileges;
1930SN/A}
1940SN/A
1950SN/A
1960SN/A
1970SN/A// Cpu architecture string
1980SN/A#if   defined(ZERO)
1990SN/Astatic char cpu_arch[] = ZERO_LIBARCH;
2000SN/A#elif defined(IA64)
2010SN/Astatic char cpu_arch[] = "ia64";
2020SN/A#elif defined(IA32)
2030SN/Astatic char cpu_arch[] = "i386";
2040SN/A#elif defined(AMD64)
2050SN/Astatic char cpu_arch[] = "amd64";
2060SN/A#elif defined(ARM)
2070SN/Astatic char cpu_arch[] = "arm";
2080SN/A#elif defined(PPC)
2090SN/Astatic char cpu_arch[] = "ppc";
2100SN/A#elif defined(SPARC)
2110SN/A#  ifdef _LP64
2120SN/Astatic char cpu_arch[] = "sparcv9";
2130SN/A#  else
2140SN/Astatic char cpu_arch[] = "sparc";
2150SN/A#  endif
2160SN/A#else
2170SN/A#error Add appropriate cpu_arch setting
2180SN/A#endif
2190SN/A
2200SN/A// Compiler variant
2210SN/A#ifdef COMPILER2
2220SN/A#define COMPILER_VARIANT "server"
2230SN/A#else
2240SN/A#define COMPILER_VARIANT "client"
2250SN/A#endif
2260SN/A
2270SN/A
2280SN/Avoid os::Bsd::initialize_system_info() {
2290SN/A  int mib[2];
2300SN/A  size_t len;
2310SN/A  int cpu_val;
2320SN/A  julong mem_val;
2330SN/A
2340SN/A  /* get processors count via hw.ncpus sysctl */
2350SN/A  mib[0] = CTL_HW;
2360SN/A  mib[1] = HW_NCPU;
2370SN/A  len = sizeof(cpu_val);
2380SN/A  if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
2390SN/A       assert(len == sizeof(cpu_val), "unexpected data size");
2400SN/A       set_processor_count(cpu_val);
2410SN/A  }
2420SN/A  else {
2430SN/A       set_processor_count(1);   // fallback
2440SN/A  }
2450SN/A
2460SN/A  /* get physical memory via hw.memsize sysctl (hw.memsize is used
2470SN/A   * since it returns a 64 bit value)
2480SN/A   */
2490SN/A  mib[0] = CTL_HW;
2500SN/A  mib[1] = HW_MEMSIZE;
2510SN/A  len = sizeof(mem_val);
2520SN/A  if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
2530SN/A       assert(len == sizeof(mem_val), "unexpected data size");
2540SN/A       _physical_memory = mem_val;
2550SN/A  } else {
2560SN/A       _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
2570SN/A  }
2580SN/A
2590SN/A#ifdef __OpenBSD__
2600SN/A  {
2610SN/A       // limit _physical_memory memory view on OpenBSD since
2620SN/A       // datasize rlimit restricts us anyway.
2630SN/A       struct rlimit limits;
2640SN/A       getrlimit(RLIMIT_DATA, &limits);
2650SN/A       _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
2660SN/A  }
2670SN/A#endif
2680SN/A}
2690SN/A
2700SN/A#ifdef __APPLE__
2710SN/Astatic const char *get_home() {
2720SN/A  const char *home_dir = ::getenv("HOME");
2730SN/A  if ((home_dir == NULL) || (*home_dir == '\0')) {
2740SN/A    struct passwd *passwd_info = getpwuid(geteuid());
2750SN/A    if (passwd_info != NULL) {
2760SN/A      home_dir = passwd_info->pw_dir;
2770SN/A    }
2780SN/A  }
2790SN/A
2800SN/A  return home_dir;
2810SN/A}
2820SN/A#endif
2830SN/A
2840SN/Avoid os::init_system_properties_values() {
2850SN/A//  char arch[12];
2860SN/A//  sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
2870SN/A
2880SN/A  // The next steps are taken in the product version:
2890SN/A  //
2900SN/A  // Obtain the JAVA_HOME value from the location of libjvm.so.
2910SN/A  // This library should be located at:
2920SN/A  // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
2930SN/A  //
2940SN/A  // If "/jre/lib/" appears at the right place in the path, then we
2950SN/A  // assume libjvm.so is installed in a JDK and we use this path.
2960SN/A  //
2970SN/A  // Otherwise exit with message: "Could not create the Java virtual machine."
2980SN/A  //
2990SN/A  // The following extra steps are taken in the debugging version:
3000SN/A  //
3010SN/A  // If "/jre/lib/" does NOT appear at the right place in the path
3020SN/A  // instead of exit check for $JAVA_HOME environment variable.
3030SN/A  //
3040SN/A  // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
3050SN/A  // then we append a fake suffix "hotspot/libjvm.so" to this path so
3060SN/A  // it looks like libjvm.so is installed there
3070SN/A  // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
3080SN/A  //
3090SN/A  // Otherwise exit.
3100SN/A  //
3110SN/A  // Important note: if the location of libjvm.so changes this
3120SN/A  // code needs to be changed accordingly.
3130SN/A
3140SN/A  // The next few definitions allow the code to be verbatim:
3150SN/A#define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
3160SN/A#define getenv(n) ::getenv(n)
3170SN/A
3180SN/A/*
3190SN/A * See ld(1):
3200SN/A *      The linker uses the following search paths to locate required
3210SN/A *      shared libraries:
3220SN/A *        1: ...
3230SN/A *        ...
3240SN/A *        7: The default directories, normally /lib and /usr/lib.
3250SN/A */
3260SN/A#ifndef DEFAULT_LIBPATH
3270SN/A#define DEFAULT_LIBPATH "/lib:/usr/lib"
3280SN/A#endif
3290SN/A
3300SN/A#define EXTENSIONS_DIR  "/lib/ext"
3310SN/A#define ENDORSED_DIR    "/lib/endorsed"
3320SN/A#define REG_DIR         "/usr/java/packages"
3330SN/A
3340SN/A#ifdef __APPLE__
3350SN/A#define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
3360SN/A#define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
3370SN/A        const char *user_home_dir = get_home();
3380SN/A        // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
3390SN/A        int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
3400SN/A            sizeof(SYS_EXTENSIONS_DIRS);
3410SN/A#endif
3420SN/A
3430SN/A  {
3440SN/A    /* sysclasspath, java_home, dll_dir */
3450SN/A    {
3460SN/A        char *home_path;
3470SN/A        char *dll_path;
3480SN/A        char *pslash;
3490SN/A        char buf[MAXPATHLEN];
3500SN/A        os::jvm_path(buf, sizeof(buf));
3510SN/A
3520SN/A        // Found the full path to libjvm.so.
3530SN/A        // Now cut the path to <java_home>/jre if we can.
3540SN/A        *(strrchr(buf, '/')) = '\0';  /* get rid of /libjvm.so */
3550SN/A        pslash = strrchr(buf, '/');
3560SN/A        if (pslash != NULL)
3570SN/A            *pslash = '\0';           /* get rid of /{client|server|hotspot} */
3580SN/A        dll_path = malloc(strlen(buf) + 1);
3590SN/A        if (dll_path == NULL)
3600SN/A            return;
3610SN/A        strcpy(dll_path, buf);
3620SN/A        Arguments::set_dll_dir(dll_path);
3630SN/A
3640SN/A        if (pslash != NULL) {
3650SN/A            pslash = strrchr(buf, '/');
3660SN/A            if (pslash != NULL) {
3670SN/A                *pslash = '\0';       /* get rid of /<arch> (/lib on macosx) */
3680SN/A#ifndef __APPLE__
3690SN/A                pslash = strrchr(buf, '/');
3700SN/A                if (pslash != NULL)
3710SN/A                    *pslash = '\0';   /* get rid of /lib */
3720SN/A#endif
3730SN/A            }
3740SN/A        }
3750SN/A
3760SN/A        home_path = malloc(strlen(buf) + 1);
3770SN/A        if (home_path == NULL)
3780SN/A            return;
3790SN/A        strcpy(home_path, buf);
3800SN/A        Arguments::set_java_home(home_path);
3810SN/A
3820SN/A        if (!set_boot_path('/', ':'))
3830SN/A            return;
3840SN/A    }
3850SN/A
3860SN/A    /*
3870SN/A     * Where to look for native libraries
3880SN/A     *
3890SN/A     * Note: Due to a legacy implementation, most of the library path
3900SN/A     * is set in the launcher.  This was to accomodate linking restrictions
3910SN/A     * on legacy Bsd implementations (which are no longer supported).
3920SN/A     * Eventually, all the library path setting will be done here.
3930SN/A     *
3940SN/A     * However, to prevent the proliferation of improperly built native
3950SN/A     * libraries, the new path component /usr/java/packages is added here.
3960SN/A     * Eventually, all the library path setting will be done here.
3970SN/A     */
3980SN/A    {
3990SN/A        char *ld_library_path;
4000SN/A
4010SN/A        /*
4020SN/A         * Construct the invariant part of ld_library_path. Note that the
4030SN/A         * space for the colon and the trailing null are provided by the
4040SN/A         * nulls included by the sizeof operator (so actually we allocate
4050SN/A         * a byte more than necessary).
4060SN/A         */
4070SN/A#ifdef __APPLE__
4080SN/A        ld_library_path = (char *) malloc(system_ext_size);
4090SN/A        sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir);
4100SN/A#else
4110SN/A        ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
4120SN/A            strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
4130SN/A        sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
4140SN/A#endif
4150SN/A
4160SN/A        /*
4170SN/A         * Get the user setting of LD_LIBRARY_PATH, and prepended it.  It
4180SN/A         * should always exist (until the legacy problem cited above is
4190SN/A         * addressed).
4200SN/A         */
4210SN/A#ifdef __APPLE__
4220SN/A        // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
4230SN/A        char *l = getenv("JAVA_LIBRARY_PATH");
4240SN/A        if (l != NULL) {
4250SN/A            char *t = ld_library_path;
4260SN/A            /* That's +1 for the colon and +1 for the trailing '\0' */
4270SN/A            ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1);
4280SN/A            sprintf(ld_library_path, "%s:%s", l, t);
4290SN/A            free(t);
4300SN/A        }
4310SN/A
4320SN/A        char *v = getenv("DYLD_LIBRARY_PATH");
4330SN/A#else
4340SN/A        char *v = getenv("LD_LIBRARY_PATH");
4350SN/A#endif
4360SN/A        if (v != NULL) {
4370SN/A            char *t = ld_library_path;
4380SN/A            /* That's +1 for the colon and +1 for the trailing '\0' */
4390SN/A            ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
4400SN/A            sprintf(ld_library_path, "%s:%s", v, t);
4410SN/A            free(t);
4420SN/A        }
4430SN/A
4440SN/A#ifdef __APPLE__
4450SN/A        // Apple's Java6 has "." at the beginning of java.library.path.
4460SN/A        // OpenJDK on Windows has "." at the end of java.library.path.
4470SN/A        // OpenJDK on Linux and Solaris don't have "." in java.library.path
4480SN/A        // at all. To ease the transition from Apple's Java6 to OpenJDK7,
4490SN/A        // "." is appended to the end of java.library.path. Yes, this
4500SN/A        // could cause a change in behavior, but Apple's Java6 behavior
4510SN/A        // can be achieved by putting "." at the beginning of the
4520SN/A        // JAVA_LIBRARY_PATH environment variable.
4530SN/A        {
4540SN/A            char *t = ld_library_path;
4550SN/A            // that's +3 for appending ":." and the trailing '\0'
4560SN/A            ld_library_path = (char *) malloc(strlen(t) + 3);
4570SN/A            sprintf(ld_library_path, "%s:%s", t, ".");
4580SN/A            free(t);
4590SN/A        }
4600SN/A#endif
4610SN/A
4620SN/A        Arguments::set_library_path(ld_library_path);
4630SN/A    }
4640SN/A
4650SN/A    /*
4660SN/A     * Extensions directories.
4670SN/A     *
4680SN/A     * Note that the space for the colon and the trailing null are provided
4690SN/A     * by the nulls included by the sizeof operator (so actually one byte more
4700SN/A     * than necessary is allocated).
4710SN/A     */
4720SN/A    {
4730SN/A#ifdef __APPLE__
4740SN/A        char *buf = malloc(strlen(Arguments::get_java_home()) +
4750SN/A            sizeof(EXTENSIONS_DIR) + system_ext_size);
4760SN/A        sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":"
4770SN/A            SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home());
4780SN/A#else
4790SN/A        char *buf = malloc(strlen(Arguments::get_java_home()) +
4800SN/A            sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
4810SN/A        sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
4820SN/A            Arguments::get_java_home());
4830SN/A#endif
4840SN/A
4850SN/A        Arguments::set_ext_dirs(buf);
4860SN/A    }
4870SN/A
4880SN/A    /* Endorsed standards default directory. */
4890SN/A    {
4900SN/A        char * buf;
4910SN/A        buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
4920SN/A        sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
4930SN/A        Arguments::set_endorsed_dirs(buf);
4940SN/A    }
4950SN/A  }
4960SN/A
4970SN/A#ifdef __APPLE__
4980SN/A#undef SYS_EXTENSIONS_DIR
4990SN/A#endif
5000SN/A#undef malloc
5010SN/A#undef getenv
5020SN/A#undef EXTENSIONS_DIR
5030SN/A#undef ENDORSED_DIR
5040SN/A
5050SN/A  // Done
5060SN/A  return;
5070SN/A}
5080SN/A
5090SN/A////////////////////////////////////////////////////////////////////////////////
5100SN/A// breakpoint support
5110SN/A
5120SN/Avoid os::breakpoint() {
5130SN/A  BREAKPOINT;
5140SN/A}
5150SN/A
5160SN/Aextern "C" void breakpoint() {
5170SN/A  // use debugger to set breakpoint here
5180SN/A}
5190SN/A
5200SN/A////////////////////////////////////////////////////////////////////////////////
5210SN/A// signal support
5220SN/A
5230SN/Adebug_only(static bool signal_sets_initialized = false);
5240SN/Astatic sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
5250SN/A
5260SN/Abool os::Bsd::is_sig_ignored(int sig) {
5270SN/A      struct sigaction oact;
5280SN/A      sigaction(sig, (struct sigaction*)NULL, &oact);
5290SN/A      void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
5300SN/A                                     : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
5310SN/A      if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
5320SN/A           return true;
5330SN/A      else
5340SN/A           return false;
5350SN/A}
5360SN/A
5370SN/Avoid os::Bsd::signal_sets_init() {
5380SN/A  // Should also have an assertion stating we are still single-threaded.
5390SN/A  assert(!signal_sets_initialized, "Already initialized");
5400SN/A  // Fill in signals that are necessarily unblocked for all threads in
5410SN/A  // the VM. Currently, we unblock the following signals:
5420SN/A  // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
5430SN/A  //                         by -Xrs (=ReduceSignalUsage));
5440SN/A  // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
5450SN/A  // other threads. The "ReduceSignalUsage" boolean tells us not to alter
5460SN/A  // the dispositions or masks wrt these signals.
5470SN/A  // Programs embedding the VM that want to use the above signals for their
5480SN/A  // own purposes must, at this time, use the "-Xrs" option to prevent
5490SN/A  // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
5500SN/A  // (See bug 4345157, and other related bugs).
5510SN/A  // In reality, though, unblocking these signals is really a nop, since
5520SN/A  // these signals are not blocked by default.
5530SN/A  sigemptyset(&unblocked_sigs);
5540SN/A  sigemptyset(&allowdebug_blocked_sigs);
5550SN/A  sigaddset(&unblocked_sigs, SIGILL);
5560SN/A  sigaddset(&unblocked_sigs, SIGSEGV);
5570SN/A  sigaddset(&unblocked_sigs, SIGBUS);
5580SN/A  sigaddset(&unblocked_sigs, SIGFPE);
5590SN/A  sigaddset(&unblocked_sigs, SR_signum);
5600SN/A
5610SN/A  if (!ReduceSignalUsage) {
5620SN/A   if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
5630SN/A      sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
5640SN/A      sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
5650SN/A   }
5660SN/A   if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
5670SN/A      sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
5680SN/A      sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
5690SN/A   }
5700SN/A   if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
5710SN/A      sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
5720SN/A      sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
5730SN/A   }
5740SN/A  }
5750SN/A  // Fill in signals that are blocked by all but the VM thread.
5760SN/A  sigemptyset(&vm_sigs);
5770SN/A  if (!ReduceSignalUsage)
5780SN/A    sigaddset(&vm_sigs, BREAK_SIGNAL);
5790SN/A  debug_only(signal_sets_initialized = true);
5800SN/A
5810SN/A}
5820SN/A
5830SN/A// These are signals that are unblocked while a thread is running Java.
5840SN/A// (For some reason, they get blocked by default.)
5850SN/Asigset_t* os::Bsd::unblocked_signals() {
5860SN/A  assert(signal_sets_initialized, "Not initialized");
5870SN/A  return &unblocked_sigs;
5880SN/A}
5890SN/A
5900SN/A// These are the signals that are blocked while a (non-VM) thread is
5910SN/A// running Java. Only the VM thread handles these signals.
5920SN/Asigset_t* os::Bsd::vm_signals() {
5930SN/A  assert(signal_sets_initialized, "Not initialized");
5940SN/A  return &vm_sigs;
5950SN/A}
5960SN/A
5970SN/A// These are signals that are blocked during cond_wait to allow debugger in
5980SN/Asigset_t* os::Bsd::allowdebug_blocked_signals() {
5990SN/A  assert(signal_sets_initialized, "Not initialized");
6000SN/A  return &allowdebug_blocked_sigs;
6010SN/A}
6020SN/A
6030SN/Avoid os::Bsd::hotspot_sigmask(Thread* thread) {
6040SN/A
6050SN/A  //Save caller's signal mask before setting VM signal mask
6060SN/A  sigset_t caller_sigmask;
6070SN/A  pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
6080SN/A
6090SN/A  OSThread* osthread = thread->osthread();
6100SN/A  osthread->set_caller_sigmask(caller_sigmask);
6110SN/A
6120SN/A  pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
6130SN/A
6140SN/A  if (!ReduceSignalUsage) {
6150SN/A    if (thread->is_VM_thread()) {
6160SN/A      // Only the VM thread handles BREAK_SIGNAL ...
6170SN/A      pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
6180SN/A    } else {
6190SN/A      // ... all other threads block BREAK_SIGNAL
6200SN/A      pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
6210SN/A    }
6220SN/A  }
6230SN/A}
6240SN/A
6250SN/A
6260SN/A//////////////////////////////////////////////////////////////////////////////
6270SN/A// create new thread
6280SN/A
6290SN/A// check if it's safe to start a new thread
6300SN/Astatic bool _thread_safety_check(Thread* thread) {
6310SN/A  return true;
6320SN/A}
6330SN/A
6340SN/A#ifdef __APPLE__
6350SN/A// library handle for calling objc_registerThreadWithCollector()
6360SN/A// without static linking to the libobjc library
6370SN/A#define OBJC_LIB "/usr/lib/libobjc.dylib"
6380SN/A#define OBJC_GCREGISTER "objc_registerThreadWithCollector"
6390SN/Atypedef void (*objc_registerThreadWithCollector_t)();
6400SN/Aextern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
6410SN/Aobjc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
6420SN/A#endif
6430SN/A
6440SN/A#ifdef __APPLE__
6450SN/Astatic uint64_t locate_unique_thread_id() {
6460SN/A  // Additional thread_id used to correlate threads in SA
6470SN/A  thread_identifier_info_data_t     m_ident_info;
6480SN/A  mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
6490SN/A
6500SN/A  thread_info(::mach_thread_self(), THREAD_IDENTIFIER_INFO,
6510SN/A              (thread_info_t) &m_ident_info, &count);
6520SN/A  return m_ident_info.thread_id;
6530SN/A}
6540SN/A#endif
6550SN/A
6560SN/A// Thread start routine for all newly created threads
6570SN/Astatic void *java_start(Thread *thread) {
6580SN/A  // Try to randomize the cache line index of hot stack frames.
6590SN/A  // This helps when threads of the same stack traces evict each other's
6600SN/A  // cache lines. The threads can be either from the same JVM instance, or
6610SN/A  // from different JVM instances. The benefit is especially true for
6620SN/A  // processors with hyperthreading technology.
6630SN/A  static int counter = 0;
6640SN/A  int pid = os::current_process_id();
6650SN/A  alloca(((pid ^ counter++) & 7) * 128);
6660SN/A
6670SN/A  ThreadLocalStorage::set_thread(thread);
6680SN/A
6690SN/A  OSThread* osthread = thread->osthread();
6700SN/A  Monitor* sync = osthread->startThread_lock();
6710SN/A
6720SN/A  // non floating stack BsdThreads needs extra check, see above
6730SN/A  if (!_thread_safety_check(thread)) {
6740SN/A    // notify parent thread
6750SN/A    MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
6760SN/A    osthread->set_state(ZOMBIE);
6770SN/A    sync->notify_all();
6780SN/A    return NULL;
6790SN/A  }
6800SN/A
6810SN/A#ifdef __APPLE__
6820SN/A  // thread_id is mach thread on macos
6830SN/A  osthread->set_thread_id(::mach_thread_self());
6840SN/A  osthread->set_unique_thread_id(locate_unique_thread_id());
6850SN/A#else
6860SN/A  // thread_id is pthread_id on BSD
6870SN/A  osthread->set_thread_id(::pthread_self());
6880SN/A#endif
6890SN/A  // initialize signal mask for this thread
6900SN/A  os::Bsd::hotspot_sigmask(thread);
6910SN/A
6920SN/A  // initialize floating point control register
6930SN/A  os::Bsd::init_thread_fpu_state();
6940SN/A
6950SN/A#ifdef __APPLE__
6960SN/A  // register thread with objc gc
6970SN/A  if (objc_registerThreadWithCollectorFunction != NULL) {
6980SN/A    objc_registerThreadWithCollectorFunction();
6990SN/A  }
7000SN/A#endif
7010SN/A
7020SN/A  // handshaking with parent thread
7030SN/A  {
7040SN/A    MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
7050SN/A
7060SN/A    // notify parent thread
7070SN/A    osthread->set_state(INITIALIZED);
7080SN/A    sync->notify_all();
7090SN/A
7100SN/A    // wait until os::start_thread()
7110SN/A    while (osthread->get_state() == INITIALIZED) {
7120SN/A      sync->wait(Mutex::_no_safepoint_check_flag);
7130SN/A    }
7140SN/A  }
7150SN/A
7160SN/A  // call one more level start routine
7170SN/A  thread->run();
7180SN/A
7190SN/A  return 0;
7200SN/A}
7210SN/A
7220SN/Abool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
7230SN/A  assert(thread->osthread() == NULL, "caller responsible");
7240SN/A
7250SN/A  // Allocate the OSThread object
7260SN/A  OSThread* osthread = new OSThread(NULL, NULL);
7270SN/A  if (osthread == NULL) {
7280SN/A    return false;
7290SN/A  }
7300SN/A
7310SN/A  // set the correct thread state
7320SN/A  osthread->set_thread_type(thr_type);
7330SN/A
7340SN/A  // Initial state is ALLOCATED but not INITIALIZED
7350SN/A  osthread->set_state(ALLOCATED);
7360SN/A
7370SN/A  thread->set_osthread(osthread);
7380SN/A
7390SN/A  // init thread attributes
7400SN/A  pthread_attr_t attr;
7410SN/A  pthread_attr_init(&attr);
7420SN/A  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
7430SN/A
7440SN/A  // stack size
7450SN/A  if (os::Bsd::supports_variable_stack_size()) {
7460SN/A    // calculate stack size if it's not specified by caller
7470SN/A    if (stack_size == 0) {
7480SN/A      stack_size = os::Bsd::default_stack_size(thr_type);
7490SN/A
7500SN/A      switch (thr_type) {
7510SN/A      case os::java_thread:
7520SN/A        // Java threads use ThreadStackSize which default value can be
7530SN/A        // changed with the flag -Xss
7540SN/A        assert (JavaThread::stack_size_at_create() > 0, "this should be set");
7550SN/A        stack_size = JavaThread::stack_size_at_create();
7560SN/A        break;
7570SN/A      case os::compiler_thread:
7580SN/A        if (CompilerThreadStackSize > 0) {
7590SN/A          stack_size = (size_t)(CompilerThreadStackSize * K);
7600SN/A          break;
7610SN/A        } // else fall through:
7620SN/A          // use VMThreadStackSize if CompilerThreadStackSize is not defined
7630SN/A      case os::vm_thread:
7640SN/A      case os::pgc_thread:
7650SN/A      case os::cgc_thread:
7660SN/A      case os::watcher_thread:
7670SN/A        if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
7680SN/A        break;
7690SN/A      }
7700SN/A    }
7710SN/A
7720SN/A    stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
7730SN/A    pthread_attr_setstacksize(&attr, stack_size);
7740SN/A  } else {
7750SN/A    // let pthread_create() pick the default value.
7760SN/A  }
7770SN/A
7780SN/A  ThreadState state;
7790SN/A
7800SN/A  {
7810SN/A    pthread_t tid;
7820SN/A    int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
7830SN/A
7840SN/A    pthread_attr_destroy(&attr);
7850SN/A
7860SN/A    if (ret != 0) {
7870SN/A      if (PrintMiscellaneous && (Verbose || WizardMode)) {
7880SN/A        perror("pthread_create()");
7890SN/A      }
7900SN/A      // Need to clean up stuff we've allocated so far
7910SN/A      thread->set_osthread(NULL);
7920SN/A      delete osthread;
7930SN/A      return false;
7940SN/A    }
7950SN/A
7960SN/A    // Store pthread info into the OSThread
7970SN/A    osthread->set_pthread_id(tid);
7980SN/A
7990SN/A    // Wait until child thread is either initialized or aborted
8000SN/A    {
8010SN/A      Monitor* sync_with_child = osthread->startThread_lock();
8020SN/A      MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
8030SN/A      while ((state = osthread->get_state()) == ALLOCATED) {
8040SN/A        sync_with_child->wait(Mutex::_no_safepoint_check_flag);
8050SN/A      }
8060SN/A    }
8070SN/A
8080SN/A  }
8090SN/A
8100SN/A  // Aborted due to thread limit being reached
8110SN/A  if (state == ZOMBIE) {
8120SN/A      thread->set_osthread(NULL);
8130SN/A      delete osthread;
8140SN/A      return false;
8150SN/A  }
8160SN/A
8170SN/A  // The thread is returned suspended (in state INITIALIZED),
8180SN/A  // and is started higher up in the call chain
8190SN/A  assert(state == INITIALIZED, "race condition");
8200SN/A  return true;
8210SN/A}
8220SN/A
8230SN/A/////////////////////////////////////////////////////////////////////////////
8240SN/A// attach existing thread
8250SN/A
8260SN/A// bootstrap the main thread
8270SN/Abool os::create_main_thread(JavaThread* thread) {
8280SN/A  assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
8290SN/A  return create_attached_thread(thread);
8300SN/A}
8310SN/A
8320SN/Abool os::create_attached_thread(JavaThread* thread) {
8330SN/A#ifdef ASSERT
8340SN/A    thread->verify_not_published();
8350SN/A#endif
8360SN/A
8370SN/A  // Allocate the OSThread object
8380SN/A  OSThread* osthread = new OSThread(NULL, NULL);
8390SN/A
8400SN/A  if (osthread == NULL) {
8410SN/A    return false;
8420SN/A  }
8430SN/A
8440SN/A  // Store pthread info into the OSThread
8450SN/A#ifdef __APPLE__
8460SN/A  osthread->set_thread_id(::mach_thread_self());
8470SN/A  osthread->set_unique_thread_id(locate_unique_thread_id());
8480SN/A#else
8490SN/A  osthread->set_thread_id(::pthread_self());
8500SN/A#endif
8510SN/A  osthread->set_pthread_id(::pthread_self());
8520SN/A
8530SN/A  // initialize floating point control register
8540SN/A  os::Bsd::init_thread_fpu_state();
8550SN/A
8560SN/A  // Initial thread state is RUNNABLE
8570SN/A  osthread->set_state(RUNNABLE);
8580SN/A
8590SN/A  thread->set_osthread(osthread);
8600SN/A
8610SN/A  // initialize signal mask for this thread
8620SN/A  // and save the caller's signal mask
8630SN/A  os::Bsd::hotspot_sigmask(thread);
8640SN/A
8650SN/A  return true;
8660SN/A}
8670SN/A
8680SN/Avoid os::pd_start_thread(Thread* thread) {
8690SN/A  OSThread * osthread = thread->osthread();
8700SN/A  assert(osthread->get_state() != INITIALIZED, "just checking");
8710SN/A  Monitor* sync_with_child = osthread->startThread_lock();
8720SN/A  MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
8730SN/A  sync_with_child->notify();
8740SN/A}
8750SN/A
8760SN/A// Free Bsd resources related to the OSThread
8770SN/Avoid os::free_thread(OSThread* osthread) {
8780SN/A  assert(osthread != NULL, "osthread not set");
8790SN/A
8800SN/A  if (Thread::current()->osthread() == osthread) {
8810SN/A    // Restore caller's signal mask
8820SN/A    sigset_t sigmask = osthread->caller_sigmask();
8830SN/A    pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
8840SN/A   }
8850SN/A
8860SN/A  delete osthread;
8870SN/A}
8880SN/A
8890SN/A//////////////////////////////////////////////////////////////////////////////
8900SN/A// thread local storage
8910SN/A
8920SN/Aint os::allocate_thread_local_storage() {
8930SN/A  pthread_key_t key;
8940SN/A  int rslt = pthread_key_create(&key, NULL);
8950SN/A  assert(rslt == 0, "cannot allocate thread local storage");
8960SN/A  return (int)key;
8970SN/A}
8980SN/A
8990SN/A// Note: This is currently not used by VM, as we don't destroy TLS key
9000SN/A// on VM exit.
9010SN/Avoid os::free_thread_local_storage(int index) {
9020SN/A  int rslt = pthread_key_delete((pthread_key_t)index);
9030SN/A  assert(rslt == 0, "invalid index");
9040SN/A}
9050SN/A
9060SN/Avoid os::thread_local_storage_at_put(int index, void* value) {
9070SN/A  int rslt = pthread_setspecific((pthread_key_t)index, value);
9080SN/A  assert(rslt == 0, "pthread_setspecific failed");
9090SN/A}
9100SN/A
9110SN/Aextern "C" Thread* get_thread() {
9120SN/A  return ThreadLocalStorage::thread();
9130SN/A}
9140SN/A
9150SN/A
9160SN/A////////////////////////////////////////////////////////////////////////////////
9170SN/A// time support
9180SN/A
9190SN/A// Time since start-up in seconds to a fine granularity.
9200SN/A// Used by VMSelfDestructTimer and the MemProfiler.
9210SN/Adouble os::elapsedTime() {
9220SN/A
9230SN/A  return (double)(os::elapsed_counter()) * 0.000001;
9240SN/A}
9250SN/A
9260SN/Ajlong os::elapsed_counter() {
9270SN/A  timeval time;
9280SN/A  int status = gettimeofday(&time, NULL);
9290SN/A  return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
9300SN/A}
9310SN/A
9320SN/Ajlong os::elapsed_frequency() {
9330SN/A  return (1000 * 1000);
9340SN/A}
9350SN/A
9360SN/Abool os::supports_vtime() { return true; }
9370SN/Abool os::enable_vtime()   { return false; }
9380SN/Abool os::vtime_enabled()  { return false; }
9390SN/A
9400SN/Adouble os::elapsedVTime() {
9410SN/A  // better than nothing, but not much
9420SN/A  return elapsedTime();
9430SN/A}
9440SN/A
9450SN/Ajlong os::javaTimeMillis() {
9460SN/A  timeval time;
9470SN/A  int status = gettimeofday(&time, NULL);
9480SN/A  assert(status != -1, "bsd error");
9490SN/A  return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
9500SN/A}
9510SN/A
9520SN/A#ifndef CLOCK_MONOTONIC
9530SN/A#define CLOCK_MONOTONIC (1)
9540SN/A#endif
9550SN/A
9560SN/A#ifdef __APPLE__
9570SN/Avoid os::Bsd::clock_init() {
9580SN/A        // XXXDARWIN: Investigate replacement monotonic clock
9590SN/A}
9600SN/A#else
9610SN/Avoid os::Bsd::clock_init() {
9620SN/A  struct timespec res;
9630SN/A  struct timespec tp;
9640SN/A  if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
9650SN/A      ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
9660SN/A    // yes, monotonic clock is supported
9670SN/A    _clock_gettime = ::clock_gettime;
9680SN/A  }
9690SN/A}
9700SN/A#endif
9710SN/A
9720SN/A
9730SN/Ajlong os::javaTimeNanos() {
9740SN/A  if (Bsd::supports_monotonic_clock()) {
9750SN/A    struct timespec tp;
9760SN/A    int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
9770SN/A    assert(status == 0, "gettime error");
9780SN/A    jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
9790SN/A    return result;
9800SN/A  } else {
9810SN/A    timeval time;
9820SN/A    int status = gettimeofday(&time, NULL);
9830SN/A    assert(status != -1, "bsd error");
9840SN/A    jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
9850SN/A    return 1000 * usecs;
9860SN/A  }
9870SN/A}
9880SN/A
9890SN/Avoid os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
9900SN/A  if (Bsd::supports_monotonic_clock()) {
9910SN/A    info_ptr->max_value = ALL_64_BITS;
9920SN/A
9930SN/A    // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
9940SN/A    info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
9950SN/A    info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
9960SN/A  } else {
9970SN/A    // gettimeofday - based on time in seconds since the Epoch thus does not wrap
9980SN/A    info_ptr->max_value = ALL_64_BITS;
9990SN/A
10000SN/A    // gettimeofday is a real time clock so it skips
10010SN/A    info_ptr->may_skip_backward = true;
10020SN/A    info_ptr->may_skip_forward = true;
10030SN/A  }
10040SN/A
10050SN/A  info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
10060SN/A}
10070SN/A
10080SN/A// Return the real, user, and system times in seconds from an
10090SN/A// arbitrary fixed point in the past.
10100SN/Abool os::getTimesSecs(double* process_real_time,
10110SN/A                      double* process_user_time,
10120SN/A                      double* process_system_time) {
10130SN/A  struct tms ticks;
10140SN/A  clock_t real_ticks = times(&ticks);
10150SN/A
10160SN/A  if (real_ticks == (clock_t) (-1)) {
10170SN/A    return false;
10180SN/A  } else {
10190SN/A    double ticks_per_second = (double) clock_tics_per_sec;
10200SN/A    *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
10210SN/A    *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
10220SN/A    *process_real_time = ((double) real_ticks) / ticks_per_second;
10230SN/A
10240SN/A    return true;
10250SN/A  }
10260SN/A}
10270SN/A
10280SN/A
10290SN/Achar * os::local_time_string(char *buf, size_t buflen) {
10300SN/A  struct tm t;
10310SN/A  time_t long_time;
10320SN/A  time(&long_time);
10330SN/A  localtime_r(&long_time, &t);
10340SN/A  jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
10350SN/A               t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
10360SN/A               t.tm_hour, t.tm_min, t.tm_sec);
10370SN/A  return buf;
10380SN/A}
10390SN/A
10400SN/Astruct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
10410SN/A  return localtime_r(clock, res);
10420SN/A}
10430SN/A
10440SN/A////////////////////////////////////////////////////////////////////////////////
10450SN/A// runtime exit support
10460SN/A
10470SN/A// Note: os::shutdown() might be called very early during initialization, or
10480SN/A// called from signal handler. Before adding something to os::shutdown(), make
10490SN/A// sure it is async-safe and can handle partially initialized VM.
10500SN/Avoid os::shutdown() {
10510SN/A
10520SN/A  // allow PerfMemory to attempt cleanup of any persistent resources
10530SN/A  perfMemory_exit();
10540SN/A
10550SN/A  // needs to remove object in file system
10560SN/A  AttachListener::abort();
10570SN/A
10580SN/A  // flush buffered output, finish log files
10590SN/A  ostream_abort();
10600SN/A
10610SN/A  // Check for abort hook
10620SN/A  abort_hook_t abort_hook = Arguments::abort_hook();
10630SN/A  if (abort_hook != NULL) {
10640SN/A    abort_hook();
10650SN/A  }
10660SN/A
10670SN/A}
10680SN/A
10690SN/A// Note: os::abort() might be called very early during initialization, or
10700SN/A// called from signal handler. Before adding something to os::abort(), make
10710SN/A// sure it is async-safe and can handle partially initialized VM.
10720SN/Avoid os::abort(bool dump_core) {
10730SN/A  os::shutdown();
10740SN/A  if (dump_core) {
10750SN/A#ifndef PRODUCT
10760SN/A    fdStream out(defaultStream::output_fd());
10770SN/A    out.print_raw("Current thread is ");
10780SN/A    char buf[16];
10790SN/A    jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
10800SN/A    out.print_raw_cr(buf);
10810SN/A    out.print_raw_cr("Dumping core ...");
10820SN/A#endif
10830SN/A    ::abort(); // dump core
1084  }
1085
1086  ::exit(1);
1087}
1088
1089// Die immediately, no exit hook, no abort hook, no cleanup.
1090void os::die() {
1091  // _exit() on BsdThreads only kills current thread
1092  ::abort();
1093}
1094
1095// unused on bsd for now.
1096void os::set_error_file(const char *logfile) {}
1097
1098
1099// This method is a copy of JDK's sysGetLastErrorString
1100// from src/solaris/hpi/src/system_md.c
1101
1102size_t os::lasterror(char *buf, size_t len) {
1103
1104  if (errno == 0)  return 0;
1105
1106  const char *s = ::strerror(errno);
1107  size_t n = ::strlen(s);
1108  if (n >= len) {
1109    n = len - 1;
1110  }
1111  ::strncpy(buf, s, n);
1112  buf[n] = '\0';
1113  return n;
1114}
1115
1116intx os::current_thread_id() {
1117#ifdef __APPLE__
1118  return (intx)::mach_thread_self();
1119#else
1120  return (intx)::pthread_self();
1121#endif
1122}
1123int os::current_process_id() {
1124
1125  // Under the old bsd thread library, bsd gives each thread
1126  // its own process id. Because of this each thread will return
1127  // a different pid if this method were to return the result
1128  // of getpid(2). Bsd provides no api that returns the pid
1129  // of the launcher thread for the vm. This implementation
1130  // returns a unique pid, the pid of the launcher thread
1131  // that starts the vm 'process'.
1132
1133  // Under the NPTL, getpid() returns the same pid as the
1134  // launcher thread rather than a unique pid per thread.
1135  // Use gettid() if you want the old pre NPTL behaviour.
1136
1137  // if you are looking for the result of a call to getpid() that
1138  // returns a unique pid for the calling thread, then look at the
1139  // OSThread::thread_id() method in osThread_bsd.hpp file
1140
1141  return (int)(_initial_pid ? _initial_pid : getpid());
1142}
1143
1144// DLL functions
1145
1146#define JNI_LIB_PREFIX "lib"
1147#ifdef __APPLE__
1148#define JNI_LIB_SUFFIX ".dylib"
1149#else
1150#define JNI_LIB_SUFFIX ".so"
1151#endif
1152
1153const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1154
1155// This must be hard coded because it's the system's temporary
1156// directory not the java application's temp directory, ala java.io.tmpdir.
1157#ifdef __APPLE__
1158// macosx has a secure per-user temporary directory
1159char temp_path_storage[PATH_MAX];
1160const char* os::get_temp_directory() {
1161  static char *temp_path = NULL;
1162  if (temp_path == NULL) {
1163    int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1164    if (pathSize == 0 || pathSize > PATH_MAX) {
1165      strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1166    }
1167    temp_path = temp_path_storage;
1168  }
1169  return temp_path;
1170}
1171#else /* __APPLE__ */
1172const char* os::get_temp_directory() { return "/tmp"; }
1173#endif /* __APPLE__ */
1174
1175static bool file_exists(const char* filename) {
1176  struct stat statbuf;
1177  if (filename == NULL || strlen(filename) == 0) {
1178    return false;
1179  }
1180  return os::stat(filename, &statbuf) == 0;
1181}
1182
1183bool os::dll_build_name(char* buffer, size_t buflen,
1184                        const char* pname, const char* fname) {
1185  bool retval = false;
1186  // Copied from libhpi
1187  const size_t pnamelen = pname ? strlen(pname) : 0;
1188
1189  // Return error on buffer overflow.
1190  if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
1191    return retval;
1192  }
1193
1194  if (pnamelen == 0) {
1195    snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
1196    retval = true;
1197  } else if (strchr(pname, *os::path_separator()) != NULL) {
1198    int n;
1199    char** pelements = split_path(pname, &n);
1200    if (pelements == NULL) {
1201      return false;
1202    }
1203    for (int i = 0 ; i < n ; i++) {
1204      // Really shouldn't be NULL, but check can't hurt
1205      if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1206        continue; // skip the empty path values
1207      }
1208      snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
1209          pelements[i], fname);
1210      if (file_exists(buffer)) {
1211        retval = true;
1212        break;
1213      }
1214    }
1215    // release the storage
1216    for (int i = 0 ; i < n ; i++) {
1217      if (pelements[i] != NULL) {
1218        FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1219      }
1220    }
1221    if (pelements != NULL) {
1222      FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1223    }
1224  } else {
1225    snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
1226    retval = true;
1227  }
1228  return retval;
1229}
1230
1231// check if addr is inside libjvm.so
1232bool os::address_is_in_vm(address addr) {
1233  static address libjvm_base_addr;
1234  Dl_info dlinfo;
1235
1236  if (libjvm_base_addr == NULL) {
1237    dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
1238    libjvm_base_addr = (address)dlinfo.dli_fbase;
1239    assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1240  }
1241
1242  if (dladdr((void *)addr, &dlinfo)) {
1243    if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1244  }
1245
1246  return false;
1247}
1248
1249
1250#define MACH_MAXSYMLEN 256
1251
1252bool os::dll_address_to_function_name(address addr, char *buf,
1253                                      int buflen, int *offset) {
1254  Dl_info dlinfo;
1255  char localbuf[MACH_MAXSYMLEN];
1256
1257  // dladdr will find names of dynamic functions only, but does
1258  // it set dli_fbase with mach_header address when it "fails" ?
1259  if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
1260    if (buf != NULL) {
1261      if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1262        jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1263      }
1264    }
1265    if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1266    return true;
1267  } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
1268    if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1269       buf, buflen, offset, dlinfo.dli_fname)) {
1270       return true;
1271    }
1272  }
1273
1274  // Handle non-dymanic manually:
1275  if (dlinfo.dli_fbase != NULL &&
1276      Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) {
1277    if(!Decoder::demangle(localbuf, buf, buflen)) {
1278      jio_snprintf(buf, buflen, "%s", localbuf);
1279    }
1280    return true;
1281  }
1282  if (buf != NULL) buf[0] = '\0';
1283  if (offset != NULL) *offset = -1;
1284  return false;
1285}
1286
1287// ported from solaris version
1288bool os::dll_address_to_library_name(address addr, char* buf,
1289                                     int buflen, int* offset) {
1290  Dl_info dlinfo;
1291
1292  if (dladdr((void*)addr, &dlinfo)){
1293     if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1294     if (offset) *offset = addr - (address)dlinfo.dli_fbase;
1295     return true;
1296  } else {
1297     if (buf) buf[0] = '\0';
1298     if (offset) *offset = -1;
1299     return false;
1300  }
1301}
1302
1303// Loads .dll/.so and
1304// in case of error it checks if .dll/.so was built for the
1305// same architecture as Hotspot is running on
1306
1307#ifdef __APPLE__
1308void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1309  void * result= ::dlopen(filename, RTLD_LAZY);
1310  if (result != NULL) {
1311    // Successful loading
1312    return result;
1313  }
1314
1315  // Read system error message into ebuf
1316  ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1317  ebuf[ebuflen-1]='\0';
1318
1319  return NULL;
1320}
1321#else
1322void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1323{
1324  void * result= ::dlopen(filename, RTLD_LAZY);
1325  if (result != NULL) {
1326    // Successful loading
1327    return result;
1328  }
1329
1330  Elf32_Ehdr elf_head;
1331
1332  // Read system error message into ebuf
1333  // It may or may not be overwritten below
1334  ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1335  ebuf[ebuflen-1]='\0';
1336  int diag_msg_max_length=ebuflen-strlen(ebuf);
1337  char* diag_msg_buf=ebuf+strlen(ebuf);
1338
1339  if (diag_msg_max_length==0) {
1340    // No more space in ebuf for additional diagnostics message
1341    return NULL;
1342  }
1343
1344
1345  int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1346
1347  if (file_descriptor < 0) {
1348    // Can't open library, report dlerror() message
1349    return NULL;
1350  }
1351
1352  bool failed_to_read_elf_head=
1353    (sizeof(elf_head)!=
1354        (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1355
1356  ::close(file_descriptor);
1357  if (failed_to_read_elf_head) {
1358    // file i/o error - report dlerror() msg
1359    return NULL;
1360  }
1361
1362  typedef struct {
1363    Elf32_Half  code;         // Actual value as defined in elf.h
1364    Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1365    char        elf_class;    // 32 or 64 bit
1366    char        endianess;    // MSB or LSB
1367    char*       name;         // String representation
1368  } arch_t;
1369
1370  #ifndef EM_486
1371  #define EM_486          6               /* Intel 80486 */
1372  #endif
1373
1374  #ifndef EM_MIPS_RS3_LE
1375  #define EM_MIPS_RS3_LE  10              /* MIPS */
1376  #endif
1377
1378  #ifndef EM_PPC64
1379  #define EM_PPC64        21              /* PowerPC64 */
1380  #endif
1381
1382  #ifndef EM_S390
1383  #define EM_S390         22              /* IBM System/390 */
1384  #endif
1385
1386  #ifndef EM_IA_64
1387  #define EM_IA_64        50              /* HP/Intel IA-64 */
1388  #endif
1389
1390  #ifndef EM_X86_64
1391  #define EM_X86_64       62              /* AMD x86-64 */
1392  #endif
1393
1394  static const arch_t arch_array[]={
1395    {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1396    {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1397    {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1398    {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1399    {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1400    {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1401    {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1402    {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1403    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1404    {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1405    {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1406    {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1407    {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1408    {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1409    {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1410    {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1411  };
1412
1413  #if  (defined IA32)
1414    static  Elf32_Half running_arch_code=EM_386;
1415  #elif   (defined AMD64)
1416    static  Elf32_Half running_arch_code=EM_X86_64;
1417  #elif  (defined IA64)
1418    static  Elf32_Half running_arch_code=EM_IA_64;
1419  #elif  (defined __sparc) && (defined _LP64)
1420    static  Elf32_Half running_arch_code=EM_SPARCV9;
1421  #elif  (defined __sparc) && (!defined _LP64)
1422    static  Elf32_Half running_arch_code=EM_SPARC;
1423  #elif  (defined __powerpc64__)
1424    static  Elf32_Half running_arch_code=EM_PPC64;
1425  #elif  (defined __powerpc__)
1426    static  Elf32_Half running_arch_code=EM_PPC;
1427  #elif  (defined ARM)
1428    static  Elf32_Half running_arch_code=EM_ARM;
1429  #elif  (defined S390)
1430    static  Elf32_Half running_arch_code=EM_S390;
1431  #elif  (defined ALPHA)
1432    static  Elf32_Half running_arch_code=EM_ALPHA;
1433  #elif  (defined MIPSEL)
1434    static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1435  #elif  (defined PARISC)
1436    static  Elf32_Half running_arch_code=EM_PARISC;
1437  #elif  (defined MIPS)
1438    static  Elf32_Half running_arch_code=EM_MIPS;
1439  #elif  (defined M68K)
1440    static  Elf32_Half running_arch_code=EM_68K;
1441  #else
1442    #error Method os::dll_load requires that one of following is defined:\
1443         IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1444  #endif
1445
1446  // Identify compatability class for VM's architecture and library's architecture
1447  // Obtain string descriptions for architectures
1448
1449  arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1450  int running_arch_index=-1;
1451
1452  for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
1453    if (running_arch_code == arch_array[i].code) {
1454      running_arch_index    = i;
1455    }
1456    if (lib_arch.code == arch_array[i].code) {
1457      lib_arch.compat_class = arch_array[i].compat_class;
1458      lib_arch.name         = arch_array[i].name;
1459    }
1460  }
1461
1462  assert(running_arch_index != -1,
1463    "Didn't find running architecture code (running_arch_code) in arch_array");
1464  if (running_arch_index == -1) {
1465    // Even though running architecture detection failed
1466    // we may still continue with reporting dlerror() message
1467    return NULL;
1468  }
1469
1470  if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1471    ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1472    return NULL;
1473  }
1474
1475#ifndef S390
1476  if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1477    ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1478    return NULL;
1479  }
1480#endif // !S390
1481
1482  if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1483    if ( lib_arch.name!=NULL ) {
1484      ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1485        " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1486        lib_arch.name, arch_array[running_arch_index].name);
1487    } else {
1488      ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1489      " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1490        lib_arch.code,
1491        arch_array[running_arch_index].name);
1492    }
1493  }
1494
1495  return NULL;
1496}
1497#endif /* !__APPLE__ */
1498
1499// XXX: Do we need a lock around this as per Linux?
1500void* os::dll_lookup(void* handle, const char* name) {
1501  return dlsym(handle, name);
1502}
1503
1504
1505static bool _print_ascii_file(const char* filename, outputStream* st) {
1506  int fd = ::open(filename, O_RDONLY);
1507  if (fd == -1) {
1508     return false;
1509  }
1510
1511  char buf[32];
1512  int bytes;
1513  while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1514    st->print_raw(buf, bytes);
1515  }
1516
1517  ::close(fd);
1518
1519  return true;
1520}
1521
1522void os::print_dll_info(outputStream *st) {
1523   st->print_cr("Dynamic libraries:");
1524#ifdef RTLD_DI_LINKMAP
1525    Dl_info dli;
1526    void *handle;
1527    Link_map *map;
1528    Link_map *p;
1529
1530    if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) {
1531        st->print_cr("Error: Cannot print dynamic libraries.");
1532        return;
1533    }
1534    handle = dlopen(dli.dli_fname, RTLD_LAZY);
1535    if (handle == NULL) {
1536        st->print_cr("Error: Cannot print dynamic libraries.");
1537        return;
1538    }
1539    dlinfo(handle, RTLD_DI_LINKMAP, &map);
1540    if (map == NULL) {
1541        st->print_cr("Error: Cannot print dynamic libraries.");
1542        return;
1543    }
1544
1545    while (map->l_prev != NULL)
1546        map = map->l_prev;
1547
1548    while (map != NULL) {
1549        st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
1550        map = map->l_next;
1551    }
1552
1553    dlclose(handle);
1554#elif defined(__APPLE__)
1555    uint32_t count;
1556    uint32_t i;
1557
1558    count = _dyld_image_count();
1559    for (i = 1; i < count; i++) {
1560        const char *name = _dyld_get_image_name(i);
1561        intptr_t slide = _dyld_get_image_vmaddr_slide(i);
1562        st->print_cr(PTR_FORMAT " \t%s", slide, name);
1563    }
1564#else
1565   st->print_cr("Error: Cannot print dynamic libraries.");
1566#endif
1567}
1568
1569void os::print_os_info_brief(outputStream* st) {
1570  st->print("Bsd");
1571
1572  os::Posix::print_uname_info(st);
1573}
1574
1575void os::print_os_info(outputStream* st) {
1576  st->print("OS:");
1577  st->print("Bsd");
1578
1579  os::Posix::print_uname_info(st);
1580
1581  os::Posix::print_rlimit_info(st);
1582
1583  os::Posix::print_load_average(st);
1584}
1585
1586void os::pd_print_cpu_info(outputStream* st) {
1587  // Nothing to do for now.
1588}
1589
1590void os::print_memory_info(outputStream* st) {
1591
1592  st->print("Memory:");
1593  st->print(" %dk page", os::vm_page_size()>>10);
1594
1595  st->print(", physical " UINT64_FORMAT "k",
1596            os::physical_memory() >> 10);
1597  st->print("(" UINT64_FORMAT "k free)",
1598            os::available_memory() >> 10);
1599  st->cr();
1600
1601  // meminfo
1602  st->print("\n/proc/meminfo:\n");
1603  _print_ascii_file("/proc/meminfo", st);
1604  st->cr();
1605}
1606
1607// Taken from /usr/include/bits/siginfo.h  Supposed to be architecture specific
1608// but they're the same for all the bsd arch that we support
1609// and they're the same for solaris but there's no common place to put this.
1610const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
1611                          "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
1612                          "ILL_COPROC", "ILL_BADSTK" };
1613
1614const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
1615                          "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
1616                          "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
1617
1618const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
1619
1620const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
1621
1622void os::print_siginfo(outputStream* st, void* siginfo) {
1623  st->print("siginfo:");
1624
1625  const int buflen = 100;
1626  char buf[buflen];
1627  siginfo_t *si = (siginfo_t*)siginfo;
1628  st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
1629  if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
1630    st->print("si_errno=%s", buf);
1631  } else {
1632    st->print("si_errno=%d", si->si_errno);
1633  }
1634  const int c = si->si_code;
1635  assert(c > 0, "unexpected si_code");
1636  switch (si->si_signo) {
1637  case SIGILL:
1638    st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
1639    st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1640    break;
1641  case SIGFPE:
1642    st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
1643    st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1644    break;
1645  case SIGSEGV:
1646    st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
1647    st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1648    break;
1649  case SIGBUS:
1650    st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
1651    st->print(", si_addr=" PTR_FORMAT, si->si_addr);
1652    break;
1653  default:
1654    st->print(", si_code=%d", si->si_code);
1655    // no si_addr
1656  }
1657
1658  if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
1659      UseSharedSpaces) {
1660    FileMapInfo* mapinfo = FileMapInfo::current_info();
1661    if (mapinfo->is_in_shared_space(si->si_addr)) {
1662      st->print("\n\nError accessing class data sharing archive."   \
1663                " Mapped file inaccessible during execution, "      \
1664                " possible disk/network problem.");
1665    }
1666  }
1667  st->cr();
1668}
1669
1670
1671static void print_signal_handler(outputStream* st, int sig,
1672                                 char* buf, size_t buflen);
1673
1674void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1675  st->print_cr("Signal Handlers:");
1676  print_signal_handler(st, SIGSEGV, buf, buflen);
1677  print_signal_handler(st, SIGBUS , buf, buflen);
1678  print_signal_handler(st, SIGFPE , buf, buflen);
1679  print_signal_handler(st, SIGPIPE, buf, buflen);
1680  print_signal_handler(st, SIGXFSZ, buf, buflen);
1681  print_signal_handler(st, SIGILL , buf, buflen);
1682  print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
1683  print_signal_handler(st, SR_signum, buf, buflen);
1684  print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1685  print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1686  print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1687  print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1688}
1689
1690static char saved_jvm_path[MAXPATHLEN] = {0};
1691
1692// Find the full path to the current module, libjvm
1693void os::jvm_path(char *buf, jint buflen) {
1694  // Error checking.
1695  if (buflen < MAXPATHLEN) {
1696    assert(false, "must use a large-enough buffer");
1697    buf[0] = '\0';
1698    return;
1699  }
1700  // Lazy resolve the path to current module.
1701  if (saved_jvm_path[0] != 0) {
1702    strcpy(buf, saved_jvm_path);
1703    return;
1704  }
1705
1706  char dli_fname[MAXPATHLEN];
1707  bool ret = dll_address_to_library_name(
1708                CAST_FROM_FN_PTR(address, os::jvm_path),
1709                dli_fname, sizeof(dli_fname), NULL);
1710  assert(ret != 0, "cannot locate libjvm");
1711  char *rp = realpath(dli_fname, buf);
1712  if (rp == NULL)
1713    return;
1714
1715  if (Arguments::created_by_gamma_launcher()) {
1716    // Support for the gamma launcher.  Typical value for buf is
1717    // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm".  If "/jre/lib/" appears at
1718    // the right place in the string, then assume we are installed in a JDK and
1719    // we're done.  Otherwise, check for a JAVA_HOME environment variable and
1720    // construct a path to the JVM being overridden.
1721
1722    const char *p = buf + strlen(buf) - 1;
1723    for (int count = 0; p > buf && count < 5; ++count) {
1724      for (--p; p > buf && *p != '/'; --p)
1725        /* empty */ ;
1726    }
1727
1728    if (strncmp(p, "/jre/lib/", 9) != 0) {
1729      // Look for JAVA_HOME in the environment.
1730      char* java_home_var = ::getenv("JAVA_HOME");
1731      if (java_home_var != NULL && java_home_var[0] != 0) {
1732        char* jrelib_p;
1733        int len;
1734
1735        // Check the current module name "libjvm"
1736        p = strrchr(buf, '/');
1737        assert(strstr(p, "/libjvm") == p, "invalid library name");
1738
1739        rp = realpath(java_home_var, buf);
1740        if (rp == NULL)
1741          return;
1742
1743        // determine if this is a legacy image or modules image
1744        // modules image doesn't have "jre" subdirectory
1745        len = strlen(buf);
1746        jrelib_p = buf + len;
1747
1748        // Add the appropriate library subdir
1749        snprintf(jrelib_p, buflen-len, "/jre/lib");
1750        if (0 != access(buf, F_OK)) {
1751          snprintf(jrelib_p, buflen-len, "/lib");
1752        }
1753
1754        // Add the appropriate client or server subdir
1755        len = strlen(buf);
1756        jrelib_p = buf + len;
1757        snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1758        if (0 != access(buf, F_OK)) {
1759          snprintf(jrelib_p, buflen-len, "");
1760        }
1761
1762        // If the path exists within JAVA_HOME, add the JVM library name
1763        // to complete the path to JVM being overridden.  Otherwise fallback
1764        // to the path to the current library.
1765        if (0 == access(buf, F_OK)) {
1766          // Use current module name "libjvm"
1767          len = strlen(buf);
1768          snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1769        } else {
1770          // Fall back to path of current library
1771          rp = realpath(dli_fname, buf);
1772          if (rp == NULL)
1773            return;
1774        }
1775      }
1776    }
1777  }
1778
1779  strcpy(saved_jvm_path, buf);
1780}
1781
1782void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1783  // no prefix required, not even "_"
1784}
1785
1786void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1787  // no suffix required
1788}
1789
1790////////////////////////////////////////////////////////////////////////////////
1791// sun.misc.Signal support
1792
1793static volatile jint sigint_count = 0;
1794
1795static void
1796UserHandler(int sig, void *siginfo, void *context) {
1797  // 4511530 - sem_post is serialized and handled by the manager thread. When
1798  // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
1799  // don't want to flood the manager thread with sem_post requests.
1800  if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
1801      return;
1802
1803  // Ctrl-C is pressed during error reporting, likely because the error
1804  // handler fails to abort. Let VM die immediately.
1805  if (sig == SIGINT && is_error_reported()) {
1806     os::die();
1807  }
1808
1809  os::signal_notify(sig);
1810}
1811
1812void* os::user_handler() {
1813  return CAST_FROM_FN_PTR(void*, UserHandler);
1814}
1815
1816extern "C" {
1817  typedef void (*sa_handler_t)(int);
1818  typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1819}
1820
1821void* os::signal(int signal_number, void* handler) {
1822  struct sigaction sigAct, oldSigAct;
1823
1824  sigfillset(&(sigAct.sa_mask));
1825  sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
1826  sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1827
1828  if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1829    // -1 means registration failed
1830    return (void *)-1;
1831  }
1832
1833  return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1834}
1835
1836void os::signal_raise(int signal_number) {
1837  ::raise(signal_number);
1838}
1839
1840/*
1841 * The following code is moved from os.cpp for making this
1842 * code platform specific, which it is by its very nature.
1843 */
1844
1845// Will be modified when max signal is changed to be dynamic
1846int os::sigexitnum_pd() {
1847  return NSIG;
1848}
1849
1850// a counter for each possible signal value
1851static volatile jint pending_signals[NSIG+1] = { 0 };
1852
1853// Bsd(POSIX) specific hand shaking semaphore.
1854#ifdef __APPLE__
1855typedef semaphore_t os_semaphore_t;
1856#define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
1857#define SEM_WAIT(sem)           semaphore_wait(sem)
1858#define SEM_POST(sem)           semaphore_signal(sem)
1859#define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
1860#else
1861typedef sem_t os_semaphore_t;
1862#define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
1863#define SEM_WAIT(sem)           sem_wait(&sem)
1864#define SEM_POST(sem)           sem_post(&sem)
1865#define SEM_DESTROY(sem)        sem_destroy(&sem)
1866#endif
1867
1868class Semaphore : public StackObj {
1869  public:
1870    Semaphore();
1871    ~Semaphore();
1872    void signal();
1873    void wait();
1874    bool trywait();
1875    bool timedwait(unsigned int sec, int nsec);
1876  private:
1877    jlong currenttime() const;
1878    semaphore_t _semaphore;
1879};
1880
1881Semaphore::Semaphore() : _semaphore(0) {
1882  SEM_INIT(_semaphore, 0);
1883}
1884
1885Semaphore::~Semaphore() {
1886  SEM_DESTROY(_semaphore);
1887}
1888
1889void Semaphore::signal() {
1890  SEM_POST(_semaphore);
1891}
1892
1893void Semaphore::wait() {
1894  SEM_WAIT(_semaphore);
1895}
1896
1897jlong Semaphore::currenttime() const {
1898    struct timeval tv;
1899    gettimeofday(&tv, NULL);
1900    return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
1901}
1902
1903#ifdef __APPLE__
1904bool Semaphore::trywait() {
1905  return timedwait(0, 0);
1906}
1907
1908bool Semaphore::timedwait(unsigned int sec, int nsec) {
1909  kern_return_t kr = KERN_ABORTED;
1910  mach_timespec_t waitspec;
1911  waitspec.tv_sec = sec;
1912  waitspec.tv_nsec = nsec;
1913
1914  jlong starttime = currenttime();
1915
1916  kr = semaphore_timedwait(_semaphore, waitspec);
1917  while (kr == KERN_ABORTED) {
1918    jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
1919
1920    jlong current = currenttime();
1921    jlong passedtime = current - starttime;
1922
1923    if (passedtime >= totalwait) {
1924      waitspec.tv_sec = 0;
1925      waitspec.tv_nsec = 0;
1926    } else {
1927      jlong waittime = totalwait - (current - starttime);
1928      waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
1929      waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
1930    }
1931
1932    kr = semaphore_timedwait(_semaphore, waitspec);
1933  }
1934
1935  return kr == KERN_SUCCESS;
1936}
1937
1938#else
1939
1940bool Semaphore::trywait() {
1941  return sem_trywait(&_semaphore) == 0;
1942}
1943
1944bool Semaphore::timedwait(unsigned int sec, int nsec) {
1945  struct timespec ts;
1946  jlong endtime = unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
1947
1948  while (1) {
1949    int result = sem_timedwait(&_semaphore, &ts);
1950    if (result == 0) {
1951      return true;
1952    } else if (errno == EINTR) {
1953      continue;
1954    } else if (errno == ETIMEDOUT) {
1955      return false;
1956    } else {
1957      return false;
1958    }
1959  }
1960}
1961
1962#endif // __APPLE__
1963
1964static os_semaphore_t sig_sem;
1965static Semaphore sr_semaphore;
1966
1967void os::signal_init_pd() {
1968  // Initialize signal structures
1969  ::memset((void*)pending_signals, 0, sizeof(pending_signals));
1970
1971  // Initialize signal semaphore
1972  ::SEM_INIT(sig_sem, 0);
1973}
1974
1975void os::signal_notify(int sig) {
1976  Atomic::inc(&pending_signals[sig]);
1977  ::SEM_POST(sig_sem);
1978}
1979
1980static int check_pending_signals(bool wait) {
1981  Atomic::store(0, &sigint_count);
1982  for (;;) {
1983    for (int i = 0; i < NSIG + 1; i++) {
1984      jint n = pending_signals[i];
1985      if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
1986        return i;
1987      }
1988    }
1989    if (!wait) {
1990      return -1;
1991    }
1992    JavaThread *thread = JavaThread::current();
1993    ThreadBlockInVM tbivm(thread);
1994
1995    bool threadIsSuspended;
1996    do {
1997      thread->set_suspend_equivalent();
1998      // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
1999      ::SEM_WAIT(sig_sem);
2000
2001      // were we externally suspended while we were waiting?
2002      threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2003      if (threadIsSuspended) {
2004        //
2005        // The semaphore has been incremented, but while we were waiting
2006        // another thread suspended us. We don't want to continue running
2007        // while suspended because that would surprise the thread that
2008        // suspended us.
2009        //
2010        ::SEM_POST(sig_sem);
2011
2012        thread->java_suspend_self();
2013      }
2014    } while (threadIsSuspended);
2015  }
2016}
2017
2018int os::signal_lookup() {
2019  return check_pending_signals(false);
2020}
2021
2022int os::signal_wait() {
2023  return check_pending_signals(true);
2024}
2025
2026////////////////////////////////////////////////////////////////////////////////
2027// Virtual Memory
2028
2029int os::vm_page_size() {
2030  // Seems redundant as all get out
2031  assert(os::Bsd::page_size() != -1, "must call os::init");
2032  return os::Bsd::page_size();
2033}
2034
2035// Solaris allocates memory by pages.
2036int os::vm_allocation_granularity() {
2037  assert(os::Bsd::page_size() != -1, "must call os::init");
2038  return os::Bsd::page_size();
2039}
2040
2041// Rationale behind this function:
2042//  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2043//  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2044//  samples for JITted code. Here we create private executable mapping over the code cache
2045//  and then we can use standard (well, almost, as mapping can change) way to provide
2046//  info for the reporting script by storing timestamp and location of symbol
2047void bsd_wrap_code(char* base, size_t size) {
2048  static volatile jint cnt = 0;
2049
2050  if (!UseOprofile) {
2051    return;
2052  }
2053
2054  char buf[PATH_MAX + 1];
2055  int num = Atomic::add(1, &cnt);
2056
2057  snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
2058           os::get_temp_directory(), os::current_process_id(), num);
2059  unlink(buf);
2060
2061  int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2062
2063  if (fd != -1) {
2064    off_t rv = ::lseek(fd, size-2, SEEK_SET);
2065    if (rv != (off_t)-1) {
2066      if (::write(fd, "", 1) == 1) {
2067        mmap(base, size,
2068             PROT_READ|PROT_WRITE|PROT_EXEC,
2069             MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2070      }
2071    }
2072    ::close(fd);
2073    unlink(buf);
2074  }
2075}
2076
2077static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2078                                    int err) {
2079  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2080          ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
2081          strerror(err), err);
2082}
2083
2084// NOTE: Bsd kernel does not really reserve the pages for us.
2085//       All it does is to check if there are enough free pages
2086//       left at the time of mmap(). This could be a potential
2087//       problem.
2088bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2089  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2090#ifdef __OpenBSD__
2091  // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2092  if (::mprotect(addr, size, prot) == 0) {
2093    return true;
2094  }
2095#else
2096  uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2097                                   MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2098  if (res != (uintptr_t) MAP_FAILED) {
2099    return true;
2100  }
2101#endif
2102
2103  // Warn about any commit errors we see in non-product builds just
2104  // in case mmap() doesn't work as described on the man page.
2105  NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
2106
2107  return false;
2108}
2109
2110bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2111                       bool exec) {
2112  // alignment_hint is ignored on this OS
2113  return pd_commit_memory(addr, size, exec);
2114}
2115
2116void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2117                                  const char* mesg) {
2118  assert(mesg != NULL, "mesg must be specified");
2119  if (!pd_commit_memory(addr, size, exec)) {
2120    // add extra info in product mode for vm_exit_out_of_memory():
2121    PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
2122    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2123  }
2124}
2125
2126void os::pd_commit_memory_or_exit(char* addr, size_t size,
2127                                  size_t alignment_hint, bool exec,
2128                                  const char* mesg) {
2129  // alignment_hint is ignored on this OS
2130  pd_commit_memory_or_exit(addr, size, exec, mesg);
2131}
2132
2133void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2134}
2135
2136void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2137  ::madvise(addr, bytes, MADV_DONTNEED);
2138}
2139
2140void os::numa_make_global(char *addr, size_t bytes) {
2141}
2142
2143void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2144}
2145
2146bool os::numa_topology_changed()   { return false; }
2147
2148size_t os::numa_get_groups_num() {
2149  return 1;
2150}
2151
2152int os::numa_get_group_id() {
2153  return 0;
2154}
2155
2156size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2157  if (size > 0) {
2158    ids[0] = 0;
2159    return 1;
2160  }
2161  return 0;
2162}
2163
2164bool os::get_page_info(char *start, page_info* info) {
2165  return false;
2166}
2167
2168char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2169  return end;
2170}
2171
2172
2173bool os::pd_uncommit_memory(char* addr, size_t size) {
2174#ifdef __OpenBSD__
2175  // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2176  return ::mprotect(addr, size, PROT_NONE) == 0;
2177#else
2178  uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2179                MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2180  return res  != (uintptr_t) MAP_FAILED;
2181#endif
2182}
2183
2184bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2185  return os::commit_memory(addr, size, !ExecMem);
2186}
2187
2188// If this is a growable mapping, remove the guard pages entirely by
2189// munmap()ping them.  If not, just call uncommit_memory().
2190bool os::remove_stack_guard_pages(char* addr, size_t size) {
2191  return os::uncommit_memory(addr, size);
2192}
2193
2194static address _highest_vm_reserved_address = NULL;
2195
2196// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2197// at 'requested_addr'. If there are existing memory mappings at the same
2198// location, however, they will be overwritten. If 'fixed' is false,
2199// 'requested_addr' is only treated as a hint, the return value may or
2200// may not start from the requested address. Unlike Bsd mmap(), this
2201// function returns NULL to indicate failure.
2202static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2203  char * addr;
2204  int flags;
2205
2206  flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2207  if (fixed) {
2208    assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2209    flags |= MAP_FIXED;
2210  }
2211
2212  // Map reserved/uncommitted pages PROT_NONE so we fail early if we
2213  // touch an uncommitted page. Otherwise, the read/write might
2214  // succeed if we have enough swap space to back the physical page.
2215  addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
2216                       flags, -1, 0);
2217
2218  if (addr != MAP_FAILED) {
2219    // anon_mmap() should only get called during VM initialization,
2220    // don't need lock (actually we can skip locking even it can be called
2221    // from multiple threads, because _highest_vm_reserved_address is just a
2222    // hint about the upper limit of non-stack memory regions.)
2223    if ((address)addr + bytes > _highest_vm_reserved_address) {
2224      _highest_vm_reserved_address = (address)addr + bytes;
2225    }
2226  }
2227
2228  return addr == MAP_FAILED ? NULL : addr;
2229}
2230
2231// Don't update _highest_vm_reserved_address, because there might be memory
2232// regions above addr + size. If so, releasing a memory region only creates
2233// a hole in the address space, it doesn't help prevent heap-stack collision.
2234//
2235static int anon_munmap(char * addr, size_t size) {
2236  return ::munmap(addr, size) == 0;
2237}
2238
2239char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2240                         size_t alignment_hint) {
2241  return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2242}
2243
2244bool os::pd_release_memory(char* addr, size_t size) {
2245  return anon_munmap(addr, size);
2246}
2247
2248static bool bsd_mprotect(char* addr, size_t size, int prot) {
2249  // Bsd wants the mprotect address argument to be page aligned.
2250  char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
2251
2252  // According to SUSv3, mprotect() should only be used with mappings
2253  // established by mmap(), and mmap() always maps whole pages. Unaligned
2254  // 'addr' likely indicates problem in the VM (e.g. trying to change
2255  // protection of malloc'ed or statically allocated memory). Check the
2256  // caller if you hit this assert.
2257  assert(addr == bottom, "sanity check");
2258
2259  size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2260  return ::mprotect(bottom, size, prot) == 0;
2261}
2262
2263// Set protections specified
2264bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2265                        bool is_committed) {
2266  unsigned int p = 0;
2267  switch (prot) {
2268  case MEM_PROT_NONE: p = PROT_NONE; break;
2269  case MEM_PROT_READ: p = PROT_READ; break;
2270  case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2271  case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2272  default:
2273    ShouldNotReachHere();
2274  }
2275  // is_committed is unused.
2276  return bsd_mprotect(addr, bytes, p);
2277}
2278
2279bool os::guard_memory(char* addr, size_t size) {
2280  return bsd_mprotect(addr, size, PROT_NONE);
2281}
2282
2283bool os::unguard_memory(char* addr, size_t size) {
2284  return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2285}
2286
2287bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2288  return false;
2289}
2290
2291// Large page support
2292
2293static size_t _large_page_size = 0;
2294
2295void os::large_page_init() {
2296}
2297
2298
2299char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
2300  // "exec" is passed in but not used.  Creating the shared image for
2301  // the code cache doesn't have an SHM_X executable permission to check.
2302  assert(UseLargePages && UseSHM, "only for SHM large pages");
2303
2304  key_t key = IPC_PRIVATE;
2305  char *addr;
2306
2307  bool warn_on_failure = UseLargePages &&
2308                        (!FLAG_IS_DEFAULT(UseLargePages) ||
2309                         !FLAG_IS_DEFAULT(LargePageSizeInBytes)
2310                        );
2311  char msg[128];
2312
2313  // Create a large shared memory region to attach to based on size.
2314  // Currently, size is the total size of the heap
2315  int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
2316  if (shmid == -1) {
2317     // Possible reasons for shmget failure:
2318     // 1. shmmax is too small for Java heap.
2319     //    > check shmmax value: cat /proc/sys/kernel/shmmax
2320     //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
2321     // 2. not enough large page memory.
2322     //    > check available large pages: cat /proc/meminfo
2323     //    > increase amount of large pages:
2324     //          echo new_value > /proc/sys/vm/nr_hugepages
2325     //      Note 1: different Bsd may use different name for this property,
2326     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
2327     //      Note 2: it's possible there's enough physical memory available but
2328     //            they are so fragmented after a long run that they can't
2329     //            coalesce into large pages. Try to reserve large pages when
2330     //            the system is still "fresh".
2331     if (warn_on_failure) {
2332       jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
2333       warning(msg);
2334     }
2335     return NULL;
2336  }
2337
2338  // attach to the region
2339  addr = (char*)shmat(shmid, req_addr, 0);
2340  int err = errno;
2341
2342  // Remove shmid. If shmat() is successful, the actual shared memory segment
2343  // will be deleted when it's detached by shmdt() or when the process
2344  // terminates. If shmat() is not successful this will remove the shared
2345  // segment immediately.
2346  shmctl(shmid, IPC_RMID, NULL);
2347
2348  if ((intptr_t)addr == -1) {
2349     if (warn_on_failure) {
2350       jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
2351       warning(msg);
2352     }
2353     return NULL;
2354  }
2355
2356  // The memory is committed
2357  address pc = CALLER_PC;
2358  MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
2359  MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
2360
2361  return addr;
2362}
2363
2364bool os::release_memory_special(char* base, size_t bytes) {
2365  // detaching the SHM segment will also delete it, see reserve_memory_special()
2366  int rslt = shmdt(base);
2367  if (rslt == 0) {
2368    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
2369    MemTracker::record_virtual_memory_release((address)base, bytes);
2370    return true;
2371  } else {
2372    return false;
2373  }
2374
2375}
2376
2377size_t os::large_page_size() {
2378  return _large_page_size;
2379}
2380
2381// HugeTLBFS allows application to commit large page memory on demand;
2382// with SysV SHM the entire memory region must be allocated as shared
2383// memory.
2384bool os::can_commit_large_page_memory() {
2385  return UseHugeTLBFS;
2386}
2387
2388bool os::can_execute_large_page_memory() {
2389  return UseHugeTLBFS;
2390}
2391
2392// Reserve memory at an arbitrary address, only if that area is
2393// available (and not reserved for something else).
2394
2395char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2396  const int max_tries = 10;
2397  char* base[max_tries];
2398  size_t size[max_tries];
2399  const size_t gap = 0x000000;
2400
2401  // Assert only that the size is a multiple of the page size, since
2402  // that's all that mmap requires, and since that's all we really know
2403  // about at this low abstraction level.  If we need higher alignment,
2404  // we can either pass an alignment to this method or verify alignment
2405  // in one of the methods further up the call chain.  See bug 5044738.
2406  assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2407
2408  // Repeatedly allocate blocks until the block is allocated at the
2409  // right spot. Give up after max_tries. Note that reserve_memory() will
2410  // automatically update _highest_vm_reserved_address if the call is
2411  // successful. The variable tracks the highest memory address every reserved
2412  // by JVM. It is used to detect heap-stack collision if running with
2413  // fixed-stack BsdThreads. Because here we may attempt to reserve more
2414  // space than needed, it could confuse the collision detecting code. To
2415  // solve the problem, save current _highest_vm_reserved_address and
2416  // calculate the correct value before return.
2417  address old_highest = _highest_vm_reserved_address;
2418
2419  // Bsd mmap allows caller to pass an address as hint; give it a try first,
2420  // if kernel honors the hint then we can return immediately.
2421  char * addr = anon_mmap(requested_addr, bytes, false);
2422  if (addr == requested_addr) {
2423     return requested_addr;
2424  }
2425
2426  if (addr != NULL) {
2427     // mmap() is successful but it fails to reserve at the requested address
2428     anon_munmap(addr, bytes);
2429  }
2430
2431  int i;
2432  for (i = 0; i < max_tries; ++i) {
2433    base[i] = reserve_memory(bytes);
2434
2435    if (base[i] != NULL) {
2436      // Is this the block we wanted?
2437      if (base[i] == requested_addr) {
2438        size[i] = bytes;
2439        break;
2440      }
2441
2442      // Does this overlap the block we wanted? Give back the overlapped
2443      // parts and try again.
2444
2445      size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2446      if (top_overlap >= 0 && top_overlap < bytes) {
2447        unmap_memory(base[i], top_overlap);
2448        base[i] += top_overlap;
2449        size[i] = bytes - top_overlap;
2450      } else {
2451        size_t bottom_overlap = base[i] + bytes - requested_addr;
2452        if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2453          unmap_memory(requested_addr, bottom_overlap);
2454          size[i] = bytes - bottom_overlap;
2455        } else {
2456          size[i] = bytes;
2457        }
2458      }
2459    }
2460  }
2461
2462  // Give back the unused reserved pieces.
2463
2464  for (int j = 0; j < i; ++j) {
2465    if (base[j] != NULL) {
2466      unmap_memory(base[j], size[j]);
2467    }
2468  }
2469
2470  if (i < max_tries) {
2471    _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
2472    return requested_addr;
2473  } else {
2474    _highest_vm_reserved_address = old_highest;
2475    return NULL;
2476  }
2477}
2478
2479size_t os::read(int fd, void *buf, unsigned int nBytes) {
2480  RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
2481}
2482
2483// TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
2484// Solaris uses poll(), bsd uses park().
2485// Poll() is likely a better choice, assuming that Thread.interrupt()
2486// generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
2487// SIGSEGV, see 4355769.
2488
2489int os::sleep(Thread* thread, jlong millis, bool interruptible) {
2490  assert(thread == Thread::current(),  "thread consistency check");
2491
2492  ParkEvent * const slp = thread->_SleepEvent ;
2493  slp->reset() ;
2494  OrderAccess::fence() ;
2495
2496  if (interruptible) {
2497    jlong prevtime = javaTimeNanos();
2498
2499    for (;;) {
2500      if (os::is_interrupted(thread, true)) {
2501        return OS_INTRPT;
2502      }
2503
2504      jlong newtime = javaTimeNanos();
2505
2506      if (newtime - prevtime < 0) {
2507        // time moving backwards, should only happen if no monotonic clock
2508        // not a guarantee() because JVM should not abort on kernel/glibc bugs
2509        assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2510      } else {
2511        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2512      }
2513
2514      if(millis <= 0) {
2515        return OS_OK;
2516      }
2517
2518      prevtime = newtime;
2519
2520      {
2521        assert(thread->is_Java_thread(), "sanity check");
2522        JavaThread *jt = (JavaThread *) thread;
2523        ThreadBlockInVM tbivm(jt);
2524        OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
2525
2526        jt->set_suspend_equivalent();
2527        // cleared by handle_special_suspend_equivalent_condition() or
2528        // java_suspend_self() via check_and_wait_while_suspended()
2529
2530        slp->park(millis);
2531
2532        // were we externally suspended while we were waiting?
2533        jt->check_and_wait_while_suspended();
2534      }
2535    }
2536  } else {
2537    OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
2538    jlong prevtime = javaTimeNanos();
2539
2540    for (;;) {
2541      // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
2542      // the 1st iteration ...
2543      jlong newtime = javaTimeNanos();
2544
2545      if (newtime - prevtime < 0) {
2546        // time moving backwards, should only happen if no monotonic clock
2547        // not a guarantee() because JVM should not abort on kernel/glibc bugs
2548        assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
2549      } else {
2550        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2551      }
2552
2553      if(millis <= 0) break ;
2554
2555      prevtime = newtime;
2556      slp->park(millis);
2557    }
2558    return OS_OK ;
2559  }
2560}
2561
2562int os::naked_sleep() {
2563  // %% make the sleep time an integer flag. for now use 1 millisec.
2564  return os::sleep(Thread::current(), 1, false);
2565}
2566
2567// Sleep forever; naked call to OS-specific sleep; use with CAUTION
2568void os::infinite_sleep() {
2569  while (true) {    // sleep forever ...
2570    ::sleep(100);   // ... 100 seconds at a time
2571  }
2572}
2573
2574// Used to convert frequent JVM_Yield() to nops
2575bool os::dont_yield() {
2576  return DontYieldALot;
2577}
2578
2579void os::yield() {
2580  sched_yield();
2581}
2582
2583os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
2584
2585void os::yield_all(int attempts) {
2586  // Yields to all threads, including threads with lower priorities
2587  // Threads on Bsd are all with same priority. The Solaris style
2588  // os::yield_all() with nanosleep(1ms) is not necessary.
2589  sched_yield();
2590}
2591
2592// Called from the tight loops to possibly influence time-sharing heuristics
2593void os::loop_breaker(int attempts) {
2594  os::yield_all(attempts);
2595}
2596
2597////////////////////////////////////////////////////////////////////////////////
2598// thread priority support
2599
2600// Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2601// only supports dynamic priority, static priority must be zero. For real-time
2602// applications, Bsd supports SCHED_RR which allows static priority (1-99).
2603// However, for large multi-threaded applications, SCHED_RR is not only slower
2604// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2605// of 5 runs - Sep 2005).
2606//
2607// The following code actually changes the niceness of kernel-thread/LWP. It
2608// has an assumption that setpriority() only modifies one kernel-thread/LWP,
2609// not the entire user process, and user level threads are 1:1 mapped to kernel
2610// threads. It has always been the case, but could change in the future. For
2611// this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2612// It is only used when ThreadPriorityPolicy=1 and requires root privilege.
2613
2614#if !defined(__APPLE__)
2615int os::java_to_os_priority[CriticalPriority + 1] = {
2616  19,              // 0 Entry should never be used
2617
2618   0,              // 1 MinPriority
2619   3,              // 2
2620   6,              // 3
2621
2622  10,              // 4
2623  15,              // 5 NormPriority
2624  18,              // 6
2625
2626  21,              // 7
2627  25,              // 8
2628  28,              // 9 NearMaxPriority
2629
2630  31,              // 10 MaxPriority
2631
2632  31               // 11 CriticalPriority
2633};
2634#else
2635/* Using Mach high-level priority assignments */
2636int os::java_to_os_priority[CriticalPriority + 1] = {
2637   0,              // 0 Entry should never be used (MINPRI_USER)
2638
2639  27,              // 1 MinPriority
2640  28,              // 2
2641  29,              // 3
2642
2643  30,              // 4
2644  31,              // 5 NormPriority (BASEPRI_DEFAULT)
2645  32,              // 6
2646
2647  33,              // 7
2648  34,              // 8
2649  35,              // 9 NearMaxPriority
2650
2651  36,              // 10 MaxPriority
2652
2653  36               // 11 CriticalPriority
2654};
2655#endif
2656
2657static int prio_init() {
2658  if (ThreadPriorityPolicy == 1) {
2659    // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
2660    // if effective uid is not root. Perhaps, a more elegant way of doing
2661    // this is to test CAP_SYS_NICE capability, but that will require libcap.so
2662    if (geteuid() != 0) {
2663      if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
2664        warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
2665      }
2666      ThreadPriorityPolicy = 0;
2667    }
2668  }
2669  if (UseCriticalJavaThreadPriority) {
2670    os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2671  }
2672  return 0;
2673}
2674
2675OSReturn os::set_native_priority(Thread* thread, int newpri) {
2676  if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
2677
2678#ifdef __OpenBSD__
2679  // OpenBSD pthread_setprio starves low priority threads
2680  return OS_OK;
2681#elif defined(__FreeBSD__)
2682  int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2683#elif defined(__APPLE__) || defined(__NetBSD__)
2684  struct sched_param sp;
2685  int policy;
2686  pthread_t self = pthread_self();
2687
2688  if (pthread_getschedparam(self, &policy, &sp) != 0)
2689    return OS_ERR;
2690
2691  sp.sched_priority = newpri;
2692  if (pthread_setschedparam(self, policy, &sp) != 0)
2693    return OS_ERR;
2694
2695  return OS_OK;
2696#else
2697  int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2698  return (ret == 0) ? OS_OK : OS_ERR;
2699#endif
2700}
2701
2702OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2703  if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
2704    *priority_ptr = java_to_os_priority[NormPriority];
2705    return OS_OK;
2706  }
2707
2708  errno = 0;
2709#if defined(__OpenBSD__) || defined(__FreeBSD__)
2710  *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2711#elif defined(__APPLE__) || defined(__NetBSD__)
2712  int policy;
2713  struct sched_param sp;
2714
2715  pthread_getschedparam(pthread_self(), &policy, &sp);
2716  *priority_ptr = sp.sched_priority;
2717#else
2718  *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2719#endif
2720  return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2721}
2722
2723// Hint to the underlying OS that a task switch would not be good.
2724// Void return because it's a hint and can fail.
2725void os::hint_no_preempt() {}
2726
2727////////////////////////////////////////////////////////////////////////////////
2728// suspend/resume support
2729
2730//  the low-level signal-based suspend/resume support is a remnant from the
2731//  old VM-suspension that used to be for java-suspension, safepoints etc,
2732//  within hotspot. Now there is a single use-case for this:
2733//    - calling get_thread_pc() on the VMThread by the flat-profiler task
2734//      that runs in the watcher thread.
2735//  The remaining code is greatly simplified from the more general suspension
2736//  code that used to be used.
2737//
2738//  The protocol is quite simple:
2739//  - suspend:
2740//      - sends a signal to the target thread
2741//      - polls the suspend state of the osthread using a yield loop
2742//      - target thread signal handler (SR_handler) sets suspend state
2743//        and blocks in sigsuspend until continued
2744//  - resume:
2745//      - sets target osthread state to continue
2746//      - sends signal to end the sigsuspend loop in the SR_handler
2747//
2748//  Note that the SR_lock plays no role in this suspend/resume protocol.
2749//
2750
2751static void resume_clear_context(OSThread *osthread) {
2752  osthread->set_ucontext(NULL);
2753  osthread->set_siginfo(NULL);
2754}
2755
2756static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2757  osthread->set_ucontext(context);
2758  osthread->set_siginfo(siginfo);
2759}
2760
2761//
2762// Handler function invoked when a thread's execution is suspended or
2763// resumed. We have to be careful that only async-safe functions are
2764// called here (Note: most pthread functions are not async safe and
2765// should be avoided.)
2766//
2767// Note: sigwait() is a more natural fit than sigsuspend() from an
2768// interface point of view, but sigwait() prevents the signal hander
2769// from being run. libpthread would get very confused by not having
2770// its signal handlers run and prevents sigwait()'s use with the
2771// mutex granting granting signal.
2772//
2773// Currently only ever called on the VMThread or JavaThread
2774//
2775static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2776  // Save and restore errno to avoid confusing native code with EINTR
2777  // after sigsuspend.
2778  int old_errno = errno;
2779
2780  Thread* thread = Thread::current();
2781  OSThread* osthread = thread->osthread();
2782  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
2783
2784  os::SuspendResume::State current = osthread->sr.state();
2785  if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
2786    suspend_save_context(osthread, siginfo, context);
2787
2788    // attempt to switch the state, we assume we had a SUSPEND_REQUEST
2789    os::SuspendResume::State state = osthread->sr.suspended();
2790    if (state == os::SuspendResume::SR_SUSPENDED) {
2791      sigset_t suspend_set;  // signals for sigsuspend()
2792
2793      // get current set of blocked signals and unblock resume signal
2794      pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2795      sigdelset(&suspend_set, SR_signum);
2796
2797      sr_semaphore.signal();
2798      // wait here until we are resumed
2799      while (1) {
2800        sigsuspend(&suspend_set);
2801
2802        os::SuspendResume::State result = osthread->sr.running();
2803        if (result == os::SuspendResume::SR_RUNNING) {
2804          sr_semaphore.signal();
2805          break;
2806        } else if (result != os::SuspendResume::SR_SUSPENDED) {
2807          ShouldNotReachHere();
2808        }
2809      }
2810
2811    } else if (state == os::SuspendResume::SR_RUNNING) {
2812      // request was cancelled, continue
2813    } else {
2814      ShouldNotReachHere();
2815    }
2816
2817    resume_clear_context(osthread);
2818  } else if (current == os::SuspendResume::SR_RUNNING) {
2819    // request was cancelled, continue
2820  } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
2821    // ignore
2822  } else {
2823    // ignore
2824  }
2825
2826  errno = old_errno;
2827}
2828
2829
2830static int SR_initialize() {
2831  struct sigaction act;
2832  char *s;
2833  /* Get signal number to use for suspend/resume */
2834  if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2835    int sig = ::strtol(s, 0, 10);
2836    if (sig > 0 || sig < NSIG) {
2837        SR_signum = sig;
2838    }
2839  }
2840
2841  assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2842        "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2843
2844  sigemptyset(&SR_sigset);
2845  sigaddset(&SR_sigset, SR_signum);
2846
2847  /* Set up signal handler for suspend/resume */
2848  act.sa_flags = SA_RESTART|SA_SIGINFO;
2849  act.sa_handler = (void (*)(int)) SR_handler;
2850
2851  // SR_signum is blocked by default.
2852  // 4528190 - We also need to block pthread restart signal (32 on all
2853  // supported Bsd platforms). Note that BsdThreads need to block
2854  // this signal for all threads to work properly. So we don't have
2855  // to use hard-coded signal number when setting up the mask.
2856  pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2857
2858  if (sigaction(SR_signum, &act, 0) == -1) {
2859    return -1;
2860  }
2861
2862  // Save signal flag
2863  os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2864  return 0;
2865}
2866
2867static int sr_notify(OSThread* osthread) {
2868  int status = pthread_kill(osthread->pthread_id(), SR_signum);
2869  assert_status(status == 0, status, "pthread_kill");
2870  return status;
2871}
2872
2873// "Randomly" selected value for how long we want to spin
2874// before bailing out on suspending a thread, also how often
2875// we send a signal to a thread we want to resume
2876static const int RANDOMLY_LARGE_INTEGER = 1000000;
2877static const int RANDOMLY_LARGE_INTEGER2 = 100;
2878
2879// returns true on success and false on error - really an error is fatal
2880// but this seems the normal response to library errors
2881static bool do_suspend(OSThread* osthread) {
2882  assert(osthread->sr.is_running(), "thread should be running");
2883  assert(!sr_semaphore.trywait(), "semaphore has invalid state");
2884
2885  // mark as suspended and send signal
2886  if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
2887    // failed to switch, state wasn't running?
2888    ShouldNotReachHere();
2889    return false;
2890  }
2891
2892  if (sr_notify(osthread) != 0) {
2893    ShouldNotReachHere();
2894  }
2895
2896  // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
2897  while (true) {
2898    if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2899      break;
2900    } else {
2901      // timeout
2902      os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
2903      if (cancelled == os::SuspendResume::SR_RUNNING) {
2904        return false;
2905      } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
2906        // make sure that we consume the signal on the semaphore as well
2907        sr_semaphore.wait();
2908        break;
2909      } else {
2910        ShouldNotReachHere();
2911        return false;
2912      }
2913    }
2914  }
2915
2916  guarantee(osthread->sr.is_suspended(), "Must be suspended");
2917  return true;
2918}
2919
2920static void do_resume(OSThread* osthread) {
2921  assert(osthread->sr.is_suspended(), "thread should be suspended");
2922  assert(!sr_semaphore.trywait(), "invalid semaphore state");
2923
2924  if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
2925    // failed to switch to WAKEUP_REQUEST
2926    ShouldNotReachHere();
2927    return;
2928  }
2929
2930  while (true) {
2931    if (sr_notify(osthread) == 0) {
2932      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2933        if (osthread->sr.is_running()) {
2934          return;
2935        }
2936      }
2937    } else {
2938      ShouldNotReachHere();
2939    }
2940  }
2941
2942  guarantee(osthread->sr.is_running(), "Must be running!");
2943}
2944
2945////////////////////////////////////////////////////////////////////////////////
2946// interrupt support
2947
2948void os::interrupt(Thread* thread) {
2949  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
2950    "possibility of dangling Thread pointer");
2951
2952  OSThread* osthread = thread->osthread();
2953
2954  if (!osthread->interrupted()) {
2955    osthread->set_interrupted(true);
2956    // More than one thread can get here with the same value of osthread,
2957    // resulting in multiple notifications.  We do, however, want the store
2958    // to interrupted() to be visible to other threads before we execute unpark().
2959    OrderAccess::fence();
2960    ParkEvent * const slp = thread->_SleepEvent ;
2961    if (slp != NULL) slp->unpark() ;
2962  }
2963
2964  // For JSR166. Unpark even if interrupt status already was set
2965  if (thread->is_Java_thread())
2966    ((JavaThread*)thread)->parker()->unpark();
2967
2968  ParkEvent * ev = thread->_ParkEvent ;
2969  if (ev != NULL) ev->unpark() ;
2970
2971}
2972
2973bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
2974  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
2975    "possibility of dangling Thread pointer");
2976
2977  OSThread* osthread = thread->osthread();
2978
2979  bool interrupted = osthread->interrupted();
2980
2981  if (interrupted && clear_interrupted) {
2982    osthread->set_interrupted(false);
2983    // consider thread->_SleepEvent->reset() ... optional optimization
2984  }
2985
2986  return interrupted;
2987}
2988
2989///////////////////////////////////////////////////////////////////////////////////
2990// signal handling (except suspend/resume)
2991
2992// This routine may be used by user applications as a "hook" to catch signals.
2993// The user-defined signal handler must pass unrecognized signals to this
2994// routine, and if it returns true (non-zero), then the signal handler must
2995// return immediately.  If the flag "abort_if_unrecognized" is true, then this
2996// routine will never retun false (zero), but instead will execute a VM panic
2997// routine kill the process.
2998//
2999// If this routine returns false, it is OK to call it again.  This allows
3000// the user-defined signal handler to perform checks either before or after
3001// the VM performs its own checks.  Naturally, the user code would be making
3002// a serious error if it tried to handle an exception (such as a null check
3003// or breakpoint) that the VM was generating for its own correct operation.
3004//
3005// This routine may recognize any of the following kinds of signals:
3006//    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
3007// It should be consulted by handlers for any of those signals.
3008//
3009// The caller of this routine must pass in the three arguments supplied
3010// to the function referred to in the "sa_sigaction" (not the "sa_handler")
3011// field of the structure passed to sigaction().  This routine assumes that
3012// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3013//
3014// Note that the VM will print warnings if it detects conflicting signal
3015// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3016//
3017extern "C" JNIEXPORT int
3018JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
3019                        void* ucontext, int abort_if_unrecognized);
3020
3021void signalHandler(int sig, siginfo_t* info, void* uc) {
3022  assert(info != NULL && uc != NULL, "it must be old kernel");
3023  int orig_errno = errno;  // Preserve errno value over signal handler.
3024  JVM_handle_bsd_signal(sig, info, uc, true);
3025  errno = orig_errno;
3026}
3027
3028
3029// This boolean allows users to forward their own non-matching signals
3030// to JVM_handle_bsd_signal, harmlessly.
3031bool os::Bsd::signal_handlers_are_installed = false;
3032
3033// For signal-chaining
3034struct sigaction os::Bsd::sigact[MAXSIGNUM];
3035unsigned int os::Bsd::sigs = 0;
3036bool os::Bsd::libjsig_is_loaded = false;
3037typedef struct sigaction *(*get_signal_t)(int);
3038get_signal_t os::Bsd::get_signal_action = NULL;
3039
3040struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
3041  struct sigaction *actp = NULL;
3042
3043  if (libjsig_is_loaded) {
3044    // Retrieve the old signal handler from libjsig
3045    actp = (*get_signal_action)(sig);
3046  }
3047  if (actp == NULL) {
3048    // Retrieve the preinstalled signal handler from jvm
3049    actp = get_preinstalled_handler(sig);
3050  }
3051
3052  return actp;
3053}
3054
3055static bool call_chained_handler(struct sigaction *actp, int sig,
3056                                 siginfo_t *siginfo, void *context) {
3057  // Call the old signal handler
3058  if (actp->sa_handler == SIG_DFL) {
3059    // It's more reasonable to let jvm treat it as an unexpected exception
3060    // instead of taking the default action.
3061    return false;
3062  } else if (actp->sa_handler != SIG_IGN) {
3063    if ((actp->sa_flags & SA_NODEFER) == 0) {
3064      // automaticlly block the signal
3065      sigaddset(&(actp->sa_mask), sig);
3066    }
3067
3068    sa_handler_t hand;
3069    sa_sigaction_t sa;
3070    bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3071    // retrieve the chained handler
3072    if (siginfo_flag_set) {
3073      sa = actp->sa_sigaction;
3074    } else {
3075      hand = actp->sa_handler;
3076    }
3077
3078    if ((actp->sa_flags & SA_RESETHAND) != 0) {
3079      actp->sa_handler = SIG_DFL;
3080    }
3081
3082    // try to honor the signal mask
3083    sigset_t oset;
3084    pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3085
3086    // call into the chained handler
3087    if (siginfo_flag_set) {
3088      (*sa)(sig, siginfo, context);
3089    } else {
3090      (*hand)(sig);
3091    }
3092
3093    // restore the signal mask
3094    pthread_sigmask(SIG_SETMASK, &oset, 0);
3095  }
3096  // Tell jvm's signal handler the signal is taken care of.
3097  return true;
3098}
3099
3100bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3101  bool chained = false;
3102  // signal-chaining
3103  if (UseSignalChaining) {
3104    struct sigaction *actp = get_chained_signal_action(sig);
3105    if (actp != NULL) {
3106      chained = call_chained_handler(actp, sig, siginfo, context);
3107    }
3108  }
3109  return chained;
3110}
3111
3112struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
3113  if ((( (unsigned int)1 << sig ) & sigs) != 0) {
3114    return &sigact[sig];
3115  }
3116  return NULL;
3117}
3118
3119void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
3120  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3121  sigact[sig] = oldAct;
3122  sigs |= (unsigned int)1 << sig;
3123}
3124
3125// for diagnostic
3126int os::Bsd::sigflags[MAXSIGNUM];
3127
3128int os::Bsd::get_our_sigflags(int sig) {
3129  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3130  return sigflags[sig];
3131}
3132
3133void os::Bsd::set_our_sigflags(int sig, int flags) {
3134  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3135  sigflags[sig] = flags;
3136}
3137
3138void os::Bsd::set_signal_handler(int sig, bool set_installed) {
3139  // Check for overwrite.
3140  struct sigaction oldAct;
3141  sigaction(sig, (struct sigaction*)NULL, &oldAct);
3142
3143  void* oldhand = oldAct.sa_sigaction
3144                ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
3145                : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
3146  if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3147      oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3148      oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
3149    if (AllowUserSignalHandlers || !set_installed) {
3150      // Do not overwrite; user takes responsibility to forward to us.
3151      return;
3152    } else if (UseSignalChaining) {
3153      // save the old handler in jvm
3154      save_preinstalled_handler(sig, oldAct);
3155      // libjsig also interposes the sigaction() call below and saves the
3156      // old sigaction on it own.
3157    } else {
3158      fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
3159                    "%#lx for signal %d.", (long)oldhand, sig));
3160    }
3161  }
3162
3163  struct sigaction sigAct;
3164  sigfillset(&(sigAct.sa_mask));
3165  sigAct.sa_handler = SIG_DFL;
3166  if (!set_installed) {
3167    sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3168  } else {
3169    sigAct.sa_sigaction = signalHandler;
3170    sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3171  }
3172#if __APPLE__
3173  // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
3174  // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
3175  // if the signal handler declares it will handle it on alternate stack.
3176  // Notice we only declare we will handle it on alt stack, but we are not
3177  // actually going to use real alt stack - this is just a workaround.
3178  // Please see ux_exception.c, method catch_mach_exception_raise for details
3179  // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
3180  if (sig == SIGSEGV) {
3181    sigAct.sa_flags |= SA_ONSTACK;
3182  }
3183#endif
3184
3185  // Save flags, which are set by ours
3186  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
3187  sigflags[sig] = sigAct.sa_flags;
3188
3189  int ret = sigaction(sig, &sigAct, &oldAct);
3190  assert(ret == 0, "check");
3191
3192  void* oldhand2  = oldAct.sa_sigaction
3193                  ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3194                  : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3195  assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3196}
3197
3198// install signal handlers for signals that HotSpot needs to
3199// handle in order to support Java-level exception handling.
3200
3201void os::Bsd::install_signal_handlers() {
3202  if (!signal_handlers_are_installed) {
3203    signal_handlers_are_installed = true;
3204
3205    // signal-chaining
3206    typedef void (*signal_setting_t)();
3207    signal_setting_t begin_signal_setting = NULL;
3208    signal_setting_t end_signal_setting = NULL;
3209    begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3210                             dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
3211    if (begin_signal_setting != NULL) {
3212      end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3213                             dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
3214      get_signal_action = CAST_TO_FN_PTR(get_signal_t,
3215                            dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
3216      libjsig_is_loaded = true;
3217      assert(UseSignalChaining, "should enable signal-chaining");
3218    }
3219    if (libjsig_is_loaded) {
3220      // Tell libjsig jvm is setting signal handlers
3221      (*begin_signal_setting)();
3222    }
3223
3224    set_signal_handler(SIGSEGV, true);
3225    set_signal_handler(SIGPIPE, true);
3226    set_signal_handler(SIGBUS, true);
3227    set_signal_handler(SIGILL, true);
3228    set_signal_handler(SIGFPE, true);
3229    set_signal_handler(SIGXFSZ, true);
3230
3231#if defined(__APPLE__)
3232    // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
3233    // signals caught and handled by the JVM. To work around this, we reset the mach task
3234    // signal handler that's placed on our process by CrashReporter. This disables
3235    // CrashReporter-based reporting.
3236    //
3237    // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
3238    // on caught fatal signals.
3239    //
3240    // Additionally, gdb installs both standard BSD signal handlers, and mach exception
3241    // handlers. By replacing the existing task exception handler, we disable gdb's mach
3242    // exception handling, while leaving the standard BSD signal handlers functional.
3243    kern_return_t kr;
3244    kr = task_set_exception_ports(mach_task_self(),
3245        EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
3246        MACH_PORT_NULL,
3247        EXCEPTION_STATE_IDENTITY,
3248        MACHINE_THREAD_STATE);
3249
3250    assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
3251#endif
3252
3253    if (libjsig_is_loaded) {
3254      // Tell libjsig jvm finishes setting signal handlers
3255      (*end_signal_setting)();
3256    }
3257
3258    // We don't activate signal checker if libjsig is in place, we trust ourselves
3259    // and if UserSignalHandler is installed all bets are off
3260    if (CheckJNICalls) {
3261      if (libjsig_is_loaded) {
3262        tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
3263        check_signals = false;
3264      }
3265      if (AllowUserSignalHandlers) {
3266        tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
3267        check_signals = false;
3268      }
3269    }
3270  }
3271}
3272
3273
3274/////
3275// glibc on Bsd platform uses non-documented flag
3276// to indicate, that some special sort of signal
3277// trampoline is used.
3278// We will never set this flag, and we should
3279// ignore this flag in our diagnostic
3280#ifdef SIGNIFICANT_SIGNAL_MASK
3281#undef SIGNIFICANT_SIGNAL_MASK
3282#endif
3283#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
3284
3285static const char* get_signal_handler_name(address handler,
3286                                           char* buf, int buflen) {
3287  int offset;
3288  bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
3289  if (found) {
3290    // skip directory names
3291    const char *p1, *p2;
3292    p1 = buf;
3293    size_t len = strlen(os::file_separator());
3294    while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
3295    jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
3296  } else {
3297    jio_snprintf(buf, buflen, PTR_FORMAT, handler);
3298  }
3299  return buf;
3300}
3301
3302static void print_signal_handler(outputStream* st, int sig,
3303                                 char* buf, size_t buflen) {
3304  struct sigaction sa;
3305
3306  sigaction(sig, NULL, &sa);
3307
3308  // See comment for SIGNIFICANT_SIGNAL_MASK define
3309  sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3310
3311  st->print("%s: ", os::exception_name(sig, buf, buflen));
3312
3313  address handler = (sa.sa_flags & SA_SIGINFO)
3314    ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
3315    : CAST_FROM_FN_PTR(address, sa.sa_handler);
3316
3317  if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
3318    st->print("SIG_DFL");
3319  } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
3320    st->print("SIG_IGN");
3321  } else {
3322    st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
3323  }
3324
3325  st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
3326
3327  address rh = VMError::get_resetted_sighandler(sig);
3328  // May be, handler was resetted by VMError?
3329  if(rh != NULL) {
3330    handler = rh;
3331    sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
3332  }
3333
3334  st->print(", sa_flags="   PTR32_FORMAT, sa.sa_flags);
3335
3336  // Check: is it our handler?
3337  if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
3338     handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
3339    // It is our signal handler
3340    // check for flags, reset system-used one!
3341    if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3342      st->print(
3343                ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
3344                os::Bsd::get_our_sigflags(sig));
3345    }
3346  }
3347  st->cr();
3348}
3349
3350
3351#define DO_SIGNAL_CHECK(sig) \
3352  if (!sigismember(&check_signal_done, sig)) \
3353    os::Bsd::check_signal_handler(sig)
3354
3355// This method is a periodic task to check for misbehaving JNI applications
3356// under CheckJNI, we can add any periodic checks here
3357
3358void os::run_periodic_checks() {
3359
3360  if (check_signals == false) return;
3361
3362  // SEGV and BUS if overridden could potentially prevent
3363  // generation of hs*.log in the event of a crash, debugging
3364  // such a case can be very challenging, so we absolutely
3365  // check the following for a good measure:
3366  DO_SIGNAL_CHECK(SIGSEGV);
3367  DO_SIGNAL_CHECK(SIGILL);
3368  DO_SIGNAL_CHECK(SIGFPE);
3369  DO_SIGNAL_CHECK(SIGBUS);
3370  DO_SIGNAL_CHECK(SIGPIPE);
3371  DO_SIGNAL_CHECK(SIGXFSZ);
3372
3373
3374  // ReduceSignalUsage allows the user to override these handlers
3375  // see comments at the very top and jvm_solaris.h
3376  if (!ReduceSignalUsage) {
3377    DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3378    DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3379    DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3380    DO_SIGNAL_CHECK(BREAK_SIGNAL);
3381  }
3382
3383  DO_SIGNAL_CHECK(SR_signum);
3384  DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
3385}
3386
3387typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3388
3389static os_sigaction_t os_sigaction = NULL;
3390
3391void os::Bsd::check_signal_handler(int sig) {
3392  char buf[O_BUFLEN];
3393  address jvmHandler = NULL;
3394
3395
3396  struct sigaction act;
3397  if (os_sigaction == NULL) {
3398    // only trust the default sigaction, in case it has been interposed
3399    os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3400    if (os_sigaction == NULL) return;
3401  }
3402
3403  os_sigaction(sig, (struct sigaction*)NULL, &act);
3404
3405
3406  act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3407
3408  address thisHandler = (act.sa_flags & SA_SIGINFO)
3409    ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3410    : CAST_FROM_FN_PTR(address, act.sa_handler) ;
3411
3412
3413  switch(sig) {
3414  case SIGSEGV:
3415  case SIGBUS:
3416  case SIGFPE:
3417  case SIGPIPE:
3418  case SIGILL:
3419  case SIGXFSZ:
3420    jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3421    break;
3422
3423  case SHUTDOWN1_SIGNAL:
3424  case SHUTDOWN2_SIGNAL:
3425  case SHUTDOWN3_SIGNAL:
3426  case BREAK_SIGNAL:
3427    jvmHandler = (address)user_handler();
3428    break;
3429
3430  case INTERRUPT_SIGNAL:
3431    jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
3432    break;
3433
3434  default:
3435    if (sig == SR_signum) {
3436      jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3437    } else {
3438      return;
3439    }
3440    break;
3441  }
3442
3443  if (thisHandler != jvmHandler) {
3444    tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3445    tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3446    tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3447    // No need to check this sig any longer
3448    sigaddset(&check_signal_done, sig);
3449  } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3450    tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3451    tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
3452    tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
3453    // No need to check this sig any longer
3454    sigaddset(&check_signal_done, sig);
3455  }
3456
3457  // Dump all the signal
3458  if (sigismember(&check_signal_done, sig)) {
3459    print_signal_handlers(tty, buf, O_BUFLEN);
3460  }
3461}
3462
3463extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
3464
3465extern bool signal_name(int signo, char* buf, size_t len);
3466
3467const char* os::exception_name(int exception_code, char* buf, size_t size) {
3468  if (0 < exception_code && exception_code <= SIGRTMAX) {
3469    // signal
3470    if (!signal_name(exception_code, buf, size)) {
3471      jio_snprintf(buf, size, "SIG%d", exception_code);
3472    }
3473    return buf;
3474  } else {
3475    return NULL;
3476  }
3477}
3478
3479// this is called _before_ the most of global arguments have been parsed
3480void os::init(void) {
3481  char dummy;   /* used to get a guess on initial stack address */
3482//  first_hrtime = gethrtime();
3483
3484  // With BsdThreads the JavaMain thread pid (primordial thread)
3485  // is different than the pid of the java launcher thread.
3486  // So, on Bsd, the launcher thread pid is passed to the VM
3487  // via the sun.java.launcher.pid property.
3488  // Use this property instead of getpid() if it was correctly passed.
3489  // See bug 6351349.
3490  pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
3491
3492  _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
3493
3494  clock_tics_per_sec = CLK_TCK;
3495
3496  init_random(1234567);
3497
3498  ThreadCritical::initialize();
3499
3500  Bsd::set_page_size(getpagesize());
3501  if (Bsd::page_size() == -1) {
3502    fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
3503                  strerror(errno)));
3504  }
3505  init_page_sizes((size_t) Bsd::page_size());
3506
3507  Bsd::initialize_system_info();
3508
3509  // main_thread points to the aboriginal thread
3510  Bsd::_main_thread = pthread_self();
3511
3512  Bsd::clock_init();
3513  initial_time_count = os::elapsed_counter();
3514
3515#ifdef __APPLE__
3516  // XXXDARWIN
3517  // Work around the unaligned VM callbacks in hotspot's
3518  // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
3519  // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
3520  // alignment when doing symbol lookup. To work around this, we force early
3521  // binding of all symbols now, thus binding when alignment is known-good.
3522  _dyld_bind_fully_image_containing_address((const void *) &os::init);
3523#endif
3524}
3525
3526// To install functions for atexit system call
3527extern "C" {
3528  static void perfMemory_exit_helper() {
3529    perfMemory_exit();
3530  }
3531}
3532
3533// this is called _after_ the global arguments have been parsed
3534jint os::init_2(void)
3535{
3536  // Allocate a single page and mark it as readable for safepoint polling
3537  address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3538  guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
3539
3540  os::set_polling_page( polling_page );
3541
3542#ifndef PRODUCT
3543  if(Verbose && PrintMiscellaneous)
3544    tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
3545#endif
3546
3547  if (!UseMembar) {
3548    address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3549    guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
3550    os::set_memory_serialize_page( mem_serialize_page );
3551
3552#ifndef PRODUCT
3553    if(Verbose && PrintMiscellaneous)
3554      tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
3555#endif
3556  }
3557
3558  os::large_page_init();
3559
3560  // initialize suspend/resume support - must do this before signal_sets_init()
3561  if (SR_initialize() != 0) {
3562    perror("SR_initialize failed");
3563    return JNI_ERR;
3564  }
3565
3566  Bsd::signal_sets_init();
3567  Bsd::install_signal_handlers();
3568
3569  // Check minimum allowable stack size for thread creation and to initialize
3570  // the java system classes, including StackOverflowError - depends on page
3571  // size.  Add a page for compiler2 recursion in main thread.
3572  // Add in 2*BytesPerWord times page size to account for VM stack during
3573  // class initialization depending on 32 or 64 bit VM.
3574  os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
3575            (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
3576                    2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
3577
3578  size_t threadStackSizeInBytes = ThreadStackSize * K;
3579  if (threadStackSizeInBytes != 0 &&
3580      threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
3581        tty->print_cr("\nThe stack size specified is too small, "
3582                      "Specify at least %dk",
3583                      os::Bsd::min_stack_allowed/ K);
3584        return JNI_ERR;
3585  }
3586
3587  // Make the stack size a multiple of the page size so that
3588  // the yellow/red zones can be guarded.
3589  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
3590        vm_page_size()));
3591
3592  if (MaxFDLimit) {
3593    // set the number of file descriptors to max. print out error
3594    // if getrlimit/setrlimit fails but continue regardless.
3595    struct rlimit nbr_files;
3596    int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3597    if (status != 0) {
3598      if (PrintMiscellaneous && (Verbose || WizardMode))
3599        perror("os::init_2 getrlimit failed");
3600    } else {
3601      nbr_files.rlim_cur = nbr_files.rlim_max;
3602
3603#ifdef __APPLE__
3604      // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3605      // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3606      // be used instead
3607      nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3608#endif
3609
3610      status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3611      if (status != 0) {
3612        if (PrintMiscellaneous && (Verbose || WizardMode))
3613          perror("os::init_2 setrlimit failed");
3614      }
3615    }
3616  }
3617
3618  // at-exit methods are called in the reverse order of their registration.
3619  // atexit functions are called on return from main or as a result of a
3620  // call to exit(3C). There can be only 32 of these functions registered
3621  // and atexit() does not set errno.
3622
3623  if (PerfAllowAtExitRegistration) {
3624    // only register atexit functions if PerfAllowAtExitRegistration is set.
3625    // atexit functions can be delayed until process exit time, which
3626    // can be problematic for embedded VM situations. Embedded VMs should
3627    // call DestroyJavaVM() to assure that VM resources are released.
3628
3629    // note: perfMemory_exit_helper atexit function may be removed in
3630    // the future if the appropriate cleanup code can be added to the
3631    // VM_Exit VMOperation's doit method.
3632    if (atexit(perfMemory_exit_helper) != 0) {
3633      warning("os::init2 atexit(perfMemory_exit_helper) failed");
3634    }
3635  }
3636
3637  // initialize thread priority policy
3638  prio_init();
3639
3640#ifdef __APPLE__
3641  // dynamically link to objective c gc registration
3642  void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3643  if (handleLibObjc != NULL) {
3644    objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3645  }
3646#endif
3647
3648  return JNI_OK;
3649}
3650
3651// this is called at the end of vm_initialization
3652void os::init_3(void) { }
3653
3654// Mark the polling page as unreadable
3655void os::make_polling_page_unreadable(void) {
3656  if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
3657    fatal("Could not disable polling page");
3658};
3659
3660// Mark the polling page as readable
3661void os::make_polling_page_readable(void) {
3662  if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
3663    fatal("Could not enable polling page");
3664  }
3665};
3666
3667int os::active_processor_count() {
3668  return _processor_count;
3669}
3670
3671void os::set_native_thread_name(const char *name) {
3672#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3673  // This is only supported in Snow Leopard and beyond
3674  if (name != NULL) {
3675    // Add a "Java: " prefix to the name
3676    char buf[MAXTHREADNAMESIZE];
3677    snprintf(buf, sizeof(buf), "Java: %s", name);
3678    pthread_setname_np(buf);
3679  }
3680#endif
3681}
3682
3683bool os::distribute_processes(uint length, uint* distribution) {
3684  // Not yet implemented.
3685  return false;
3686}
3687
3688bool os::bind_to_processor(uint processor_id) {
3689  // Not yet implemented.
3690  return false;
3691}
3692
3693void os::SuspendedThreadTask::internal_do_task() {
3694  if (do_suspend(_thread->osthread())) {
3695    SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3696    do_task(context);
3697    do_resume(_thread->osthread());
3698  }
3699}
3700
3701///
3702class PcFetcher : public os::SuspendedThreadTask {
3703public:
3704  PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3705  ExtendedPC result();
3706protected:
3707  void do_task(const os::SuspendedThreadTaskContext& context);
3708private:
3709  ExtendedPC _epc;
3710};
3711
3712ExtendedPC PcFetcher::result() {
3713  guarantee(is_done(), "task is not done yet.");
3714  return _epc;
3715}
3716
3717void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3718  Thread* thread = context.thread();
3719  OSThread* osthread = thread->osthread();
3720  if (osthread->ucontext() != NULL) {
3721    _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());
3722  } else {
3723    // NULL context is unexpected, double-check this is the VMThread
3724    guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3725  }
3726}
3727
3728// Suspends the target using the signal mechanism and then grabs the PC before
3729// resuming the target. Used by the flat-profiler only
3730ExtendedPC os::get_thread_pc(Thread* thread) {
3731  // Make sure that it is called by the watcher for the VMThread
3732  assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
3733  assert(thread->is_VM_thread(), "Can only be called for VMThread");
3734
3735  PcFetcher fetcher(thread);
3736  fetcher.run();
3737  return fetcher.result();
3738}
3739
3740int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
3741{
3742  return pthread_cond_timedwait(_cond, _mutex, _abstime);
3743}
3744
3745////////////////////////////////////////////////////////////////////////////////
3746// debug support
3747
3748bool os::find(address addr, outputStream* st) {
3749  Dl_info dlinfo;
3750  memset(&dlinfo, 0, sizeof(dlinfo));
3751  if (dladdr(addr, &dlinfo)) {
3752    st->print(PTR_FORMAT ": ", addr);
3753    if (dlinfo.dli_sname != NULL) {
3754      st->print("%s+%#x", dlinfo.dli_sname,
3755                 addr - (intptr_t)dlinfo.dli_saddr);
3756    } else if (dlinfo.dli_fname) {
3757      st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
3758    } else {
3759      st->print("<absolute address>");
3760    }
3761    if (dlinfo.dli_fname) {
3762      st->print(" in %s", dlinfo.dli_fname);
3763    }
3764    if (dlinfo.dli_fbase) {
3765      st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
3766    }
3767    st->cr();
3768
3769    if (Verbose) {
3770      // decode some bytes around the PC
3771      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
3772      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
3773      address       lowest = (address) dlinfo.dli_sname;
3774      if (!lowest)  lowest = (address) dlinfo.dli_fbase;
3775      if (begin < lowest)  begin = lowest;
3776      Dl_info dlinfo2;
3777      if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
3778          && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
3779        end = (address) dlinfo2.dli_saddr;
3780      Disassembler::decode(begin, end, st);
3781    }
3782    return true;
3783  }
3784  return false;
3785}
3786
3787////////////////////////////////////////////////////////////////////////////////
3788// misc
3789
3790// This does not do anything on Bsd. This is basically a hook for being
3791// able to use structured exception handling (thread-local exception filters)
3792// on, e.g., Win32.
3793void
3794os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
3795                         JavaCallArguments* args, Thread* thread) {
3796  f(value, method, args, thread);
3797}
3798
3799void os::print_statistics() {
3800}
3801
3802int os::message_box(const char* title, const char* message) {
3803  int i;
3804  fdStream err(defaultStream::error_fd());
3805  for (i = 0; i < 78; i++) err.print_raw("=");
3806  err.cr();
3807  err.print_raw_cr(title);
3808  for (i = 0; i < 78; i++) err.print_raw("-");
3809  err.cr();
3810  err.print_raw_cr(message);
3811  for (i = 0; i < 78; i++) err.print_raw("=");
3812  err.cr();
3813
3814  char buf[16];
3815  // Prevent process from exiting upon "read error" without consuming all CPU
3816  while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3817
3818  return buf[0] == 'y' || buf[0] == 'Y';
3819}
3820
3821int os::stat(const char *path, struct stat *sbuf) {
3822  char pathbuf[MAX_PATH];
3823  if (strlen(path) > MAX_PATH - 1) {
3824    errno = ENAMETOOLONG;
3825    return -1;
3826  }
3827  os::native_path(strcpy(pathbuf, path));
3828  return ::stat(pathbuf, sbuf);
3829}
3830
3831bool os::check_heap(bool force) {
3832  return true;
3833}
3834
3835int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
3836  return ::vsnprintf(buf, count, format, args);
3837}
3838
3839// Is a (classpath) directory empty?
3840bool os::dir_is_empty(const char* path) {
3841  DIR *dir = NULL;
3842  struct dirent *ptr;
3843
3844  dir = opendir(path);
3845  if (dir == NULL) return true;
3846
3847  /* Scan the directory */
3848  bool result = true;
3849  char buf[sizeof(struct dirent) + MAX_PATH];
3850  while (result && (ptr = ::readdir(dir)) != NULL) {
3851    if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3852      result = false;
3853    }
3854  }
3855  closedir(dir);
3856  return result;
3857}
3858
3859// This code originates from JDK's sysOpen and open64_w
3860// from src/solaris/hpi/src/system_md.c
3861
3862#ifndef O_DELETE
3863#define O_DELETE 0x10000
3864#endif
3865
3866// Open a file. Unlink the file immediately after open returns
3867// if the specified oflag has the O_DELETE flag set.
3868// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
3869
3870int os::open(const char *path, int oflag, int mode) {
3871
3872  if (strlen(path) > MAX_PATH - 1) {
3873    errno = ENAMETOOLONG;
3874    return -1;
3875  }
3876  int fd;
3877  int o_delete = (oflag & O_DELETE);
3878  oflag = oflag & ~O_DELETE;
3879
3880  fd = ::open(path, oflag, mode);
3881  if (fd == -1) return -1;
3882
3883  //If the open succeeded, the file might still be a directory
3884  {
3885    struct stat buf;
3886    int ret = ::fstat(fd, &buf);
3887    int st_mode = buf.st_mode;
3888
3889    if (ret != -1) {
3890      if ((st_mode & S_IFMT) == S_IFDIR) {
3891        errno = EISDIR;
3892        ::close(fd);
3893        return -1;
3894      }
3895    } else {
3896      ::close(fd);
3897      return -1;
3898    }
3899  }
3900
3901    /*
3902     * All file descriptors that are opened in the JVM and not
3903     * specifically destined for a subprocess should have the
3904     * close-on-exec flag set.  If we don't set it, then careless 3rd
3905     * party native code might fork and exec without closing all
3906     * appropriate file descriptors (e.g. as we do in closeDescriptors in
3907     * UNIXProcess.c), and this in turn might:
3908     *
3909     * - cause end-of-file to fail to be detected on some file
3910     *   descriptors, resulting in mysterious hangs, or
3911     *
3912     * - might cause an fopen in the subprocess to fail on a system
3913     *   suffering from bug 1085341.
3914     *
3915     * (Yes, the default setting of the close-on-exec flag is a Unix
3916     * design flaw)
3917     *
3918     * See:
3919     * 1085341: 32-bit stdio routines should support file descriptors >255
3920     * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3921     * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3922     */
3923#ifdef FD_CLOEXEC
3924    {
3925        int flags = ::fcntl(fd, F_GETFD);
3926        if (flags != -1)
3927            ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3928    }
3929#endif
3930
3931  if (o_delete != 0) {
3932    ::unlink(path);
3933  }
3934  return fd;
3935}
3936
3937
3938// create binary file, rewriting existing file if required
3939int os::create_binary_file(const char* path, bool rewrite_existing) {
3940  int oflags = O_WRONLY | O_CREAT;
3941  if (!rewrite_existing) {
3942    oflags |= O_EXCL;
3943  }
3944  return ::open(path, oflags, S_IREAD | S_IWRITE);
3945}
3946
3947// return current position of file pointer
3948jlong os::current_file_offset(int fd) {
3949  return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
3950}
3951
3952// move file pointer to the specified offset
3953jlong os::seek_to_file_offset(int fd, jlong offset) {
3954  return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
3955}
3956
3957// This code originates from JDK's sysAvailable
3958// from src/solaris/hpi/src/native_threads/src/sys_api_td.c
3959
3960int os::available(int fd, jlong *bytes) {
3961  jlong cur, end;
3962  int mode;
3963  struct stat buf;
3964
3965  if (::fstat(fd, &buf) >= 0) {
3966    mode = buf.st_mode;
3967    if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
3968      /*
3969      * XXX: is the following call interruptible? If so, this might
3970      * need to go through the INTERRUPT_IO() wrapper as for other
3971      * blocking, interruptible calls in this file.
3972      */
3973      int n;
3974      if (::ioctl(fd, FIONREAD, &n) >= 0) {
3975        *bytes = n;
3976        return 1;
3977      }
3978    }
3979  }
3980  if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
3981    return 0;
3982  } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
3983    return 0;
3984  } else if (::lseek(fd, cur, SEEK_SET) == -1) {
3985    return 0;
3986  }
3987  *bytes = end - cur;
3988  return 1;
3989}
3990
3991int os::socket_available(int fd, jint *pbytes) {
3992   if (fd < 0)
3993     return OS_OK;
3994
3995   int ret;
3996
3997   RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
3998
3999   //%% note ioctl can return 0 when successful, JVM_SocketAvailable
4000   // is expected to return 0 on failure and 1 on success to the jdk.
4001
4002   return (ret == OS_ERR) ? 0 : 1;
4003}
4004
4005// Map a block of memory.
4006char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4007                     char *addr, size_t bytes, bool read_only,
4008                     bool allow_exec) {
4009  int prot;
4010  int flags;
4011
4012  if (read_only) {
4013    prot = PROT_READ;
4014    flags = MAP_SHARED;
4015  } else {
4016    prot = PROT_READ | PROT_WRITE;
4017    flags = MAP_PRIVATE;
4018  }
4019
4020  if (allow_exec) {
4021    prot |= PROT_EXEC;
4022  }
4023
4024  if (addr != NULL) {
4025    flags |= MAP_FIXED;
4026  }
4027
4028  char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4029                                     fd, file_offset);
4030  if (mapped_address == MAP_FAILED) {
4031    return NULL;
4032  }
4033  return mapped_address;
4034}
4035
4036
4037// Remap a block of memory.
4038char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4039                       char *addr, size_t bytes, bool read_only,
4040                       bool allow_exec) {
4041  // same as map_memory() on this OS
4042  return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4043                        allow_exec);
4044}
4045
4046
4047// Unmap a block of memory.
4048bool os::pd_unmap_memory(char* addr, size_t bytes) {
4049  return munmap(addr, bytes) == 0;
4050}
4051
4052// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4053// are used by JVM M&M and JVMTI to get user+sys or user CPU time
4054// of a thread.
4055//
4056// current_thread_cpu_time() and thread_cpu_time(Thread*) returns
4057// the fast estimate available on the platform.
4058
4059jlong os::current_thread_cpu_time() {
4060#ifdef __APPLE__
4061  return os::thread_cpu_time(Thread::current(), true /* user + sys */);
4062#else
4063  Unimplemented();
4064  return 0;
4065#endif
4066}
4067
4068jlong os::thread_cpu_time(Thread* thread) {
4069#ifdef __APPLE__
4070  return os::thread_cpu_time(thread, true /* user + sys */);
4071#else
4072  Unimplemented();
4073  return 0;
4074#endif
4075}
4076
4077jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
4078#ifdef __APPLE__
4079  return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
4080#else
4081  Unimplemented();
4082  return 0;
4083#endif
4084}
4085
4086jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
4087#ifdef __APPLE__
4088  struct thread_basic_info tinfo;
4089  mach_msg_type_number_t tcount = THREAD_INFO_MAX;
4090  kern_return_t kr;
4091  thread_t mach_thread;
4092
4093  mach_thread = thread->osthread()->thread_id();
4094  kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
4095  if (kr != KERN_SUCCESS)
4096    return -1;
4097
4098  if (user_sys_cpu_time) {
4099    jlong nanos;
4100    nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
4101    nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
4102    return nanos;
4103  } else {
4104    return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
4105  }
4106#else
4107  Unimplemented();
4108  return 0;
4109#endif
4110}
4111
4112
4113void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4114  info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
4115  info_ptr->may_skip_backward = false;     // elapsed time not wall time
4116  info_ptr->may_skip_forward = false;      // elapsed time not wall time
4117  info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
4118}
4119
4120void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4121  info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
4122  info_ptr->may_skip_backward = false;     // elapsed time not wall time
4123  info_ptr->may_skip_forward = false;      // elapsed time not wall time
4124  info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
4125}
4126
4127bool os::is_thread_cpu_time_supported() {
4128#ifdef __APPLE__
4129  return true;
4130#else
4131  return false;
4132#endif
4133}
4134
4135// System loadavg support.  Returns -1 if load average cannot be obtained.
4136// Bsd doesn't yet have a (official) notion of processor sets,
4137// so just return the system wide load average.
4138int os::loadavg(double loadavg[], int nelem) {
4139  return ::getloadavg(loadavg, nelem);
4140}
4141
4142void os::pause() {
4143  char filename[MAX_PATH];
4144  if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4145    jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4146  } else {
4147    jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4148  }
4149
4150  int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4151  if (fd != -1) {
4152    struct stat buf;
4153    ::close(fd);
4154    while (::stat(filename, &buf) == 0) {
4155      (void)::poll(NULL, 0, 100);
4156    }
4157  } else {
4158    jio_fprintf(stderr,
4159      "Could not open pause file '%s', continuing immediately.\n", filename);
4160  }
4161}
4162
4163
4164// Refer to the comments in os_solaris.cpp park-unpark.
4165//
4166// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
4167// hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
4168// For specifics regarding the bug see GLIBC BUGID 261237 :
4169//    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
4170// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
4171// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
4172// is used.  (The simple C test-case provided in the GLIBC bug report manifests the
4173// hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
4174// and monitorenter when we're using 1-0 locking.  All those operations may result in
4175// calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
4176// of libpthread avoids the problem, but isn't practical.
4177//
4178// Possible remedies:
4179//
4180// 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
4181//      This is palliative and probabilistic, however.  If the thread is preempted
4182//      between the call to compute_abstime() and pthread_cond_timedwait(), more
4183//      than the minimum period may have passed, and the abstime may be stale (in the
4184//      past) resultin in a hang.   Using this technique reduces the odds of a hang
4185//      but the JVM is still vulnerable, particularly on heavily loaded systems.
4186//
4187// 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
4188//      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
4189//      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
4190//      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
4191//      thread.
4192//
4193// 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
4194//      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
4195//      a timeout request to the chron thread and then blocking via pthread_cond_wait().
4196//      This also works well.  In fact it avoids kernel-level scalability impediments
4197//      on certain platforms that don't handle lots of active pthread_cond_timedwait()
4198//      timers in a graceful fashion.
4199//
4200// 4.   When the abstime value is in the past it appears that control returns
4201//      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
4202//      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
4203//      can avoid the problem by reinitializing the condvar -- by cond_destroy()
4204//      followed by cond_init() -- after all calls to pthread_cond_timedwait().
4205//      It may be possible to avoid reinitialization by checking the return
4206//      value from pthread_cond_timedwait().  In addition to reinitializing the
4207//      condvar we must establish the invariant that cond_signal() is only called
4208//      within critical sections protected by the adjunct mutex.  This prevents
4209//      cond_signal() from "seeing" a condvar that's in the midst of being
4210//      reinitialized or that is corrupt.  Sadly, this invariant obviates the
4211//      desirable signal-after-unlock optimization that avoids futile context switching.
4212//
4213//      I'm also concerned that some versions of NTPL might allocate an auxilliary
4214//      structure when a condvar is used or initialized.  cond_destroy()  would
4215//      release the helper structure.  Our reinitialize-after-timedwait fix
4216//      put excessive stress on malloc/free and locks protecting the c-heap.
4217//
4218// We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
4219// It may be possible to refine (4) by checking the kernel and NTPL verisons
4220// and only enabling the work-around for vulnerable environments.
4221
4222// utility to compute the abstime argument to timedwait:
4223// millis is the relative timeout time
4224// abstime will be the absolute timeout time
4225// TODO: replace compute_abstime() with unpackTime()
4226
4227static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
4228  if (millis < 0)  millis = 0;
4229  struct timeval now;
4230  int status = gettimeofday(&now, NULL);
4231  assert(status == 0, "gettimeofday");
4232  jlong seconds = millis / 1000;
4233  millis %= 1000;
4234  if (seconds > 50000000) { // see man cond_timedwait(3T)
4235    seconds = 50000000;
4236  }
4237  abstime->tv_sec = now.tv_sec  + seconds;
4238  long       usec = now.tv_usec + millis * 1000;
4239  if (usec >= 1000000) {
4240    abstime->tv_sec += 1;
4241    usec -= 1000000;
4242  }
4243  abstime->tv_nsec = usec * 1000;
4244  return abstime;
4245}
4246
4247
4248// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
4249// Conceptually TryPark() should be equivalent to park(0).
4250
4251int os::PlatformEvent::TryPark() {
4252  for (;;) {
4253    const int v = _Event ;
4254    guarantee ((v == 0) || (v == 1), "invariant") ;
4255    if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
4256  }
4257}
4258
4259void os::PlatformEvent::park() {       // AKA "down()"
4260  // Invariant: Only the thread associated with the Event/PlatformEvent
4261  // may call park().
4262  // TODO: assert that _Assoc != NULL or _Assoc == Self
4263  int v ;
4264  for (;;) {
4265      v = _Event ;
4266      if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4267  }
4268  guarantee (v >= 0, "invariant") ;
4269  if (v == 0) {
4270     // Do this the hard way by blocking ...
4271     int status = pthread_mutex_lock(_mutex);
4272     assert_status(status == 0, status, "mutex_lock");
4273     guarantee (_nParked == 0, "invariant") ;
4274     ++ _nParked ;
4275     while (_Event < 0) {
4276        status = pthread_cond_wait(_cond, _mutex);
4277        // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
4278        // Treat this the same as if the wait was interrupted
4279        if (status == ETIMEDOUT) { status = EINTR; }
4280        assert_status(status == 0 || status == EINTR, status, "cond_wait");
4281     }
4282     -- _nParked ;
4283
4284    _Event = 0 ;
4285     status = pthread_mutex_unlock(_mutex);
4286     assert_status(status == 0, status, "mutex_unlock");
4287    // Paranoia to ensure our locked and lock-free paths interact
4288    // correctly with each other.
4289    OrderAccess::fence();
4290  }
4291  guarantee (_Event >= 0, "invariant") ;
4292}
4293
4294int os::PlatformEvent::park(jlong millis) {
4295  guarantee (_nParked == 0, "invariant") ;
4296
4297  int v ;
4298  for (;;) {
4299      v = _Event ;
4300      if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
4301  }
4302  guarantee (v >= 0, "invariant") ;
4303  if (v != 0) return OS_OK ;
4304
4305  // We do this the hard way, by blocking the thread.
4306  // Consider enforcing a minimum timeout value.
4307  struct timespec abst;
4308  compute_abstime(&abst, millis);
4309
4310  int ret = OS_TIMEOUT;
4311  int status = pthread_mutex_lock(_mutex);
4312  assert_status(status == 0, status, "mutex_lock");
4313  guarantee (_nParked == 0, "invariant") ;
4314  ++_nParked ;
4315
4316  // Object.wait(timo) will return because of
4317  // (a) notification
4318  // (b) timeout
4319  // (c) thread.interrupt
4320  //
4321  // Thread.interrupt and object.notify{All} both call Event::set.
4322  // That is, we treat thread.interrupt as a special case of notification.
4323  // The underlying Solaris implementation, cond_timedwait, admits
4324  // spurious/premature wakeups, but the JLS/JVM spec prevents the
4325  // JVM from making those visible to Java code.  As such, we must
4326  // filter out spurious wakeups.  We assume all ETIME returns are valid.
4327  //
4328  // TODO: properly differentiate simultaneous notify+interrupt.
4329  // In that case, we should propagate the notify to another waiter.
4330
4331  while (_Event < 0) {
4332    status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
4333    if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4334      pthread_cond_destroy (_cond);
4335      pthread_cond_init (_cond, NULL) ;
4336    }
4337    assert_status(status == 0 || status == EINTR ||
4338                  status == ETIMEDOUT,
4339                  status, "cond_timedwait");
4340    if (!FilterSpuriousWakeups) break ;                 // previous semantics
4341    if (status == ETIMEDOUT) break ;
4342    // We consume and ignore EINTR and spurious wakeups.
4343  }
4344  --_nParked ;
4345  if (_Event >= 0) {
4346     ret = OS_OK;
4347  }
4348  _Event = 0 ;
4349  status = pthread_mutex_unlock(_mutex);
4350  assert_status(status == 0, status, "mutex_unlock");
4351  assert (_nParked == 0, "invariant") ;
4352  // Paranoia to ensure our locked and lock-free paths interact
4353  // correctly with each other.
4354  OrderAccess::fence();
4355  return ret;
4356}
4357
4358void os::PlatformEvent::unpark() {
4359  // Transitions for _Event:
4360  //    0 :=> 1
4361  //    1 :=> 1
4362  //   -1 :=> either 0 or 1; must signal target thread
4363  //          That is, we can safely transition _Event from -1 to either
4364  //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
4365  //          unpark() calls.
4366  // See also: "Semaphores in Plan 9" by Mullender & Cox
4367  //
4368  // Note: Forcing a transition from "-1" to "1" on an unpark() means
4369  // that it will take two back-to-back park() calls for the owning
4370  // thread to block. This has the benefit of forcing a spurious return
4371  // from the first park() call after an unpark() call which will help
4372  // shake out uses of park() and unpark() without condition variables.
4373
4374  if (Atomic::xchg(1, &_Event) >= 0) return;
4375
4376  // Wait for the thread associated with the event to vacate
4377  int status = pthread_mutex_lock(_mutex);
4378  assert_status(status == 0, status, "mutex_lock");
4379  int AnyWaiters = _nParked;
4380  assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
4381  if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
4382    AnyWaiters = 0;
4383    pthread_cond_signal(_cond);
4384  }
4385  status = pthread_mutex_unlock(_mutex);
4386  assert_status(status == 0, status, "mutex_unlock");
4387  if (AnyWaiters != 0) {
4388    status = pthread_cond_signal(_cond);
4389    assert_status(status == 0, status, "cond_signal");
4390  }
4391
4392  // Note that we signal() _after dropping the lock for "immortal" Events.
4393  // This is safe and avoids a common class of  futile wakeups.  In rare
4394  // circumstances this can cause a thread to return prematurely from
4395  // cond_{timed}wait() but the spurious wakeup is benign and the victim will
4396  // simply re-test the condition and re-park itself.
4397}
4398
4399
4400// JSR166
4401// -------------------------------------------------------
4402
4403/*
4404 * The solaris and bsd implementations of park/unpark are fairly
4405 * conservative for now, but can be improved. They currently use a
4406 * mutex/condvar pair, plus a a count.
4407 * Park decrements count if > 0, else does a condvar wait.  Unpark
4408 * sets count to 1 and signals condvar.  Only one thread ever waits
4409 * on the condvar. Contention seen when trying to park implies that someone
4410 * is unparking you, so don't wait. And spurious returns are fine, so there
4411 * is no need to track notifications.
4412 */
4413
4414#define MAX_SECS 100000000
4415/*
4416 * This code is common to bsd and solaris and will be moved to a
4417 * common place in dolphin.
4418 *
4419 * The passed in time value is either a relative time in nanoseconds
4420 * or an absolute time in milliseconds. Either way it has to be unpacked
4421 * into suitable seconds and nanoseconds components and stored in the
4422 * given timespec structure.
4423 * Given time is a 64-bit value and the time_t used in the timespec is only
4424 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
4425 * overflow if times way in the future are given. Further on Solaris versions
4426 * prior to 10 there is a restriction (see cond_timedwait) that the specified
4427 * number of seconds, in abstime, is less than current_time  + 100,000,000.
4428 * As it will be 28 years before "now + 100000000" will overflow we can
4429 * ignore overflow and just impose a hard-limit on seconds using the value
4430 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
4431 * years from "now".
4432 */
4433
4434static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
4435  assert (time > 0, "convertTime");
4436
4437  struct timeval now;
4438  int status = gettimeofday(&now, NULL);
4439  assert(status == 0, "gettimeofday");
4440
4441  time_t max_secs = now.tv_sec + MAX_SECS;
4442
4443  if (isAbsolute) {
4444    jlong secs = time / 1000;
4445    if (secs > max_secs) {
4446      absTime->tv_sec = max_secs;
4447    }
4448    else {
4449      absTime->tv_sec = secs;
4450    }
4451    absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
4452  }
4453  else {
4454    jlong secs = time / NANOSECS_PER_SEC;
4455    if (secs >= MAX_SECS) {
4456      absTime->tv_sec = max_secs;
4457      absTime->tv_nsec = 0;
4458    }
4459    else {
4460      absTime->tv_sec = now.tv_sec + secs;
4461      absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
4462      if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
4463        absTime->tv_nsec -= NANOSECS_PER_SEC;
4464        ++absTime->tv_sec; // note: this must be <= max_secs
4465      }
4466    }
4467  }
4468  assert(absTime->tv_sec >= 0, "tv_sec < 0");
4469  assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
4470  assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
4471  assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
4472}
4473
4474void Parker::park(bool isAbsolute, jlong time) {
4475  // Ideally we'd do something useful while spinning, such
4476  // as calling unpackTime().
4477
4478  // Optional fast-path check:
4479  // Return immediately if a permit is available.
4480  // We depend on Atomic::xchg() having full barrier semantics
4481  // since we are doing a lock-free update to _counter.
4482  if (Atomic::xchg(0, &_counter) > 0) return;
4483
4484  Thread* thread = Thread::current();
4485  assert(thread->is_Java_thread(), "Must be JavaThread");
4486  JavaThread *jt = (JavaThread *)thread;
4487
4488  // Optional optimization -- avoid state transitions if there's an interrupt pending.
4489  // Check interrupt before trying to wait
4490  if (Thread::is_interrupted(thread, false)) {
4491    return;
4492  }
4493
4494  // Next, demultiplex/decode time arguments
4495  struct timespec absTime;
4496  if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
4497    return;
4498  }
4499  if (time > 0) {
4500    unpackTime(&absTime, isAbsolute, time);
4501  }
4502
4503
4504  // Enter safepoint region
4505  // Beware of deadlocks such as 6317397.
4506  // The per-thread Parker:: mutex is a classic leaf-lock.
4507  // In particular a thread must never block on the Threads_lock while
4508  // holding the Parker:: mutex.  If safepoints are pending both the
4509  // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
4510  ThreadBlockInVM tbivm(jt);
4511
4512  // Don't wait if cannot get lock since interference arises from
4513  // unblocking.  Also. check interrupt before trying wait
4514  if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
4515    return;
4516  }
4517
4518  int status ;
4519  if (_counter > 0)  { // no wait needed
4520    _counter = 0;
4521    status = pthread_mutex_unlock(_mutex);
4522    assert (status == 0, "invariant") ;
4523    // Paranoia to ensure our locked and lock-free paths interact
4524    // correctly with each other and Java-level accesses.
4525    OrderAccess::fence();
4526    return;
4527  }
4528
4529#ifdef ASSERT
4530  // Don't catch signals while blocked; let the running threads have the signals.
4531  // (This allows a debugger to break into the running thread.)
4532  sigset_t oldsigs;
4533  sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
4534  pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
4535#endif
4536
4537  OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
4538  jt->set_suspend_equivalent();
4539  // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
4540
4541  if (time == 0) {
4542    status = pthread_cond_wait (_cond, _mutex) ;
4543  } else {
4544    status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
4545    if (status != 0 && WorkAroundNPTLTimedWaitHang) {
4546      pthread_cond_destroy (_cond) ;
4547      pthread_cond_init    (_cond, NULL);
4548    }
4549  }
4550  assert_status(status == 0 || status == EINTR ||
4551                status == ETIMEDOUT,
4552                status, "cond_timedwait");
4553
4554#ifdef ASSERT
4555  pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
4556#endif
4557
4558  _counter = 0 ;
4559  status = pthread_mutex_unlock(_mutex) ;
4560  assert_status(status == 0, status, "invariant") ;
4561  // Paranoia to ensure our locked and lock-free paths interact
4562  // correctly with each other and Java-level accesses.
4563  OrderAccess::fence();
4564
4565  // If externally suspended while waiting, re-suspend
4566  if (jt->handle_special_suspend_equivalent_condition()) {
4567    jt->java_suspend_self();
4568  }
4569}
4570
4571void Parker::unpark() {
4572  int s, status ;
4573  status = pthread_mutex_lock(_mutex);
4574  assert (status == 0, "invariant") ;
4575  s = _counter;
4576  _counter = 1;
4577  if (s < 1) {
4578     if (WorkAroundNPTLTimedWaitHang) {
4579        status = pthread_cond_signal (_cond) ;
4580        assert (status == 0, "invariant") ;
4581        status = pthread_mutex_unlock(_mutex);
4582        assert (status == 0, "invariant") ;
4583     } else {
4584        status = pthread_mutex_unlock(_mutex);
4585        assert (status == 0, "invariant") ;
4586        status = pthread_cond_signal (_cond) ;
4587        assert (status == 0, "invariant") ;
4588     }
4589  } else {
4590    pthread_mutex_unlock(_mutex);
4591    assert (status == 0, "invariant") ;
4592  }
4593}
4594
4595
4596/* Darwin has no "environ" in a dynamic library. */
4597#ifdef __APPLE__
4598#include <crt_externs.h>
4599#define environ (*_NSGetEnviron())
4600#else
4601extern char** environ;
4602#endif
4603
4604// Run the specified command in a separate process. Return its exit value,
4605// or -1 on failure (e.g. can't fork a new process).
4606// Unlike system(), this function can be called from signal handler. It
4607// doesn't block SIGINT et al.
4608int os::fork_and_exec(char* cmd) {
4609  const char * argv[4] = {"sh", "-c", cmd, NULL};
4610
4611  // fork() in BsdThreads/NPTL is not async-safe. It needs to run
4612  // pthread_atfork handlers and reset pthread library. All we need is a
4613  // separate process to execve. Make a direct syscall to fork process.
4614  // On IA64 there's no fork syscall, we have to use fork() and hope for
4615  // the best...
4616  pid_t pid = fork();
4617
4618  if (pid < 0) {
4619    // fork failed
4620    return -1;
4621
4622  } else if (pid == 0) {
4623    // child process
4624
4625    // execve() in BsdThreads will call pthread_kill_other_threads_np()
4626    // first to kill every thread on the thread list. Because this list is
4627    // not reset by fork() (see notes above), execve() will instead kill
4628    // every thread in the parent process. We know this is the only thread
4629    // in the new process, so make a system call directly.
4630    // IA64 should use normal execve() from glibc to match the glibc fork()
4631    // above.
4632    execve("/bin/sh", (char* const*)argv, environ);
4633
4634    // execve failed
4635    _exit(-1);
4636
4637  } else  {
4638    // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
4639    // care about the actual exit code, for now.
4640
4641    int status;
4642
4643    // Wait for the child process to exit.  This returns immediately if
4644    // the child has already exited. */
4645    while (waitpid(pid, &status, 0) < 0) {
4646        switch (errno) {
4647        case ECHILD: return 0;
4648        case EINTR: break;
4649        default: return -1;
4650        }
4651    }
4652
4653    if (WIFEXITED(status)) {
4654       // The child exited normally; get its exit code.
4655       return WEXITSTATUS(status);
4656    } else if (WIFSIGNALED(status)) {
4657       // The child exited because of a signal
4658       // The best value to return is 0x80 + signal number,
4659       // because that is what all Unix shells do, and because
4660       // it allows callers to distinguish between process exit and
4661       // process death by signal.
4662       return 0x80 + WTERMSIG(status);
4663    } else {
4664       // Unknown exit code; pass it through
4665       return status;
4666    }
4667  }
4668}
4669
4670// is_headless_jre()
4671//
4672// Test for the existence of xawt/libmawt.so or libawt_xawt.so
4673// in order to report if we are running in a headless jre
4674//
4675// Since JDK8 xawt/libmawt.so was moved into the same directory
4676// as libawt.so, and renamed libawt_xawt.so
4677//
4678bool os::is_headless_jre() {
4679    struct stat statbuf;
4680    char buf[MAXPATHLEN];
4681    char libmawtpath[MAXPATHLEN];
4682    const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
4683    const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
4684    char *p;
4685
4686    // Get path to libjvm.so
4687    os::jvm_path(buf, sizeof(buf));
4688
4689    // Get rid of libjvm.so
4690    p = strrchr(buf, '/');
4691    if (p == NULL) return false;
4692    else *p = '\0';
4693
4694    // Get rid of client or server
4695    p = strrchr(buf, '/');
4696    if (p == NULL) return false;
4697    else *p = '\0';
4698
4699    // check xawt/libmawt.so
4700    strcpy(libmawtpath, buf);
4701    strcat(libmawtpath, xawtstr);
4702    if (::stat(libmawtpath, &statbuf) == 0) return false;
4703
4704    // check libawt_xawt.so
4705    strcpy(libmawtpath, buf);
4706    strcat(libmawtpath, new_xawtstr);
4707    if (::stat(libmawtpath, &statbuf) == 0) return false;
4708
4709    return true;
4710}
4711
4712// Get the default path to the core file
4713// Returns the length of the string
4714int os::get_core_path(char* buffer, size_t bufferSize) {
4715  int n = jio_snprintf(buffer, bufferSize, "/cores");
4716
4717  // Truncate if theoretical string was longer than bufferSize
4718  n = MIN2(n, (int)bufferSize);
4719
4720  return n;
4721}
4722
4723