src/os/bsd/vm/os_bsd.cpp

Thu, 05 Sep 2013 11:04:39 -0700

author
kvn
date
Thu, 05 Sep 2013 11:04:39 -0700
changeset 6462
e2722a66aba7
parent 6460
f42f2e2a1518
parent 5578
4c84d351cca9
child 6472
2b8e28fdf503
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 // no precompiled headers
    26 #include "classfile/classLoader.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "classfile/vmSymbols.hpp"
    29 #include "code/icBuffer.hpp"
    30 #include "code/vtableStubs.hpp"
    31 #include "compiler/compileBroker.hpp"
    32 #include "compiler/disassembler.hpp"
    33 #include "interpreter/interpreter.hpp"
    34 #include "jvm_bsd.h"
    35 #include "memory/allocation.inline.hpp"
    36 #include "memory/filemap.hpp"
    37 #include "mutex_bsd.inline.hpp"
    38 #include "oops/oop.inline.hpp"
    39 #include "os_share_bsd.hpp"
    40 #include "prims/jniFastGetField.hpp"
    41 #include "prims/jvm.h"
    42 #include "prims/jvm_misc.hpp"
    43 #include "runtime/arguments.hpp"
    44 #include "runtime/extendedPC.hpp"
    45 #include "runtime/globals.hpp"
    46 #include "runtime/interfaceSupport.hpp"
    47 #include "runtime/java.hpp"
    48 #include "runtime/javaCalls.hpp"
    49 #include "runtime/mutexLocker.hpp"
    50 #include "runtime/objectMonitor.hpp"
    51 #include "runtime/osThread.hpp"
    52 #include "runtime/perfMemory.hpp"
    53 #include "runtime/sharedRuntime.hpp"
    54 #include "runtime/statSampler.hpp"
    55 #include "runtime/stubRoutines.hpp"
    56 #include "runtime/thread.inline.hpp"
    57 #include "runtime/threadCritical.hpp"
    58 #include "runtime/timer.hpp"
    59 #include "services/attachListener.hpp"
    60 #include "services/memTracker.hpp"
    61 #include "services/runtimeService.hpp"
    62 #include "utilities/decoder.hpp"
    63 #include "utilities/defaultStream.hpp"
    64 #include "utilities/events.hpp"
    65 #include "utilities/growableArray.hpp"
    66 #include "utilities/vmError.hpp"
    68 // put OS-includes here
    69 # include <sys/types.h>
    70 # include <sys/mman.h>
    71 # include <sys/stat.h>
    72 # include <sys/select.h>
    73 # include <pthread.h>
    74 # include <signal.h>
    75 # include <errno.h>
    76 # include <dlfcn.h>
    77 # include <stdio.h>
    78 # include <unistd.h>
    79 # include <sys/resource.h>
    80 # include <pthread.h>
    81 # include <sys/stat.h>
    82 # include <sys/time.h>
    83 # include <sys/times.h>
    84 # include <sys/utsname.h>
    85 # include <sys/socket.h>
    86 # include <sys/wait.h>
    87 # include <time.h>
    88 # include <pwd.h>
    89 # include <poll.h>
    90 # include <semaphore.h>
    91 # include <fcntl.h>
    92 # include <string.h>
    93 # include <sys/param.h>
    94 # include <sys/sysctl.h>
    95 # include <sys/ipc.h>
    96 # include <sys/shm.h>
    97 #ifndef __APPLE__
    98 # include <link.h>
    99 #endif
   100 # include <stdint.h>
   101 # include <inttypes.h>
   102 # include <sys/ioctl.h>
   104 #if defined(__FreeBSD__) || defined(__NetBSD__)
   105 # include <elf.h>
   106 #endif
   108 #ifdef __APPLE__
   109 # include <mach/mach.h> // semaphore_* API
   110 # include <mach-o/dyld.h>
   111 # include <sys/proc_info.h>
   112 # include <objc/objc-auto.h>
   113 #endif
   115 #ifndef MAP_ANONYMOUS
   116 #define MAP_ANONYMOUS MAP_ANON
   117 #endif
   119 #define MAX_PATH    (2 * K)
   121 // for timer info max values which include all bits
   122 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
   124 #define LARGEPAGES_BIT (1 << 6)
   125 ////////////////////////////////////////////////////////////////////////////////
   126 // global variables
   127 julong os::Bsd::_physical_memory = 0;
   130 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
   131 pthread_t os::Bsd::_main_thread;
   132 int os::Bsd::_page_size = -1;
   134 static jlong initial_time_count=0;
   136 static int clock_tics_per_sec = 100;
   138 // For diagnostics to print a message once. see run_periodic_checks
   139 static sigset_t check_signal_done;
   140 static bool check_signals = true;
   142 static pid_t _initial_pid = 0;
   144 /* Signal number used to suspend/resume a thread */
   146 /* do not use any signal number less than SIGSEGV, see 4355769 */
   147 static int SR_signum = SIGUSR2;
   148 sigset_t SR_sigset;
   151 ////////////////////////////////////////////////////////////////////////////////
   152 // utility functions
   154 static int SR_initialize();
   156 julong os::available_memory() {
   157   return Bsd::available_memory();
   158 }
   160 julong os::Bsd::available_memory() {
   161   // XXXBSD: this is just a stopgap implementation
   162   return physical_memory() >> 2;
   163 }
   165 julong os::physical_memory() {
   166   return Bsd::physical_memory();
   167 }
   169 ////////////////////////////////////////////////////////////////////////////////
   170 // environment support
   172 bool os::getenv(const char* name, char* buf, int len) {
   173   const char* val = ::getenv(name);
   174   if (val != NULL && strlen(val) < (size_t)len) {
   175     strcpy(buf, val);
   176     return true;
   177   }
   178   if (len > 0) buf[0] = 0;  // return a null string
   179   return false;
   180 }
   183 // Return true if user is running as root.
   185 bool os::have_special_privileges() {
   186   static bool init = false;
   187   static bool privileges = false;
   188   if (!init) {
   189     privileges = (getuid() != geteuid()) || (getgid() != getegid());
   190     init = true;
   191   }
   192   return privileges;
   193 }
   197 // Cpu architecture string
   198 #if   defined(ZERO)
   199 static char cpu_arch[] = ZERO_LIBARCH;
   200 #elif defined(IA64)
   201 static char cpu_arch[] = "ia64";
   202 #elif defined(IA32)
   203 static char cpu_arch[] = "i386";
   204 #elif defined(AMD64)
   205 static char cpu_arch[] = "amd64";
   206 #elif defined(ARM)
   207 static char cpu_arch[] = "arm";
   208 #elif defined(PPC32)
   209 static char cpu_arch[] = "ppc";
   210 #elif defined(SPARC)
   211 #  ifdef _LP64
   212 static char cpu_arch[] = "sparcv9";
   213 #  else
   214 static char cpu_arch[] = "sparc";
   215 #  endif
   216 #else
   217 #error Add appropriate cpu_arch setting
   218 #endif
   220 // Compiler variant
   221 #ifdef COMPILER2
   222 #define COMPILER_VARIANT "server"
   223 #else
   224 #define COMPILER_VARIANT "client"
   225 #endif
   228 void os::Bsd::initialize_system_info() {
   229   int mib[2];
   230   size_t len;
   231   int cpu_val;
   232   julong mem_val;
   234   /* get processors count via hw.ncpus sysctl */
   235   mib[0] = CTL_HW;
   236   mib[1] = HW_NCPU;
   237   len = sizeof(cpu_val);
   238   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
   239        assert(len == sizeof(cpu_val), "unexpected data size");
   240        set_processor_count(cpu_val);
   241   }
   242   else {
   243        set_processor_count(1);   // fallback
   244   }
   246   /* get physical memory via hw.memsize sysctl (hw.memsize is used
   247    * since it returns a 64 bit value)
   248    */
   249   mib[0] = CTL_HW;
   250   mib[1] = HW_MEMSIZE;
   251   len = sizeof(mem_val);
   252   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
   253        assert(len == sizeof(mem_val), "unexpected data size");
   254        _physical_memory = mem_val;
   255   } else {
   256        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
   257   }
   259 #ifdef __OpenBSD__
   260   {
   261        // limit _physical_memory memory view on OpenBSD since
   262        // datasize rlimit restricts us anyway.
   263        struct rlimit limits;
   264        getrlimit(RLIMIT_DATA, &limits);
   265        _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
   266   }
   267 #endif
   268 }
   270 #ifdef __APPLE__
   271 static const char *get_home() {
   272   const char *home_dir = ::getenv("HOME");
   273   if ((home_dir == NULL) || (*home_dir == '\0')) {
   274     struct passwd *passwd_info = getpwuid(geteuid());
   275     if (passwd_info != NULL) {
   276       home_dir = passwd_info->pw_dir;
   277     }
   278   }
   280   return home_dir;
   281 }
   282 #endif
   284 void os::init_system_properties_values() {
   285 //  char arch[12];
   286 //  sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
   288   // The next steps are taken in the product version:
   289   //
   290   // Obtain the JAVA_HOME value from the location of libjvm.so.
   291   // This library should be located at:
   292   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
   293   //
   294   // If "/jre/lib/" appears at the right place in the path, then we
   295   // assume libjvm.so is installed in a JDK and we use this path.
   296   //
   297   // Otherwise exit with message: "Could not create the Java virtual machine."
   298   //
   299   // The following extra steps are taken in the debugging version:
   300   //
   301   // If "/jre/lib/" does NOT appear at the right place in the path
   302   // instead of exit check for $JAVA_HOME environment variable.
   303   //
   304   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
   305   // then we append a fake suffix "hotspot/libjvm.so" to this path so
   306   // it looks like libjvm.so is installed there
   307   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
   308   //
   309   // Otherwise exit.
   310   //
   311   // Important note: if the location of libjvm.so changes this
   312   // code needs to be changed accordingly.
   314   // The next few definitions allow the code to be verbatim:
   315 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
   316 #define getenv(n) ::getenv(n)
   318 /*
   319  * See ld(1):
   320  *      The linker uses the following search paths to locate required
   321  *      shared libraries:
   322  *        1: ...
   323  *        ...
   324  *        7: The default directories, normally /lib and /usr/lib.
   325  */
   326 #ifndef DEFAULT_LIBPATH
   327 #define DEFAULT_LIBPATH "/lib:/usr/lib"
   328 #endif
   330 #define EXTENSIONS_DIR  "/lib/ext"
   331 #define ENDORSED_DIR    "/lib/endorsed"
   332 #define REG_DIR         "/usr/java/packages"
   334 #ifdef __APPLE__
   335 #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
   336 #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
   337         const char *user_home_dir = get_home();
   338         // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
   339         int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
   340             sizeof(SYS_EXTENSIONS_DIRS);
   341 #endif
   343   {
   344     /* sysclasspath, java_home, dll_dir */
   345     {
   346         char *home_path;
   347         char *dll_path;
   348         char *pslash;
   349         char buf[MAXPATHLEN];
   350         os::jvm_path(buf, sizeof(buf));
   352         // Found the full path to libjvm.so.
   353         // Now cut the path to <java_home>/jre if we can.
   354         *(strrchr(buf, '/')) = '\0';  /* get rid of /libjvm.so */
   355         pslash = strrchr(buf, '/');
   356         if (pslash != NULL)
   357             *pslash = '\0';           /* get rid of /{client|server|hotspot} */
   358         dll_path = malloc(strlen(buf) + 1);
   359         if (dll_path == NULL)
   360             return;
   361         strcpy(dll_path, buf);
   362         Arguments::set_dll_dir(dll_path);
   364         if (pslash != NULL) {
   365             pslash = strrchr(buf, '/');
   366             if (pslash != NULL) {
   367                 *pslash = '\0';       /* get rid of /<arch> (/lib on macosx) */
   368 #ifndef __APPLE__
   369                 pslash = strrchr(buf, '/');
   370                 if (pslash != NULL)
   371                     *pslash = '\0';   /* get rid of /lib */
   372 #endif
   373             }
   374         }
   376         home_path = malloc(strlen(buf) + 1);
   377         if (home_path == NULL)
   378             return;
   379         strcpy(home_path, buf);
   380         Arguments::set_java_home(home_path);
   382         if (!set_boot_path('/', ':'))
   383             return;
   384     }
   386     /*
   387      * Where to look for native libraries
   388      *
   389      * Note: Due to a legacy implementation, most of the library path
   390      * is set in the launcher.  This was to accomodate linking restrictions
   391      * on legacy Bsd implementations (which are no longer supported).
   392      * Eventually, all the library path setting will be done here.
   393      *
   394      * However, to prevent the proliferation of improperly built native
   395      * libraries, the new path component /usr/java/packages is added here.
   396      * Eventually, all the library path setting will be done here.
   397      */
   398     {
   399         char *ld_library_path;
   401         /*
   402          * Construct the invariant part of ld_library_path. Note that the
   403          * space for the colon and the trailing null are provided by the
   404          * nulls included by the sizeof operator (so actually we allocate
   405          * a byte more than necessary).
   406          */
   407 #ifdef __APPLE__
   408         ld_library_path = (char *) malloc(system_ext_size);
   409         sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir);
   410 #else
   411         ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
   412             strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
   413         sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
   414 #endif
   416         /*
   417          * Get the user setting of LD_LIBRARY_PATH, and prepended it.  It
   418          * should always exist (until the legacy problem cited above is
   419          * addressed).
   420          */
   421 #ifdef __APPLE__
   422         // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
   423         char *l = getenv("JAVA_LIBRARY_PATH");
   424         if (l != NULL) {
   425             char *t = ld_library_path;
   426             /* That's +1 for the colon and +1 for the trailing '\0' */
   427             ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1);
   428             sprintf(ld_library_path, "%s:%s", l, t);
   429             free(t);
   430         }
   432         char *v = getenv("DYLD_LIBRARY_PATH");
   433 #else
   434         char *v = getenv("LD_LIBRARY_PATH");
   435 #endif
   436         if (v != NULL) {
   437             char *t = ld_library_path;
   438             /* That's +1 for the colon and +1 for the trailing '\0' */
   439             ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
   440             sprintf(ld_library_path, "%s:%s", v, t);
   441             free(t);
   442         }
   444 #ifdef __APPLE__
   445         // Apple's Java6 has "." at the beginning of java.library.path.
   446         // OpenJDK on Windows has "." at the end of java.library.path.
   447         // OpenJDK on Linux and Solaris don't have "." in java.library.path
   448         // at all. To ease the transition from Apple's Java6 to OpenJDK7,
   449         // "." is appended to the end of java.library.path. Yes, this
   450         // could cause a change in behavior, but Apple's Java6 behavior
   451         // can be achieved by putting "." at the beginning of the
   452         // JAVA_LIBRARY_PATH environment variable.
   453         {
   454             char *t = ld_library_path;
   455             // that's +3 for appending ":." and the trailing '\0'
   456             ld_library_path = (char *) malloc(strlen(t) + 3);
   457             sprintf(ld_library_path, "%s:%s", t, ".");
   458             free(t);
   459         }
   460 #endif
   462         Arguments::set_library_path(ld_library_path);
   463     }
   465     /*
   466      * Extensions directories.
   467      *
   468      * Note that the space for the colon and the trailing null are provided
   469      * by the nulls included by the sizeof operator (so actually one byte more
   470      * than necessary is allocated).
   471      */
   472     {
   473 #ifdef __APPLE__
   474         char *buf = malloc(strlen(Arguments::get_java_home()) +
   475             sizeof(EXTENSIONS_DIR) + system_ext_size);
   476         sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":"
   477             SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home());
   478 #else
   479         char *buf = malloc(strlen(Arguments::get_java_home()) +
   480             sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
   481         sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
   482             Arguments::get_java_home());
   483 #endif
   485         Arguments::set_ext_dirs(buf);
   486     }
   488     /* Endorsed standards default directory. */
   489     {
   490         char * buf;
   491         buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
   492         sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
   493         Arguments::set_endorsed_dirs(buf);
   494     }
   495   }
   497 #ifdef __APPLE__
   498 #undef SYS_EXTENSIONS_DIR
   499 #endif
   500 #undef malloc
   501 #undef getenv
   502 #undef EXTENSIONS_DIR
   503 #undef ENDORSED_DIR
   505   // Done
   506   return;
   507 }
   509 ////////////////////////////////////////////////////////////////////////////////
   510 // breakpoint support
   512 void os::breakpoint() {
   513   BREAKPOINT;
   514 }
   516 extern "C" void breakpoint() {
   517   // use debugger to set breakpoint here
   518 }
   520 ////////////////////////////////////////////////////////////////////////////////
   521 // signal support
   523 debug_only(static bool signal_sets_initialized = false);
   524 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
   526 bool os::Bsd::is_sig_ignored(int sig) {
   527       struct sigaction oact;
   528       sigaction(sig, (struct sigaction*)NULL, &oact);
   529       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
   530                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
   531       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
   532            return true;
   533       else
   534            return false;
   535 }
   537 void os::Bsd::signal_sets_init() {
   538   // Should also have an assertion stating we are still single-threaded.
   539   assert(!signal_sets_initialized, "Already initialized");
   540   // Fill in signals that are necessarily unblocked for all threads in
   541   // the VM. Currently, we unblock the following signals:
   542   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
   543   //                         by -Xrs (=ReduceSignalUsage));
   544   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
   545   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
   546   // the dispositions or masks wrt these signals.
   547   // Programs embedding the VM that want to use the above signals for their
   548   // own purposes must, at this time, use the "-Xrs" option to prevent
   549   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
   550   // (See bug 4345157, and other related bugs).
   551   // In reality, though, unblocking these signals is really a nop, since
   552   // these signals are not blocked by default.
   553   sigemptyset(&unblocked_sigs);
   554   sigemptyset(&allowdebug_blocked_sigs);
   555   sigaddset(&unblocked_sigs, SIGILL);
   556   sigaddset(&unblocked_sigs, SIGSEGV);
   557   sigaddset(&unblocked_sigs, SIGBUS);
   558   sigaddset(&unblocked_sigs, SIGFPE);
   559   sigaddset(&unblocked_sigs, SR_signum);
   561   if (!ReduceSignalUsage) {
   562    if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
   563       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
   564       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
   565    }
   566    if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
   567       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
   568       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
   569    }
   570    if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
   571       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
   572       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
   573    }
   574   }
   575   // Fill in signals that are blocked by all but the VM thread.
   576   sigemptyset(&vm_sigs);
   577   if (!ReduceSignalUsage)
   578     sigaddset(&vm_sigs, BREAK_SIGNAL);
   579   debug_only(signal_sets_initialized = true);
   581 }
   583 // These are signals that are unblocked while a thread is running Java.
   584 // (For some reason, they get blocked by default.)
   585 sigset_t* os::Bsd::unblocked_signals() {
   586   assert(signal_sets_initialized, "Not initialized");
   587   return &unblocked_sigs;
   588 }
   590 // These are the signals that are blocked while a (non-VM) thread is
   591 // running Java. Only the VM thread handles these signals.
   592 sigset_t* os::Bsd::vm_signals() {
   593   assert(signal_sets_initialized, "Not initialized");
   594   return &vm_sigs;
   595 }
   597 // These are signals that are blocked during cond_wait to allow debugger in
   598 sigset_t* os::Bsd::allowdebug_blocked_signals() {
   599   assert(signal_sets_initialized, "Not initialized");
   600   return &allowdebug_blocked_sigs;
   601 }
   603 void os::Bsd::hotspot_sigmask(Thread* thread) {
   605   //Save caller's signal mask before setting VM signal mask
   606   sigset_t caller_sigmask;
   607   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
   609   OSThread* osthread = thread->osthread();
   610   osthread->set_caller_sigmask(caller_sigmask);
   612   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
   614   if (!ReduceSignalUsage) {
   615     if (thread->is_VM_thread()) {
   616       // Only the VM thread handles BREAK_SIGNAL ...
   617       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
   618     } else {
   619       // ... all other threads block BREAK_SIGNAL
   620       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
   621     }
   622   }
   623 }
   626 //////////////////////////////////////////////////////////////////////////////
   627 // create new thread
   629 // check if it's safe to start a new thread
   630 static bool _thread_safety_check(Thread* thread) {
   631   return true;
   632 }
   634 #ifdef __APPLE__
   635 // library handle for calling objc_registerThreadWithCollector()
   636 // without static linking to the libobjc library
   637 #define OBJC_LIB "/usr/lib/libobjc.dylib"
   638 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
   639 typedef void (*objc_registerThreadWithCollector_t)();
   640 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
   641 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
   642 #endif
   644 #ifdef __APPLE__
   645 static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {
   646   // Additional thread_id used to correlate threads in SA
   647   thread_identifier_info_data_t     m_ident_info;
   648   mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
   650   thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,
   651               (thread_info_t) &m_ident_info, &count);
   653   return m_ident_info.thread_id;
   654 }
   655 #endif
   657 // Thread start routine for all newly created threads
   658 static void *java_start(Thread *thread) {
   659   // Try to randomize the cache line index of hot stack frames.
   660   // This helps when threads of the same stack traces evict each other's
   661   // cache lines. The threads can be either from the same JVM instance, or
   662   // from different JVM instances. The benefit is especially true for
   663   // processors with hyperthreading technology.
   664   static int counter = 0;
   665   int pid = os::current_process_id();
   666   alloca(((pid ^ counter++) & 7) * 128);
   668   ThreadLocalStorage::set_thread(thread);
   670   OSThread* osthread = thread->osthread();
   671   Monitor* sync = osthread->startThread_lock();
   673   // non floating stack BsdThreads needs extra check, see above
   674   if (!_thread_safety_check(thread)) {
   675     // notify parent thread
   676     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   677     osthread->set_state(ZOMBIE);
   678     sync->notify_all();
   679     return NULL;
   680   }
   682 #ifdef __APPLE__
   683   // thread_id is mach thread on macos, which pthreads graciously caches and provides for us
   684   mach_port_t thread_id = ::pthread_mach_thread_np(::pthread_self());
   685   guarantee(thread_id != 0, "thread id missing from pthreads");
   686   osthread->set_thread_id(thread_id);
   688   uint64_t unique_thread_id = locate_unique_thread_id(thread_id);
   689   guarantee(unique_thread_id != 0, "unique thread id was not found");
   690   osthread->set_unique_thread_id(unique_thread_id);
   691 #else
   692   // thread_id is pthread_id on BSD
   693   osthread->set_thread_id(::pthread_self());
   694 #endif
   695   // initialize signal mask for this thread
   696   os::Bsd::hotspot_sigmask(thread);
   698   // initialize floating point control register
   699   os::Bsd::init_thread_fpu_state();
   701 #ifdef __APPLE__
   702   // register thread with objc gc
   703   if (objc_registerThreadWithCollectorFunction != NULL) {
   704     objc_registerThreadWithCollectorFunction();
   705   }
   706 #endif
   708   // handshaking with parent thread
   709   {
   710     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   712     // notify parent thread
   713     osthread->set_state(INITIALIZED);
   714     sync->notify_all();
   716     // wait until os::start_thread()
   717     while (osthread->get_state() == INITIALIZED) {
   718       sync->wait(Mutex::_no_safepoint_check_flag);
   719     }
   720   }
   722   // call one more level start routine
   723   thread->run();
   725   return 0;
   726 }
   728 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
   729   assert(thread->osthread() == NULL, "caller responsible");
   731   // Allocate the OSThread object
   732   OSThread* osthread = new OSThread(NULL, NULL);
   733   if (osthread == NULL) {
   734     return false;
   735   }
   737   // set the correct thread state
   738   osthread->set_thread_type(thr_type);
   740   // Initial state is ALLOCATED but not INITIALIZED
   741   osthread->set_state(ALLOCATED);
   743   thread->set_osthread(osthread);
   745   // init thread attributes
   746   pthread_attr_t attr;
   747   pthread_attr_init(&attr);
   748   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   750   // stack size
   751   if (os::Bsd::supports_variable_stack_size()) {
   752     // calculate stack size if it's not specified by caller
   753     if (stack_size == 0) {
   754       stack_size = os::Bsd::default_stack_size(thr_type);
   756       switch (thr_type) {
   757       case os::java_thread:
   758         // Java threads use ThreadStackSize which default value can be
   759         // changed with the flag -Xss
   760         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
   761         stack_size = JavaThread::stack_size_at_create();
   762         break;
   763       case os::compiler_thread:
   764         if (CompilerThreadStackSize > 0) {
   765           stack_size = (size_t)(CompilerThreadStackSize * K);
   766           break;
   767         } // else fall through:
   768           // use VMThreadStackSize if CompilerThreadStackSize is not defined
   769       case os::vm_thread:
   770       case os::pgc_thread:
   771       case os::cgc_thread:
   772       case os::watcher_thread:
   773         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
   774         break;
   775       }
   776     }
   778     stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
   779     pthread_attr_setstacksize(&attr, stack_size);
   780   } else {
   781     // let pthread_create() pick the default value.
   782   }
   784   ThreadState state;
   786   {
   787     pthread_t tid;
   788     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
   790     pthread_attr_destroy(&attr);
   792     if (ret != 0) {
   793       if (PrintMiscellaneous && (Verbose || WizardMode)) {
   794         perror("pthread_create()");
   795       }
   796       // Need to clean up stuff we've allocated so far
   797       thread->set_osthread(NULL);
   798       delete osthread;
   799       return false;
   800     }
   802     // Store pthread info into the OSThread
   803     osthread->set_pthread_id(tid);
   805     // Wait until child thread is either initialized or aborted
   806     {
   807       Monitor* sync_with_child = osthread->startThread_lock();
   808       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   809       while ((state = osthread->get_state()) == ALLOCATED) {
   810         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
   811       }
   812     }
   814   }
   816   // Aborted due to thread limit being reached
   817   if (state == ZOMBIE) {
   818       thread->set_osthread(NULL);
   819       delete osthread;
   820       return false;
   821   }
   823   // The thread is returned suspended (in state INITIALIZED),
   824   // and is started higher up in the call chain
   825   assert(state == INITIALIZED, "race condition");
   826   return true;
   827 }
   829 /////////////////////////////////////////////////////////////////////////////
   830 // attach existing thread
   832 // bootstrap the main thread
   833 bool os::create_main_thread(JavaThread* thread) {
   834   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
   835   return create_attached_thread(thread);
   836 }
   838 bool os::create_attached_thread(JavaThread* thread) {
   839 #ifdef ASSERT
   840     thread->verify_not_published();
   841 #endif
   843   // Allocate the OSThread object
   844   OSThread* osthread = new OSThread(NULL, NULL);
   846   if (osthread == NULL) {
   847     return false;
   848   }
   850   // Store pthread info into the OSThread
   851 #ifdef __APPLE__
   852   // thread_id is mach thread on macos, which pthreads graciously caches and provides for us
   853   mach_port_t thread_id = ::pthread_mach_thread_np(::pthread_self());
   854   guarantee(thread_id != 0, "just checking");
   855   osthread->set_thread_id(thread_id);
   857   uint64_t unique_thread_id = locate_unique_thread_id(thread_id);
   858   guarantee(unique_thread_id != 0, "just checking");
   859   osthread->set_unique_thread_id(unique_thread_id);
   860 #else
   861   osthread->set_thread_id(::pthread_self());
   862 #endif
   863   osthread->set_pthread_id(::pthread_self());
   865   // initialize floating point control register
   866   os::Bsd::init_thread_fpu_state();
   868   // Initial thread state is RUNNABLE
   869   osthread->set_state(RUNNABLE);
   871   thread->set_osthread(osthread);
   873   // initialize signal mask for this thread
   874   // and save the caller's signal mask
   875   os::Bsd::hotspot_sigmask(thread);
   877   return true;
   878 }
   880 void os::pd_start_thread(Thread* thread) {
   881   OSThread * osthread = thread->osthread();
   882   assert(osthread->get_state() != INITIALIZED, "just checking");
   883   Monitor* sync_with_child = osthread->startThread_lock();
   884   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   885   sync_with_child->notify();
   886 }
   888 // Free Bsd resources related to the OSThread
   889 void os::free_thread(OSThread* osthread) {
   890   assert(osthread != NULL, "osthread not set");
   892   if (Thread::current()->osthread() == osthread) {
   893     // Restore caller's signal mask
   894     sigset_t sigmask = osthread->caller_sigmask();
   895     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   896    }
   898   delete osthread;
   899 }
   901 //////////////////////////////////////////////////////////////////////////////
   902 // thread local storage
   904 int os::allocate_thread_local_storage() {
   905   pthread_key_t key;
   906   int rslt = pthread_key_create(&key, NULL);
   907   assert(rslt == 0, "cannot allocate thread local storage");
   908   return (int)key;
   909 }
   911 // Note: This is currently not used by VM, as we don't destroy TLS key
   912 // on VM exit.
   913 void os::free_thread_local_storage(int index) {
   914   int rslt = pthread_key_delete((pthread_key_t)index);
   915   assert(rslt == 0, "invalid index");
   916 }
   918 void os::thread_local_storage_at_put(int index, void* value) {
   919   int rslt = pthread_setspecific((pthread_key_t)index, value);
   920   assert(rslt == 0, "pthread_setspecific failed");
   921 }
   923 extern "C" Thread* get_thread() {
   924   return ThreadLocalStorage::thread();
   925 }
   928 ////////////////////////////////////////////////////////////////////////////////
   929 // time support
   931 // Time since start-up in seconds to a fine granularity.
   932 // Used by VMSelfDestructTimer and the MemProfiler.
   933 double os::elapsedTime() {
   935   return (double)(os::elapsed_counter()) * 0.000001;
   936 }
   938 jlong os::elapsed_counter() {
   939   timeval time;
   940   int status = gettimeofday(&time, NULL);
   941   return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
   942 }
   944 jlong os::elapsed_frequency() {
   945   return (1000 * 1000);
   946 }
   948 bool os::supports_vtime() { return true; }
   949 bool os::enable_vtime()   { return false; }
   950 bool os::vtime_enabled()  { return false; }
   952 double os::elapsedVTime() {
   953   // better than nothing, but not much
   954   return elapsedTime();
   955 }
   957 jlong os::javaTimeMillis() {
   958   timeval time;
   959   int status = gettimeofday(&time, NULL);
   960   assert(status != -1, "bsd error");
   961   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   962 }
   964 #ifndef CLOCK_MONOTONIC
   965 #define CLOCK_MONOTONIC (1)
   966 #endif
   968 #ifdef __APPLE__
   969 void os::Bsd::clock_init() {
   970         // XXXDARWIN: Investigate replacement monotonic clock
   971 }
   972 #else
   973 void os::Bsd::clock_init() {
   974   struct timespec res;
   975   struct timespec tp;
   976   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
   977       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
   978     // yes, monotonic clock is supported
   979     _clock_gettime = ::clock_gettime;
   980   }
   981 }
   982 #endif
   985 jlong os::javaTimeNanos() {
   986   if (Bsd::supports_monotonic_clock()) {
   987     struct timespec tp;
   988     int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
   989     assert(status == 0, "gettime error");
   990     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
   991     return result;
   992   } else {
   993     timeval time;
   994     int status = gettimeofday(&time, NULL);
   995     assert(status != -1, "bsd error");
   996     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
   997     return 1000 * usecs;
   998   }
   999 }
  1001 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
  1002   if (Bsd::supports_monotonic_clock()) {
  1003     info_ptr->max_value = ALL_64_BITS;
  1005     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
  1006     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
  1007     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
  1008   } else {
  1009     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
  1010     info_ptr->max_value = ALL_64_BITS;
  1012     // gettimeofday is a real time clock so it skips
  1013     info_ptr->may_skip_backward = true;
  1014     info_ptr->may_skip_forward = true;
  1017   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
  1020 // Return the real, user, and system times in seconds from an
  1021 // arbitrary fixed point in the past.
  1022 bool os::getTimesSecs(double* process_real_time,
  1023                       double* process_user_time,
  1024                       double* process_system_time) {
  1025   struct tms ticks;
  1026   clock_t real_ticks = times(&ticks);
  1028   if (real_ticks == (clock_t) (-1)) {
  1029     return false;
  1030   } else {
  1031     double ticks_per_second = (double) clock_tics_per_sec;
  1032     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
  1033     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
  1034     *process_real_time = ((double) real_ticks) / ticks_per_second;
  1036     return true;
  1041 char * os::local_time_string(char *buf, size_t buflen) {
  1042   struct tm t;
  1043   time_t long_time;
  1044   time(&long_time);
  1045   localtime_r(&long_time, &t);
  1046   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  1047                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
  1048                t.tm_hour, t.tm_min, t.tm_sec);
  1049   return buf;
  1052 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
  1053   return localtime_r(clock, res);
  1056 ////////////////////////////////////////////////////////////////////////////////
  1057 // runtime exit support
  1059 // Note: os::shutdown() might be called very early during initialization, or
  1060 // called from signal handler. Before adding something to os::shutdown(), make
  1061 // sure it is async-safe and can handle partially initialized VM.
  1062 void os::shutdown() {
  1064   // allow PerfMemory to attempt cleanup of any persistent resources
  1065   perfMemory_exit();
  1067   // needs to remove object in file system
  1068   AttachListener::abort();
  1070   // flush buffered output, finish log files
  1071   ostream_abort();
  1073   // Check for abort hook
  1074   abort_hook_t abort_hook = Arguments::abort_hook();
  1075   if (abort_hook != NULL) {
  1076     abort_hook();
  1081 // Note: os::abort() might be called very early during initialization, or
  1082 // called from signal handler. Before adding something to os::abort(), make
  1083 // sure it is async-safe and can handle partially initialized VM.
  1084 void os::abort(bool dump_core) {
  1085   os::shutdown();
  1086   if (dump_core) {
  1087 #ifndef PRODUCT
  1088     fdStream out(defaultStream::output_fd());
  1089     out.print_raw("Current thread is ");
  1090     char buf[16];
  1091     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
  1092     out.print_raw_cr(buf);
  1093     out.print_raw_cr("Dumping core ...");
  1094 #endif
  1095     ::abort(); // dump core
  1098   ::exit(1);
  1101 // Die immediately, no exit hook, no abort hook, no cleanup.
  1102 void os::die() {
  1103   // _exit() on BsdThreads only kills current thread
  1104   ::abort();
  1107 // unused on bsd for now.
  1108 void os::set_error_file(const char *logfile) {}
  1111 // This method is a copy of JDK's sysGetLastErrorString
  1112 // from src/solaris/hpi/src/system_md.c
  1114 size_t os::lasterror(char *buf, size_t len) {
  1116   if (errno == 0)  return 0;
  1118   const char *s = ::strerror(errno);
  1119   size_t n = ::strlen(s);
  1120   if (n >= len) {
  1121     n = len - 1;
  1123   ::strncpy(buf, s, n);
  1124   buf[n] = '\0';
  1125   return n;
  1128 intx os::current_thread_id() {
  1129 #ifdef __APPLE__
  1130   return (intx)::pthread_mach_thread_np(::pthread_self());
  1131 #else
  1132   return (intx)::pthread_self();
  1133 #endif
  1135 int os::current_process_id() {
  1137   // Under the old bsd thread library, bsd gives each thread
  1138   // its own process id. Because of this each thread will return
  1139   // a different pid if this method were to return the result
  1140   // of getpid(2). Bsd provides no api that returns the pid
  1141   // of the launcher thread for the vm. This implementation
  1142   // returns a unique pid, the pid of the launcher thread
  1143   // that starts the vm 'process'.
  1145   // Under the NPTL, getpid() returns the same pid as the
  1146   // launcher thread rather than a unique pid per thread.
  1147   // Use gettid() if you want the old pre NPTL behaviour.
  1149   // if you are looking for the result of a call to getpid() that
  1150   // returns a unique pid for the calling thread, then look at the
  1151   // OSThread::thread_id() method in osThread_bsd.hpp file
  1153   return (int)(_initial_pid ? _initial_pid : getpid());
  1156 // DLL functions
  1158 #define JNI_LIB_PREFIX "lib"
  1159 #ifdef __APPLE__
  1160 #define JNI_LIB_SUFFIX ".dylib"
  1161 #else
  1162 #define JNI_LIB_SUFFIX ".so"
  1163 #endif
  1165 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1167 // This must be hard coded because it's the system's temporary
  1168 // directory not the java application's temp directory, ala java.io.tmpdir.
  1169 #ifdef __APPLE__
  1170 // macosx has a secure per-user temporary directory
  1171 char temp_path_storage[PATH_MAX];
  1172 const char* os::get_temp_directory() {
  1173   static char *temp_path = NULL;
  1174   if (temp_path == NULL) {
  1175     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
  1176     if (pathSize == 0 || pathSize > PATH_MAX) {
  1177       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
  1179     temp_path = temp_path_storage;
  1181   return temp_path;
  1183 #else /* __APPLE__ */
  1184 const char* os::get_temp_directory() { return "/tmp"; }
  1185 #endif /* __APPLE__ */
  1187 static bool file_exists(const char* filename) {
  1188   struct stat statbuf;
  1189   if (filename == NULL || strlen(filename) == 0) {
  1190     return false;
  1192   return os::stat(filename, &statbuf) == 0;
  1195 bool os::dll_build_name(char* buffer, size_t buflen,
  1196                         const char* pname, const char* fname) {
  1197   bool retval = false;
  1198   // Copied from libhpi
  1199   const size_t pnamelen = pname ? strlen(pname) : 0;
  1201   // Return error on buffer overflow.
  1202   if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
  1203     return retval;
  1206   if (pnamelen == 0) {
  1207     snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
  1208     retval = true;
  1209   } else if (strchr(pname, *os::path_separator()) != NULL) {
  1210     int n;
  1211     char** pelements = split_path(pname, &n);
  1212     if (pelements == NULL) {
  1213       return false;
  1215     for (int i = 0 ; i < n ; i++) {
  1216       // Really shouldn't be NULL, but check can't hurt
  1217       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1218         continue; // skip the empty path values
  1220       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1221           pelements[i], fname);
  1222       if (file_exists(buffer)) {
  1223         retval = true;
  1224         break;
  1227     // release the storage
  1228     for (int i = 0 ; i < n ; i++) {
  1229       if (pelements[i] != NULL) {
  1230         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
  1233     if (pelements != NULL) {
  1234       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
  1236   } else {
  1237     snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
  1238     retval = true;
  1240   return retval;
  1243 // check if addr is inside libjvm.so
  1244 bool os::address_is_in_vm(address addr) {
  1245   static address libjvm_base_addr;
  1246   Dl_info dlinfo;
  1248   if (libjvm_base_addr == NULL) {
  1249     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
  1250       libjvm_base_addr = (address)dlinfo.dli_fbase;
  1252     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
  1255   if (dladdr((void *)addr, &dlinfo) != 0) {
  1256     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
  1259   return false;
  1263 #define MACH_MAXSYMLEN 256
  1265 bool os::dll_address_to_function_name(address addr, char *buf,
  1266                                       int buflen, int *offset) {
  1267   // buf is not optional, but offset is optional
  1268   assert(buf != NULL, "sanity check");
  1270   Dl_info dlinfo;
  1271   char localbuf[MACH_MAXSYMLEN];
  1273   if (dladdr((void*)addr, &dlinfo) != 0) {
  1274     // see if we have a matching symbol
  1275     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
  1276       if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1277         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
  1279       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1280       return true;
  1282     // no matching symbol so try for just file info
  1283     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1284       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1285                           buf, buflen, offset, dlinfo.dli_fname)) {
  1286          return true;
  1290     // Handle non-dynamic manually:
  1291     if (dlinfo.dli_fbase != NULL &&
  1292         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
  1293                         dlinfo.dli_fbase)) {
  1294       if (!Decoder::demangle(localbuf, buf, buflen)) {
  1295         jio_snprintf(buf, buflen, "%s", localbuf);
  1297       return true;
  1300   buf[0] = '\0';
  1301   if (offset != NULL) *offset = -1;
  1302   return false;
  1305 // ported from solaris version
  1306 bool os::dll_address_to_library_name(address addr, char* buf,
  1307                                      int buflen, int* offset) {
  1308   // buf is not optional, but offset is optional
  1309   assert(buf != NULL, "sanity check");
  1311   Dl_info dlinfo;
  1313   if (dladdr((void*)addr, &dlinfo) != 0) {
  1314     if (dlinfo.dli_fname != NULL) {
  1315       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
  1317     if (dlinfo.dli_fbase != NULL && offset != NULL) {
  1318       *offset = addr - (address)dlinfo.dli_fbase;
  1320     return true;
  1323   buf[0] = '\0';
  1324   if (offset) *offset = -1;
  1325   return false;
  1328 // Loads .dll/.so and
  1329 // in case of error it checks if .dll/.so was built for the
  1330 // same architecture as Hotspot is running on
  1332 #ifdef __APPLE__
  1333 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
  1334   void * result= ::dlopen(filename, RTLD_LAZY);
  1335   if (result != NULL) {
  1336     // Successful loading
  1337     return result;
  1340   // Read system error message into ebuf
  1341   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1342   ebuf[ebuflen-1]='\0';
  1344   return NULL;
  1346 #else
  1347 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1349   void * result= ::dlopen(filename, RTLD_LAZY);
  1350   if (result != NULL) {
  1351     // Successful loading
  1352     return result;
  1355   Elf32_Ehdr elf_head;
  1357   // Read system error message into ebuf
  1358   // It may or may not be overwritten below
  1359   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1360   ebuf[ebuflen-1]='\0';
  1361   int diag_msg_max_length=ebuflen-strlen(ebuf);
  1362   char* diag_msg_buf=ebuf+strlen(ebuf);
  1364   if (diag_msg_max_length==0) {
  1365     // No more space in ebuf for additional diagnostics message
  1366     return NULL;
  1370   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
  1372   if (file_descriptor < 0) {
  1373     // Can't open library, report dlerror() message
  1374     return NULL;
  1377   bool failed_to_read_elf_head=
  1378     (sizeof(elf_head)!=
  1379         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
  1381   ::close(file_descriptor);
  1382   if (failed_to_read_elf_head) {
  1383     // file i/o error - report dlerror() msg
  1384     return NULL;
  1387   typedef struct {
  1388     Elf32_Half  code;         // Actual value as defined in elf.h
  1389     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
  1390     char        elf_class;    // 32 or 64 bit
  1391     char        endianess;    // MSB or LSB
  1392     char*       name;         // String representation
  1393   } arch_t;
  1395   #ifndef EM_486
  1396   #define EM_486          6               /* Intel 80486 */
  1397   #endif
  1399   #ifndef EM_MIPS_RS3_LE
  1400   #define EM_MIPS_RS3_LE  10              /* MIPS */
  1401   #endif
  1403   #ifndef EM_PPC64
  1404   #define EM_PPC64        21              /* PowerPC64 */
  1405   #endif
  1407   #ifndef EM_S390
  1408   #define EM_S390         22              /* IBM System/390 */
  1409   #endif
  1411   #ifndef EM_IA_64
  1412   #define EM_IA_64        50              /* HP/Intel IA-64 */
  1413   #endif
  1415   #ifndef EM_X86_64
  1416   #define EM_X86_64       62              /* AMD x86-64 */
  1417   #endif
  1419   static const arch_t arch_array[]={
  1420     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1421     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1422     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
  1423     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
  1424     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1425     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1426     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
  1427     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
  1428     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
  1429     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
  1430     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
  1431     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
  1432     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
  1433     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
  1434     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1435     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1436   };
  1438   #if  (defined IA32)
  1439     static  Elf32_Half running_arch_code=EM_386;
  1440   #elif   (defined AMD64)
  1441     static  Elf32_Half running_arch_code=EM_X86_64;
  1442   #elif  (defined IA64)
  1443     static  Elf32_Half running_arch_code=EM_IA_64;
  1444   #elif  (defined __sparc) && (defined _LP64)
  1445     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1446   #elif  (defined __sparc) && (!defined _LP64)
  1447     static  Elf32_Half running_arch_code=EM_SPARC;
  1448   #elif  (defined __powerpc64__)
  1449     static  Elf32_Half running_arch_code=EM_PPC64;
  1450   #elif  (defined __powerpc__)
  1451     static  Elf32_Half running_arch_code=EM_PPC;
  1452   #elif  (defined ARM)
  1453     static  Elf32_Half running_arch_code=EM_ARM;
  1454   #elif  (defined S390)
  1455     static  Elf32_Half running_arch_code=EM_S390;
  1456   #elif  (defined ALPHA)
  1457     static  Elf32_Half running_arch_code=EM_ALPHA;
  1458   #elif  (defined MIPSEL)
  1459     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1460   #elif  (defined PARISC)
  1461     static  Elf32_Half running_arch_code=EM_PARISC;
  1462   #elif  (defined MIPS)
  1463     static  Elf32_Half running_arch_code=EM_MIPS;
  1464   #elif  (defined M68K)
  1465     static  Elf32_Half running_arch_code=EM_68K;
  1466   #else
  1467     #error Method os::dll_load requires that one of following is defined:\
  1468          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1469   #endif
  1471   // Identify compatability class for VM's architecture and library's architecture
  1472   // Obtain string descriptions for architectures
  1474   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
  1475   int running_arch_index=-1;
  1477   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
  1478     if (running_arch_code == arch_array[i].code) {
  1479       running_arch_index    = i;
  1481     if (lib_arch.code == arch_array[i].code) {
  1482       lib_arch.compat_class = arch_array[i].compat_class;
  1483       lib_arch.name         = arch_array[i].name;
  1487   assert(running_arch_index != -1,
  1488     "Didn't find running architecture code (running_arch_code) in arch_array");
  1489   if (running_arch_index == -1) {
  1490     // Even though running architecture detection failed
  1491     // we may still continue with reporting dlerror() message
  1492     return NULL;
  1495   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
  1496     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
  1497     return NULL;
  1500 #ifndef S390
  1501   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
  1502     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
  1503     return NULL;
  1505 #endif // !S390
  1507   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1508     if ( lib_arch.name!=NULL ) {
  1509       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1510         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1511         lib_arch.name, arch_array[running_arch_index].name);
  1512     } else {
  1513       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1514       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1515         lib_arch.code,
  1516         arch_array[running_arch_index].name);
  1520   return NULL;
  1522 #endif /* !__APPLE__ */
  1524 // XXX: Do we need a lock around this as per Linux?
  1525 void* os::dll_lookup(void* handle, const char* name) {
  1526   return dlsym(handle, name);
  1530 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1531   int fd = ::open(filename, O_RDONLY);
  1532   if (fd == -1) {
  1533      return false;
  1536   char buf[32];
  1537   int bytes;
  1538   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1539     st->print_raw(buf, bytes);
  1542   ::close(fd);
  1544   return true;
  1547 void os::print_dll_info(outputStream *st) {
  1548   st->print_cr("Dynamic libraries:");
  1549 #ifdef RTLD_DI_LINKMAP
  1550   Dl_info dli;
  1551   void *handle;
  1552   Link_map *map;
  1553   Link_map *p;
  1555   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
  1556       dli.dli_fname == NULL) {
  1557     st->print_cr("Error: Cannot print dynamic libraries.");
  1558     return;
  1560   handle = dlopen(dli.dli_fname, RTLD_LAZY);
  1561   if (handle == NULL) {
  1562     st->print_cr("Error: Cannot print dynamic libraries.");
  1563     return;
  1565   dlinfo(handle, RTLD_DI_LINKMAP, &map);
  1566   if (map == NULL) {
  1567     st->print_cr("Error: Cannot print dynamic libraries.");
  1568     return;
  1571   while (map->l_prev != NULL)
  1572     map = map->l_prev;
  1574   while (map != NULL) {
  1575     st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
  1576     map = map->l_next;
  1579   dlclose(handle);
  1580 #elif defined(__APPLE__)
  1581   uint32_t count;
  1582   uint32_t i;
  1584   count = _dyld_image_count();
  1585   for (i = 1; i < count; i++) {
  1586     const char *name = _dyld_get_image_name(i);
  1587     intptr_t slide = _dyld_get_image_vmaddr_slide(i);
  1588     st->print_cr(PTR_FORMAT " \t%s", slide, name);
  1590 #else
  1591   st->print_cr("Error: Cannot print dynamic libraries.");
  1592 #endif
  1595 void os::print_os_info_brief(outputStream* st) {
  1596   st->print("Bsd");
  1598   os::Posix::print_uname_info(st);
  1601 void os::print_os_info(outputStream* st) {
  1602   st->print("OS:");
  1603   st->print("Bsd");
  1605   os::Posix::print_uname_info(st);
  1607   os::Posix::print_rlimit_info(st);
  1609   os::Posix::print_load_average(st);
  1612 void os::pd_print_cpu_info(outputStream* st) {
  1613   // Nothing to do for now.
  1616 void os::print_memory_info(outputStream* st) {
  1618   st->print("Memory:");
  1619   st->print(" %dk page", os::vm_page_size()>>10);
  1621   st->print(", physical " UINT64_FORMAT "k",
  1622             os::physical_memory() >> 10);
  1623   st->print("(" UINT64_FORMAT "k free)",
  1624             os::available_memory() >> 10);
  1625   st->cr();
  1627   // meminfo
  1628   st->print("\n/proc/meminfo:\n");
  1629   _print_ascii_file("/proc/meminfo", st);
  1630   st->cr();
  1633 void os::print_siginfo(outputStream* st, void* siginfo) {
  1634   const siginfo_t* si = (const siginfo_t*)siginfo;
  1636   os::Posix::print_siginfo_brief(st, si);
  1638   if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
  1639       UseSharedSpaces) {
  1640     FileMapInfo* mapinfo = FileMapInfo::current_info();
  1641     if (mapinfo->is_in_shared_space(si->si_addr)) {
  1642       st->print("\n\nError accessing class data sharing archive."   \
  1643                 " Mapped file inaccessible during execution, "      \
  1644                 " possible disk/network problem.");
  1647   st->cr();
  1651 static void print_signal_handler(outputStream* st, int sig,
  1652                                  char* buf, size_t buflen);
  1654 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  1655   st->print_cr("Signal Handlers:");
  1656   print_signal_handler(st, SIGSEGV, buf, buflen);
  1657   print_signal_handler(st, SIGBUS , buf, buflen);
  1658   print_signal_handler(st, SIGFPE , buf, buflen);
  1659   print_signal_handler(st, SIGPIPE, buf, buflen);
  1660   print_signal_handler(st, SIGXFSZ, buf, buflen);
  1661   print_signal_handler(st, SIGILL , buf, buflen);
  1662   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
  1663   print_signal_handler(st, SR_signum, buf, buflen);
  1664   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
  1665   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
  1666   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
  1667   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
  1670 static char saved_jvm_path[MAXPATHLEN] = {0};
  1672 // Find the full path to the current module, libjvm
  1673 void os::jvm_path(char *buf, jint buflen) {
  1674   // Error checking.
  1675   if (buflen < MAXPATHLEN) {
  1676     assert(false, "must use a large-enough buffer");
  1677     buf[0] = '\0';
  1678     return;
  1680   // Lazy resolve the path to current module.
  1681   if (saved_jvm_path[0] != 0) {
  1682     strcpy(buf, saved_jvm_path);
  1683     return;
  1686   char dli_fname[MAXPATHLEN];
  1687   bool ret = dll_address_to_library_name(
  1688                 CAST_FROM_FN_PTR(address, os::jvm_path),
  1689                 dli_fname, sizeof(dli_fname), NULL);
  1690   assert(ret, "cannot locate libjvm");
  1691   char *rp = NULL;
  1692   if (ret && dli_fname[0] != '\0') {
  1693     rp = realpath(dli_fname, buf);
  1695   if (rp == NULL)
  1696     return;
  1698   if (Arguments::created_by_gamma_launcher()) {
  1699     // Support for the gamma launcher.  Typical value for buf is
  1700     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm".  If "/jre/lib/" appears at
  1701     // the right place in the string, then assume we are installed in a JDK and
  1702     // we're done.  Otherwise, check for a JAVA_HOME environment variable and
  1703     // construct a path to the JVM being overridden.
  1705     const char *p = buf + strlen(buf) - 1;
  1706     for (int count = 0; p > buf && count < 5; ++count) {
  1707       for (--p; p > buf && *p != '/'; --p)
  1708         /* empty */ ;
  1711     if (strncmp(p, "/jre/lib/", 9) != 0) {
  1712       // Look for JAVA_HOME in the environment.
  1713       char* java_home_var = ::getenv("JAVA_HOME");
  1714       if (java_home_var != NULL && java_home_var[0] != 0) {
  1715         char* jrelib_p;
  1716         int len;
  1718         // Check the current module name "libjvm"
  1719         p = strrchr(buf, '/');
  1720         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1722         rp = realpath(java_home_var, buf);
  1723         if (rp == NULL)
  1724           return;
  1726         // determine if this is a legacy image or modules image
  1727         // modules image doesn't have "jre" subdirectory
  1728         len = strlen(buf);
  1729         jrelib_p = buf + len;
  1731         // Add the appropriate library subdir
  1732         snprintf(jrelib_p, buflen-len, "/jre/lib");
  1733         if (0 != access(buf, F_OK)) {
  1734           snprintf(jrelib_p, buflen-len, "/lib");
  1737         // Add the appropriate client or server subdir
  1738         len = strlen(buf);
  1739         jrelib_p = buf + len;
  1740         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
  1741         if (0 != access(buf, F_OK)) {
  1742           snprintf(jrelib_p, buflen-len, "");
  1745         // If the path exists within JAVA_HOME, add the JVM library name
  1746         // to complete the path to JVM being overridden.  Otherwise fallback
  1747         // to the path to the current library.
  1748         if (0 == access(buf, F_OK)) {
  1749           // Use current module name "libjvm"
  1750           len = strlen(buf);
  1751           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1752         } else {
  1753           // Fall back to path of current library
  1754           rp = realpath(dli_fname, buf);
  1755           if (rp == NULL)
  1756             return;
  1762   strcpy(saved_jvm_path, buf);
  1765 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  1766   // no prefix required, not even "_"
  1769 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  1770   // no suffix required
  1773 ////////////////////////////////////////////////////////////////////////////////
  1774 // sun.misc.Signal support
  1776 static volatile jint sigint_count = 0;
  1778 static void
  1779 UserHandler(int sig, void *siginfo, void *context) {
  1780   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1781   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1782   // don't want to flood the manager thread with sem_post requests.
  1783   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1784       return;
  1786   // Ctrl-C is pressed during error reporting, likely because the error
  1787   // handler fails to abort. Let VM die immediately.
  1788   if (sig == SIGINT && is_error_reported()) {
  1789      os::die();
  1792   os::signal_notify(sig);
  1795 void* os::user_handler() {
  1796   return CAST_FROM_FN_PTR(void*, UserHandler);
  1799 extern "C" {
  1800   typedef void (*sa_handler_t)(int);
  1801   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  1804 void* os::signal(int signal_number, void* handler) {
  1805   struct sigaction sigAct, oldSigAct;
  1807   sigfillset(&(sigAct.sa_mask));
  1808   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
  1809   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
  1811   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
  1812     // -1 means registration failed
  1813     return (void *)-1;
  1816   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
  1819 void os::signal_raise(int signal_number) {
  1820   ::raise(signal_number);
  1823 /*
  1824  * The following code is moved from os.cpp for making this
  1825  * code platform specific, which it is by its very nature.
  1826  */
  1828 // Will be modified when max signal is changed to be dynamic
  1829 int os::sigexitnum_pd() {
  1830   return NSIG;
  1833 // a counter for each possible signal value
  1834 static volatile jint pending_signals[NSIG+1] = { 0 };
  1836 // Bsd(POSIX) specific hand shaking semaphore.
  1837 #ifdef __APPLE__
  1838 typedef semaphore_t os_semaphore_t;
  1839 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1840 #define SEM_WAIT(sem)           semaphore_wait(sem)
  1841 #define SEM_POST(sem)           semaphore_signal(sem)
  1842 #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1843 #else
  1844 typedef sem_t os_semaphore_t;
  1845 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1846 #define SEM_WAIT(sem)           sem_wait(&sem)
  1847 #define SEM_POST(sem)           sem_post(&sem)
  1848 #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1849 #endif
  1851 class Semaphore : public StackObj {
  1852   public:
  1853     Semaphore();
  1854     ~Semaphore();
  1855     void signal();
  1856     void wait();
  1857     bool trywait();
  1858     bool timedwait(unsigned int sec, int nsec);
  1859   private:
  1860     jlong currenttime() const;
  1861     semaphore_t _semaphore;
  1862 };
  1864 Semaphore::Semaphore() : _semaphore(0) {
  1865   SEM_INIT(_semaphore, 0);
  1868 Semaphore::~Semaphore() {
  1869   SEM_DESTROY(_semaphore);
  1872 void Semaphore::signal() {
  1873   SEM_POST(_semaphore);
  1876 void Semaphore::wait() {
  1877   SEM_WAIT(_semaphore);
  1880 jlong Semaphore::currenttime() const {
  1881     struct timeval tv;
  1882     gettimeofday(&tv, NULL);
  1883     return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
  1886 #ifdef __APPLE__
  1887 bool Semaphore::trywait() {
  1888   return timedwait(0, 0);
  1891 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  1892   kern_return_t kr = KERN_ABORTED;
  1893   mach_timespec_t waitspec;
  1894   waitspec.tv_sec = sec;
  1895   waitspec.tv_nsec = nsec;
  1897   jlong starttime = currenttime();
  1899   kr = semaphore_timedwait(_semaphore, waitspec);
  1900   while (kr == KERN_ABORTED) {
  1901     jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
  1903     jlong current = currenttime();
  1904     jlong passedtime = current - starttime;
  1906     if (passedtime >= totalwait) {
  1907       waitspec.tv_sec = 0;
  1908       waitspec.tv_nsec = 0;
  1909     } else {
  1910       jlong waittime = totalwait - (current - starttime);
  1911       waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
  1912       waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
  1915     kr = semaphore_timedwait(_semaphore, waitspec);
  1918   return kr == KERN_SUCCESS;
  1921 #else
  1923 bool Semaphore::trywait() {
  1924   return sem_trywait(&_semaphore) == 0;
  1927 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  1928   struct timespec ts;
  1929   jlong endtime = unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
  1931   while (1) {
  1932     int result = sem_timedwait(&_semaphore, &ts);
  1933     if (result == 0) {
  1934       return true;
  1935     } else if (errno == EINTR) {
  1936       continue;
  1937     } else if (errno == ETIMEDOUT) {
  1938       return false;
  1939     } else {
  1940       return false;
  1945 #endif // __APPLE__
  1947 static os_semaphore_t sig_sem;
  1948 static Semaphore sr_semaphore;
  1950 void os::signal_init_pd() {
  1951   // Initialize signal structures
  1952   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
  1954   // Initialize signal semaphore
  1955   ::SEM_INIT(sig_sem, 0);
  1958 void os::signal_notify(int sig) {
  1959   Atomic::inc(&pending_signals[sig]);
  1960   ::SEM_POST(sig_sem);
  1963 static int check_pending_signals(bool wait) {
  1964   Atomic::store(0, &sigint_count);
  1965   for (;;) {
  1966     for (int i = 0; i < NSIG + 1; i++) {
  1967       jint n = pending_signals[i];
  1968       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  1969         return i;
  1972     if (!wait) {
  1973       return -1;
  1975     JavaThread *thread = JavaThread::current();
  1976     ThreadBlockInVM tbivm(thread);
  1978     bool threadIsSuspended;
  1979     do {
  1980       thread->set_suspend_equivalent();
  1981       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  1982       ::SEM_WAIT(sig_sem);
  1984       // were we externally suspended while we were waiting?
  1985       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  1986       if (threadIsSuspended) {
  1987         //
  1988         // The semaphore has been incremented, but while we were waiting
  1989         // another thread suspended us. We don't want to continue running
  1990         // while suspended because that would surprise the thread that
  1991         // suspended us.
  1992         //
  1993         ::SEM_POST(sig_sem);
  1995         thread->java_suspend_self();
  1997     } while (threadIsSuspended);
  2001 int os::signal_lookup() {
  2002   return check_pending_signals(false);
  2005 int os::signal_wait() {
  2006   return check_pending_signals(true);
  2009 ////////////////////////////////////////////////////////////////////////////////
  2010 // Virtual Memory
  2012 int os::vm_page_size() {
  2013   // Seems redundant as all get out
  2014   assert(os::Bsd::page_size() != -1, "must call os::init");
  2015   return os::Bsd::page_size();
  2018 // Solaris allocates memory by pages.
  2019 int os::vm_allocation_granularity() {
  2020   assert(os::Bsd::page_size() != -1, "must call os::init");
  2021   return os::Bsd::page_size();
  2024 // Rationale behind this function:
  2025 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
  2026 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
  2027 //  samples for JITted code. Here we create private executable mapping over the code cache
  2028 //  and then we can use standard (well, almost, as mapping can change) way to provide
  2029 //  info for the reporting script by storing timestamp and location of symbol
  2030 void bsd_wrap_code(char* base, size_t size) {
  2031   static volatile jint cnt = 0;
  2033   if (!UseOprofile) {
  2034     return;
  2037   char buf[PATH_MAX + 1];
  2038   int num = Atomic::add(1, &cnt);
  2040   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
  2041            os::get_temp_directory(), os::current_process_id(), num);
  2042   unlink(buf);
  2044   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
  2046   if (fd != -1) {
  2047     off_t rv = ::lseek(fd, size-2, SEEK_SET);
  2048     if (rv != (off_t)-1) {
  2049       if (::write(fd, "", 1) == 1) {
  2050         mmap(base, size,
  2051              PROT_READ|PROT_WRITE|PROT_EXEC,
  2052              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
  2055     ::close(fd);
  2056     unlink(buf);
  2060 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
  2061                                     int err) {
  2062   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
  2063           ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
  2064           strerror(err), err);
  2067 // NOTE: Bsd kernel does not really reserve the pages for us.
  2068 //       All it does is to check if there are enough free pages
  2069 //       left at the time of mmap(). This could be a potential
  2070 //       problem.
  2071 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
  2072   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
  2073 #ifdef __OpenBSD__
  2074   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2075   if (::mprotect(addr, size, prot) == 0) {
  2076     return true;
  2078 #else
  2079   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2080                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2081   if (res != (uintptr_t) MAP_FAILED) {
  2082     return true;
  2084 #endif
  2086   // Warn about any commit errors we see in non-product builds just
  2087   // in case mmap() doesn't work as described on the man page.
  2088   NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
  2090   return false;
  2093 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2094                        bool exec) {
  2095   // alignment_hint is ignored on this OS
  2096   return pd_commit_memory(addr, size, exec);
  2099 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
  2100                                   const char* mesg) {
  2101   assert(mesg != NULL, "mesg must be specified");
  2102   if (!pd_commit_memory(addr, size, exec)) {
  2103     // add extra info in product mode for vm_exit_out_of_memory():
  2104     PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
  2105     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
  2109 void os::pd_commit_memory_or_exit(char* addr, size_t size,
  2110                                   size_t alignment_hint, bool exec,
  2111                                   const char* mesg) {
  2112   // alignment_hint is ignored on this OS
  2113   pd_commit_memory_or_exit(addr, size, exec, mesg);
  2116 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2119 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2120   ::madvise(addr, bytes, MADV_DONTNEED);
  2123 void os::numa_make_global(char *addr, size_t bytes) {
  2126 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
  2129 bool os::numa_topology_changed()   { return false; }
  2131 size_t os::numa_get_groups_num() {
  2132   return 1;
  2135 int os::numa_get_group_id() {
  2136   return 0;
  2139 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2140   if (size > 0) {
  2141     ids[0] = 0;
  2142     return 1;
  2144   return 0;
  2147 bool os::get_page_info(char *start, page_info* info) {
  2148   return false;
  2151 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2152   return end;
  2156 bool os::pd_uncommit_memory(char* addr, size_t size) {
  2157 #ifdef __OpenBSD__
  2158   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2159   return ::mprotect(addr, size, PROT_NONE) == 0;
  2160 #else
  2161   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2162                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2163   return res  != (uintptr_t) MAP_FAILED;
  2164 #endif
  2167 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2168   return os::commit_memory(addr, size, !ExecMem);
  2171 // If this is a growable mapping, remove the guard pages entirely by
  2172 // munmap()ping them.  If not, just call uncommit_memory().
  2173 bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2174   return os::uncommit_memory(addr, size);
  2177 static address _highest_vm_reserved_address = NULL;
  2179 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
  2180 // at 'requested_addr'. If there are existing memory mappings at the same
  2181 // location, however, they will be overwritten. If 'fixed' is false,
  2182 // 'requested_addr' is only treated as a hint, the return value may or
  2183 // may not start from the requested address. Unlike Bsd mmap(), this
  2184 // function returns NULL to indicate failure.
  2185 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
  2186   char * addr;
  2187   int flags;
  2189   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
  2190   if (fixed) {
  2191     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
  2192     flags |= MAP_FIXED;
  2195   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
  2196   // touch an uncommitted page. Otherwise, the read/write might
  2197   // succeed if we have enough swap space to back the physical page.
  2198   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
  2199                        flags, -1, 0);
  2201   if (addr != MAP_FAILED) {
  2202     // anon_mmap() should only get called during VM initialization,
  2203     // don't need lock (actually we can skip locking even it can be called
  2204     // from multiple threads, because _highest_vm_reserved_address is just a
  2205     // hint about the upper limit of non-stack memory regions.)
  2206     if ((address)addr + bytes > _highest_vm_reserved_address) {
  2207       _highest_vm_reserved_address = (address)addr + bytes;
  2211   return addr == MAP_FAILED ? NULL : addr;
  2214 // Don't update _highest_vm_reserved_address, because there might be memory
  2215 // regions above addr + size. If so, releasing a memory region only creates
  2216 // a hole in the address space, it doesn't help prevent heap-stack collision.
  2217 //
  2218 static int anon_munmap(char * addr, size_t size) {
  2219   return ::munmap(addr, size) == 0;
  2222 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2223                          size_t alignment_hint) {
  2224   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2227 bool os::pd_release_memory(char* addr, size_t size) {
  2228   return anon_munmap(addr, size);
  2231 static bool bsd_mprotect(char* addr, size_t size, int prot) {
  2232   // Bsd wants the mprotect address argument to be page aligned.
  2233   char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
  2235   // According to SUSv3, mprotect() should only be used with mappings
  2236   // established by mmap(), and mmap() always maps whole pages. Unaligned
  2237   // 'addr' likely indicates problem in the VM (e.g. trying to change
  2238   // protection of malloc'ed or statically allocated memory). Check the
  2239   // caller if you hit this assert.
  2240   assert(addr == bottom, "sanity check");
  2242   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
  2243   return ::mprotect(bottom, size, prot) == 0;
  2246 // Set protections specified
  2247 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  2248                         bool is_committed) {
  2249   unsigned int p = 0;
  2250   switch (prot) {
  2251   case MEM_PROT_NONE: p = PROT_NONE; break;
  2252   case MEM_PROT_READ: p = PROT_READ; break;
  2253   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
  2254   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
  2255   default:
  2256     ShouldNotReachHere();
  2258   // is_committed is unused.
  2259   return bsd_mprotect(addr, bytes, p);
  2262 bool os::guard_memory(char* addr, size_t size) {
  2263   return bsd_mprotect(addr, size, PROT_NONE);
  2266 bool os::unguard_memory(char* addr, size_t size) {
  2267   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
  2270 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
  2271   return false;
  2274 // Large page support
  2276 static size_t _large_page_size = 0;
  2278 void os::large_page_init() {
  2282 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
  2283   fatal("This code is not used or maintained.");
  2285   // "exec" is passed in but not used.  Creating the shared image for
  2286   // the code cache doesn't have an SHM_X executable permission to check.
  2287   assert(UseLargePages && UseSHM, "only for SHM large pages");
  2289   key_t key = IPC_PRIVATE;
  2290   char *addr;
  2292   bool warn_on_failure = UseLargePages &&
  2293                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2294                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2295                         );
  2296   char msg[128];
  2298   // Create a large shared memory region to attach to based on size.
  2299   // Currently, size is the total size of the heap
  2300   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2301   if (shmid == -1) {
  2302      // Possible reasons for shmget failure:
  2303      // 1. shmmax is too small for Java heap.
  2304      //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2305      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2306      // 2. not enough large page memory.
  2307      //    > check available large pages: cat /proc/meminfo
  2308      //    > increase amount of large pages:
  2309      //          echo new_value > /proc/sys/vm/nr_hugepages
  2310      //      Note 1: different Bsd may use different name for this property,
  2311      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2312      //      Note 2: it's possible there's enough physical memory available but
  2313      //            they are so fragmented after a long run that they can't
  2314      //            coalesce into large pages. Try to reserve large pages when
  2315      //            the system is still "fresh".
  2316      if (warn_on_failure) {
  2317        jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
  2318        warning(msg);
  2320      return NULL;
  2323   // attach to the region
  2324   addr = (char*)shmat(shmid, req_addr, 0);
  2325   int err = errno;
  2327   // Remove shmid. If shmat() is successful, the actual shared memory segment
  2328   // will be deleted when it's detached by shmdt() or when the process
  2329   // terminates. If shmat() is not successful this will remove the shared
  2330   // segment immediately.
  2331   shmctl(shmid, IPC_RMID, NULL);
  2333   if ((intptr_t)addr == -1) {
  2334      if (warn_on_failure) {
  2335        jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
  2336        warning(msg);
  2338      return NULL;
  2341   // The memory is committed
  2342   MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
  2344   return addr;
  2347 bool os::release_memory_special(char* base, size_t bytes) {
  2348   MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
  2349   // detaching the SHM segment will also delete it, see reserve_memory_special()
  2350   int rslt = shmdt(base);
  2351   if (rslt == 0) {
  2352     tkr.record((address)base, bytes);
  2353     return true;
  2354   } else {
  2355     tkr.discard();
  2356     return false;
  2361 size_t os::large_page_size() {
  2362   return _large_page_size;
  2365 // HugeTLBFS allows application to commit large page memory on demand;
  2366 // with SysV SHM the entire memory region must be allocated as shared
  2367 // memory.
  2368 bool os::can_commit_large_page_memory() {
  2369   return UseHugeTLBFS;
  2372 bool os::can_execute_large_page_memory() {
  2373   return UseHugeTLBFS;
  2376 // Reserve memory at an arbitrary address, only if that area is
  2377 // available (and not reserved for something else).
  2379 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2380   const int max_tries = 10;
  2381   char* base[max_tries];
  2382   size_t size[max_tries];
  2383   const size_t gap = 0x000000;
  2385   // Assert only that the size is a multiple of the page size, since
  2386   // that's all that mmap requires, and since that's all we really know
  2387   // about at this low abstraction level.  If we need higher alignment,
  2388   // we can either pass an alignment to this method or verify alignment
  2389   // in one of the methods further up the call chain.  See bug 5044738.
  2390   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
  2392   // Repeatedly allocate blocks until the block is allocated at the
  2393   // right spot. Give up after max_tries. Note that reserve_memory() will
  2394   // automatically update _highest_vm_reserved_address if the call is
  2395   // successful. The variable tracks the highest memory address every reserved
  2396   // by JVM. It is used to detect heap-stack collision if running with
  2397   // fixed-stack BsdThreads. Because here we may attempt to reserve more
  2398   // space than needed, it could confuse the collision detecting code. To
  2399   // solve the problem, save current _highest_vm_reserved_address and
  2400   // calculate the correct value before return.
  2401   address old_highest = _highest_vm_reserved_address;
  2403   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2404   // if kernel honors the hint then we can return immediately.
  2405   char * addr = anon_mmap(requested_addr, bytes, false);
  2406   if (addr == requested_addr) {
  2407      return requested_addr;
  2410   if (addr != NULL) {
  2411      // mmap() is successful but it fails to reserve at the requested address
  2412      anon_munmap(addr, bytes);
  2415   int i;
  2416   for (i = 0; i < max_tries; ++i) {
  2417     base[i] = reserve_memory(bytes);
  2419     if (base[i] != NULL) {
  2420       // Is this the block we wanted?
  2421       if (base[i] == requested_addr) {
  2422         size[i] = bytes;
  2423         break;
  2426       // Does this overlap the block we wanted? Give back the overlapped
  2427       // parts and try again.
  2429       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
  2430       if (top_overlap >= 0 && top_overlap < bytes) {
  2431         unmap_memory(base[i], top_overlap);
  2432         base[i] += top_overlap;
  2433         size[i] = bytes - top_overlap;
  2434       } else {
  2435         size_t bottom_overlap = base[i] + bytes - requested_addr;
  2436         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
  2437           unmap_memory(requested_addr, bottom_overlap);
  2438           size[i] = bytes - bottom_overlap;
  2439         } else {
  2440           size[i] = bytes;
  2446   // Give back the unused reserved pieces.
  2448   for (int j = 0; j < i; ++j) {
  2449     if (base[j] != NULL) {
  2450       unmap_memory(base[j], size[j]);
  2454   if (i < max_tries) {
  2455     _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
  2456     return requested_addr;
  2457   } else {
  2458     _highest_vm_reserved_address = old_highest;
  2459     return NULL;
  2463 size_t os::read(int fd, void *buf, unsigned int nBytes) {
  2464   RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
  2467 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
  2468 // Solaris uses poll(), bsd uses park().
  2469 // Poll() is likely a better choice, assuming that Thread.interrupt()
  2470 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
  2471 // SIGSEGV, see 4355769.
  2473 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  2474   assert(thread == Thread::current(),  "thread consistency check");
  2476   ParkEvent * const slp = thread->_SleepEvent ;
  2477   slp->reset() ;
  2478   OrderAccess::fence() ;
  2480   if (interruptible) {
  2481     jlong prevtime = javaTimeNanos();
  2483     for (;;) {
  2484       if (os::is_interrupted(thread, true)) {
  2485         return OS_INTRPT;
  2488       jlong newtime = javaTimeNanos();
  2490       if (newtime - prevtime < 0) {
  2491         // time moving backwards, should only happen if no monotonic clock
  2492         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2493         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2494       } else {
  2495         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2498       if(millis <= 0) {
  2499         return OS_OK;
  2502       prevtime = newtime;
  2505         assert(thread->is_Java_thread(), "sanity check");
  2506         JavaThread *jt = (JavaThread *) thread;
  2507         ThreadBlockInVM tbivm(jt);
  2508         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
  2510         jt->set_suspend_equivalent();
  2511         // cleared by handle_special_suspend_equivalent_condition() or
  2512         // java_suspend_self() via check_and_wait_while_suspended()
  2514         slp->park(millis);
  2516         // were we externally suspended while we were waiting?
  2517         jt->check_and_wait_while_suspended();
  2520   } else {
  2521     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  2522     jlong prevtime = javaTimeNanos();
  2524     for (;;) {
  2525       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
  2526       // the 1st iteration ...
  2527       jlong newtime = javaTimeNanos();
  2529       if (newtime - prevtime < 0) {
  2530         // time moving backwards, should only happen if no monotonic clock
  2531         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2532         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2533       } else {
  2534         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2537       if(millis <= 0) break ;
  2539       prevtime = newtime;
  2540       slp->park(millis);
  2542     return OS_OK ;
  2546 int os::naked_sleep() {
  2547   // %% make the sleep time an integer flag. for now use 1 millisec.
  2548   return os::sleep(Thread::current(), 1, false);
  2551 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  2552 void os::infinite_sleep() {
  2553   while (true) {    // sleep forever ...
  2554     ::sleep(100);   // ... 100 seconds at a time
  2558 // Used to convert frequent JVM_Yield() to nops
  2559 bool os::dont_yield() {
  2560   return DontYieldALot;
  2563 void os::yield() {
  2564   sched_yield();
  2567 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
  2569 void os::yield_all(int attempts) {
  2570   // Yields to all threads, including threads with lower priorities
  2571   // Threads on Bsd are all with same priority. The Solaris style
  2572   // os::yield_all() with nanosleep(1ms) is not necessary.
  2573   sched_yield();
  2576 // Called from the tight loops to possibly influence time-sharing heuristics
  2577 void os::loop_breaker(int attempts) {
  2578   os::yield_all(attempts);
  2581 ////////////////////////////////////////////////////////////////////////////////
  2582 // thread priority support
  2584 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
  2585 // only supports dynamic priority, static priority must be zero. For real-time
  2586 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
  2587 // However, for large multi-threaded applications, SCHED_RR is not only slower
  2588 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
  2589 // of 5 runs - Sep 2005).
  2590 //
  2591 // The following code actually changes the niceness of kernel-thread/LWP. It
  2592 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
  2593 // not the entire user process, and user level threads are 1:1 mapped to kernel
  2594 // threads. It has always been the case, but could change in the future. For
  2595 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
  2596 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
  2598 #if !defined(__APPLE__)
  2599 int os::java_to_os_priority[CriticalPriority + 1] = {
  2600   19,              // 0 Entry should never be used
  2602    0,              // 1 MinPriority
  2603    3,              // 2
  2604    6,              // 3
  2606   10,              // 4
  2607   15,              // 5 NormPriority
  2608   18,              // 6
  2610   21,              // 7
  2611   25,              // 8
  2612   28,              // 9 NearMaxPriority
  2614   31,              // 10 MaxPriority
  2616   31               // 11 CriticalPriority
  2617 };
  2618 #else
  2619 /* Using Mach high-level priority assignments */
  2620 int os::java_to_os_priority[CriticalPriority + 1] = {
  2621    0,              // 0 Entry should never be used (MINPRI_USER)
  2623   27,              // 1 MinPriority
  2624   28,              // 2
  2625   29,              // 3
  2627   30,              // 4
  2628   31,              // 5 NormPriority (BASEPRI_DEFAULT)
  2629   32,              // 6
  2631   33,              // 7
  2632   34,              // 8
  2633   35,              // 9 NearMaxPriority
  2635   36,              // 10 MaxPriority
  2637   36               // 11 CriticalPriority
  2638 };
  2639 #endif
  2641 static int prio_init() {
  2642   if (ThreadPriorityPolicy == 1) {
  2643     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
  2644     // if effective uid is not root. Perhaps, a more elegant way of doing
  2645     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
  2646     if (geteuid() != 0) {
  2647       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
  2648         warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
  2650       ThreadPriorityPolicy = 0;
  2653   if (UseCriticalJavaThreadPriority) {
  2654     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
  2656   return 0;
  2659 OSReturn os::set_native_priority(Thread* thread, int newpri) {
  2660   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
  2662 #ifdef __OpenBSD__
  2663   // OpenBSD pthread_setprio starves low priority threads
  2664   return OS_OK;
  2665 #elif defined(__FreeBSD__)
  2666   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
  2667 #elif defined(__APPLE__) || defined(__NetBSD__)
  2668   struct sched_param sp;
  2669   int policy;
  2670   pthread_t self = pthread_self();
  2672   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2673     return OS_ERR;
  2675   sp.sched_priority = newpri;
  2676   if (pthread_setschedparam(self, policy, &sp) != 0)
  2677     return OS_ERR;
  2679   return OS_OK;
  2680 #else
  2681   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2682   return (ret == 0) ? OS_OK : OS_ERR;
  2683 #endif
  2686 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
  2687   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
  2688     *priority_ptr = java_to_os_priority[NormPriority];
  2689     return OS_OK;
  2692   errno = 0;
  2693 #if defined(__OpenBSD__) || defined(__FreeBSD__)
  2694   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
  2695 #elif defined(__APPLE__) || defined(__NetBSD__)
  2696   int policy;
  2697   struct sched_param sp;
  2699   pthread_getschedparam(pthread_self(), &policy, &sp);
  2700   *priority_ptr = sp.sched_priority;
  2701 #else
  2702   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
  2703 #endif
  2704   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
  2707 // Hint to the underlying OS that a task switch would not be good.
  2708 // Void return because it's a hint and can fail.
  2709 void os::hint_no_preempt() {}
  2711 ////////////////////////////////////////////////////////////////////////////////
  2712 // suspend/resume support
  2714 //  the low-level signal-based suspend/resume support is a remnant from the
  2715 //  old VM-suspension that used to be for java-suspension, safepoints etc,
  2716 //  within hotspot. Now there is a single use-case for this:
  2717 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
  2718 //      that runs in the watcher thread.
  2719 //  The remaining code is greatly simplified from the more general suspension
  2720 //  code that used to be used.
  2721 //
  2722 //  The protocol is quite simple:
  2723 //  - suspend:
  2724 //      - sends a signal to the target thread
  2725 //      - polls the suspend state of the osthread using a yield loop
  2726 //      - target thread signal handler (SR_handler) sets suspend state
  2727 //        and blocks in sigsuspend until continued
  2728 //  - resume:
  2729 //      - sets target osthread state to continue
  2730 //      - sends signal to end the sigsuspend loop in the SR_handler
  2731 //
  2732 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2733 //
  2735 static void resume_clear_context(OSThread *osthread) {
  2736   osthread->set_ucontext(NULL);
  2737   osthread->set_siginfo(NULL);
  2740 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2741   osthread->set_ucontext(context);
  2742   osthread->set_siginfo(siginfo);
  2745 //
  2746 // Handler function invoked when a thread's execution is suspended or
  2747 // resumed. We have to be careful that only async-safe functions are
  2748 // called here (Note: most pthread functions are not async safe and
  2749 // should be avoided.)
  2750 //
  2751 // Note: sigwait() is a more natural fit than sigsuspend() from an
  2752 // interface point of view, but sigwait() prevents the signal hander
  2753 // from being run. libpthread would get very confused by not having
  2754 // its signal handlers run and prevents sigwait()'s use with the
  2755 // mutex granting granting signal.
  2756 //
  2757 // Currently only ever called on the VMThread or JavaThread
  2758 //
  2759 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
  2760   // Save and restore errno to avoid confusing native code with EINTR
  2761   // after sigsuspend.
  2762   int old_errno = errno;
  2764   Thread* thread = Thread::current();
  2765   OSThread* osthread = thread->osthread();
  2766   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
  2768   os::SuspendResume::State current = osthread->sr.state();
  2769   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
  2770     suspend_save_context(osthread, siginfo, context);
  2772     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
  2773     os::SuspendResume::State state = osthread->sr.suspended();
  2774     if (state == os::SuspendResume::SR_SUSPENDED) {
  2775       sigset_t suspend_set;  // signals for sigsuspend()
  2777       // get current set of blocked signals and unblock resume signal
  2778       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
  2779       sigdelset(&suspend_set, SR_signum);
  2781       sr_semaphore.signal();
  2782       // wait here until we are resumed
  2783       while (1) {
  2784         sigsuspend(&suspend_set);
  2786         os::SuspendResume::State result = osthread->sr.running();
  2787         if (result == os::SuspendResume::SR_RUNNING) {
  2788           sr_semaphore.signal();
  2789           break;
  2790         } else if (result != os::SuspendResume::SR_SUSPENDED) {
  2791           ShouldNotReachHere();
  2795     } else if (state == os::SuspendResume::SR_RUNNING) {
  2796       // request was cancelled, continue
  2797     } else {
  2798       ShouldNotReachHere();
  2801     resume_clear_context(osthread);
  2802   } else if (current == os::SuspendResume::SR_RUNNING) {
  2803     // request was cancelled, continue
  2804   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
  2805     // ignore
  2806   } else {
  2807     // ignore
  2810   errno = old_errno;
  2814 static int SR_initialize() {
  2815   struct sigaction act;
  2816   char *s;
  2817   /* Get signal number to use for suspend/resume */
  2818   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2819     int sig = ::strtol(s, 0, 10);
  2820     if (sig > 0 || sig < NSIG) {
  2821         SR_signum = sig;
  2825   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2826         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2828   sigemptyset(&SR_sigset);
  2829   sigaddset(&SR_sigset, SR_signum);
  2831   /* Set up signal handler for suspend/resume */
  2832   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2833   act.sa_handler = (void (*)(int)) SR_handler;
  2835   // SR_signum is blocked by default.
  2836   // 4528190 - We also need to block pthread restart signal (32 on all
  2837   // supported Bsd platforms). Note that BsdThreads need to block
  2838   // this signal for all threads to work properly. So we don't have
  2839   // to use hard-coded signal number when setting up the mask.
  2840   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
  2842   if (sigaction(SR_signum, &act, 0) == -1) {
  2843     return -1;
  2846   // Save signal flag
  2847   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
  2848   return 0;
  2851 static int sr_notify(OSThread* osthread) {
  2852   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2853   assert_status(status == 0, status, "pthread_kill");
  2854   return status;
  2857 // "Randomly" selected value for how long we want to spin
  2858 // before bailing out on suspending a thread, also how often
  2859 // we send a signal to a thread we want to resume
  2860 static const int RANDOMLY_LARGE_INTEGER = 1000000;
  2861 static const int RANDOMLY_LARGE_INTEGER2 = 100;
  2863 // returns true on success and false on error - really an error is fatal
  2864 // but this seems the normal response to library errors
  2865 static bool do_suspend(OSThread* osthread) {
  2866   assert(osthread->sr.is_running(), "thread should be running");
  2867   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
  2869   // mark as suspended and send signal
  2870   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
  2871     // failed to switch, state wasn't running?
  2872     ShouldNotReachHere();
  2873     return false;
  2876   if (sr_notify(osthread) != 0) {
  2877     ShouldNotReachHere();
  2880   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
  2881   while (true) {
  2882     if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  2883       break;
  2884     } else {
  2885       // timeout
  2886       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
  2887       if (cancelled == os::SuspendResume::SR_RUNNING) {
  2888         return false;
  2889       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
  2890         // make sure that we consume the signal on the semaphore as well
  2891         sr_semaphore.wait();
  2892         break;
  2893       } else {
  2894         ShouldNotReachHere();
  2895         return false;
  2900   guarantee(osthread->sr.is_suspended(), "Must be suspended");
  2901   return true;
  2904 static void do_resume(OSThread* osthread) {
  2905   assert(osthread->sr.is_suspended(), "thread should be suspended");
  2906   assert(!sr_semaphore.trywait(), "invalid semaphore state");
  2908   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
  2909     // failed to switch to WAKEUP_REQUEST
  2910     ShouldNotReachHere();
  2911     return;
  2914   while (true) {
  2915     if (sr_notify(osthread) == 0) {
  2916       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  2917         if (osthread->sr.is_running()) {
  2918           return;
  2921     } else {
  2922       ShouldNotReachHere();
  2926   guarantee(osthread->sr.is_running(), "Must be running!");
  2929 ////////////////////////////////////////////////////////////////////////////////
  2930 // interrupt support
  2932 void os::interrupt(Thread* thread) {
  2933   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2934     "possibility of dangling Thread pointer");
  2936   OSThread* osthread = thread->osthread();
  2938   if (!osthread->interrupted()) {
  2939     osthread->set_interrupted(true);
  2940     // More than one thread can get here with the same value of osthread,
  2941     // resulting in multiple notifications.  We do, however, want the store
  2942     // to interrupted() to be visible to other threads before we execute unpark().
  2943     OrderAccess::fence();
  2944     ParkEvent * const slp = thread->_SleepEvent ;
  2945     if (slp != NULL) slp->unpark() ;
  2948   // For JSR166. Unpark even if interrupt status already was set
  2949   if (thread->is_Java_thread())
  2950     ((JavaThread*)thread)->parker()->unpark();
  2952   ParkEvent * ev = thread->_ParkEvent ;
  2953   if (ev != NULL) ev->unpark() ;
  2957 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  2958   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2959     "possibility of dangling Thread pointer");
  2961   OSThread* osthread = thread->osthread();
  2963   bool interrupted = osthread->interrupted();
  2965   if (interrupted && clear_interrupted) {
  2966     osthread->set_interrupted(false);
  2967     // consider thread->_SleepEvent->reset() ... optional optimization
  2970   return interrupted;
  2973 ///////////////////////////////////////////////////////////////////////////////////
  2974 // signal handling (except suspend/resume)
  2976 // This routine may be used by user applications as a "hook" to catch signals.
  2977 // The user-defined signal handler must pass unrecognized signals to this
  2978 // routine, and if it returns true (non-zero), then the signal handler must
  2979 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
  2980 // routine will never retun false (zero), but instead will execute a VM panic
  2981 // routine kill the process.
  2982 //
  2983 // If this routine returns false, it is OK to call it again.  This allows
  2984 // the user-defined signal handler to perform checks either before or after
  2985 // the VM performs its own checks.  Naturally, the user code would be making
  2986 // a serious error if it tried to handle an exception (such as a null check
  2987 // or breakpoint) that the VM was generating for its own correct operation.
  2988 //
  2989 // This routine may recognize any of the following kinds of signals:
  2990 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
  2991 // It should be consulted by handlers for any of those signals.
  2992 //
  2993 // The caller of this routine must pass in the three arguments supplied
  2994 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
  2995 // field of the structure passed to sigaction().  This routine assumes that
  2996 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2997 //
  2998 // Note that the VM will print warnings if it detects conflicting signal
  2999 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  3000 //
  3001 extern "C" JNIEXPORT int
  3002 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  3003                         void* ucontext, int abort_if_unrecognized);
  3005 void signalHandler(int sig, siginfo_t* info, void* uc) {
  3006   assert(info != NULL && uc != NULL, "it must be old kernel");
  3007   int orig_errno = errno;  // Preserve errno value over signal handler.
  3008   JVM_handle_bsd_signal(sig, info, uc, true);
  3009   errno = orig_errno;
  3013 // This boolean allows users to forward their own non-matching signals
  3014 // to JVM_handle_bsd_signal, harmlessly.
  3015 bool os::Bsd::signal_handlers_are_installed = false;
  3017 // For signal-chaining
  3018 struct sigaction os::Bsd::sigact[MAXSIGNUM];
  3019 unsigned int os::Bsd::sigs = 0;
  3020 bool os::Bsd::libjsig_is_loaded = false;
  3021 typedef struct sigaction *(*get_signal_t)(int);
  3022 get_signal_t os::Bsd::get_signal_action = NULL;
  3024 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
  3025   struct sigaction *actp = NULL;
  3027   if (libjsig_is_loaded) {
  3028     // Retrieve the old signal handler from libjsig
  3029     actp = (*get_signal_action)(sig);
  3031   if (actp == NULL) {
  3032     // Retrieve the preinstalled signal handler from jvm
  3033     actp = get_preinstalled_handler(sig);
  3036   return actp;
  3039 static bool call_chained_handler(struct sigaction *actp, int sig,
  3040                                  siginfo_t *siginfo, void *context) {
  3041   // Call the old signal handler
  3042   if (actp->sa_handler == SIG_DFL) {
  3043     // It's more reasonable to let jvm treat it as an unexpected exception
  3044     // instead of taking the default action.
  3045     return false;
  3046   } else if (actp->sa_handler != SIG_IGN) {
  3047     if ((actp->sa_flags & SA_NODEFER) == 0) {
  3048       // automaticlly block the signal
  3049       sigaddset(&(actp->sa_mask), sig);
  3052     sa_handler_t hand;
  3053     sa_sigaction_t sa;
  3054     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
  3055     // retrieve the chained handler
  3056     if (siginfo_flag_set) {
  3057       sa = actp->sa_sigaction;
  3058     } else {
  3059       hand = actp->sa_handler;
  3062     if ((actp->sa_flags & SA_RESETHAND) != 0) {
  3063       actp->sa_handler = SIG_DFL;
  3066     // try to honor the signal mask
  3067     sigset_t oset;
  3068     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
  3070     // call into the chained handler
  3071     if (siginfo_flag_set) {
  3072       (*sa)(sig, siginfo, context);
  3073     } else {
  3074       (*hand)(sig);
  3077     // restore the signal mask
  3078     pthread_sigmask(SIG_SETMASK, &oset, 0);
  3080   // Tell jvm's signal handler the signal is taken care of.
  3081   return true;
  3084 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
  3085   bool chained = false;
  3086   // signal-chaining
  3087   if (UseSignalChaining) {
  3088     struct sigaction *actp = get_chained_signal_action(sig);
  3089     if (actp != NULL) {
  3090       chained = call_chained_handler(actp, sig, siginfo, context);
  3093   return chained;
  3096 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
  3097   if ((( (unsigned int)1 << sig ) & sigs) != 0) {
  3098     return &sigact[sig];
  3100   return NULL;
  3103 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
  3104   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3105   sigact[sig] = oldAct;
  3106   sigs |= (unsigned int)1 << sig;
  3109 // for diagnostic
  3110 int os::Bsd::sigflags[MAXSIGNUM];
  3112 int os::Bsd::get_our_sigflags(int sig) {
  3113   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3114   return sigflags[sig];
  3117 void os::Bsd::set_our_sigflags(int sig, int flags) {
  3118   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3119   sigflags[sig] = flags;
  3122 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
  3123   // Check for overwrite.
  3124   struct sigaction oldAct;
  3125   sigaction(sig, (struct sigaction*)NULL, &oldAct);
  3127   void* oldhand = oldAct.sa_sigaction
  3128                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
  3129                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
  3130   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
  3131       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
  3132       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
  3133     if (AllowUserSignalHandlers || !set_installed) {
  3134       // Do not overwrite; user takes responsibility to forward to us.
  3135       return;
  3136     } else if (UseSignalChaining) {
  3137       // save the old handler in jvm
  3138       save_preinstalled_handler(sig, oldAct);
  3139       // libjsig also interposes the sigaction() call below and saves the
  3140       // old sigaction on it own.
  3141     } else {
  3142       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
  3143                     "%#lx for signal %d.", (long)oldhand, sig));
  3147   struct sigaction sigAct;
  3148   sigfillset(&(sigAct.sa_mask));
  3149   sigAct.sa_handler = SIG_DFL;
  3150   if (!set_installed) {
  3151     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3152   } else {
  3153     sigAct.sa_sigaction = signalHandler;
  3154     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3156 #if __APPLE__
  3157   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
  3158   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
  3159   // if the signal handler declares it will handle it on alternate stack.
  3160   // Notice we only declare we will handle it on alt stack, but we are not
  3161   // actually going to use real alt stack - this is just a workaround.
  3162   // Please see ux_exception.c, method catch_mach_exception_raise for details
  3163   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
  3164   if (sig == SIGSEGV) {
  3165     sigAct.sa_flags |= SA_ONSTACK;
  3167 #endif
  3169   // Save flags, which are set by ours
  3170   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3171   sigflags[sig] = sigAct.sa_flags;
  3173   int ret = sigaction(sig, &sigAct, &oldAct);
  3174   assert(ret == 0, "check");
  3176   void* oldhand2  = oldAct.sa_sigaction
  3177                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
  3178                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
  3179   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
  3182 // install signal handlers for signals that HotSpot needs to
  3183 // handle in order to support Java-level exception handling.
  3185 void os::Bsd::install_signal_handlers() {
  3186   if (!signal_handlers_are_installed) {
  3187     signal_handlers_are_installed = true;
  3189     // signal-chaining
  3190     typedef void (*signal_setting_t)();
  3191     signal_setting_t begin_signal_setting = NULL;
  3192     signal_setting_t end_signal_setting = NULL;
  3193     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3194                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3195     if (begin_signal_setting != NULL) {
  3196       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3197                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3198       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3199                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3200       libjsig_is_loaded = true;
  3201       assert(UseSignalChaining, "should enable signal-chaining");
  3203     if (libjsig_is_loaded) {
  3204       // Tell libjsig jvm is setting signal handlers
  3205       (*begin_signal_setting)();
  3208     set_signal_handler(SIGSEGV, true);
  3209     set_signal_handler(SIGPIPE, true);
  3210     set_signal_handler(SIGBUS, true);
  3211     set_signal_handler(SIGILL, true);
  3212     set_signal_handler(SIGFPE, true);
  3213     set_signal_handler(SIGXFSZ, true);
  3215 #if defined(__APPLE__)
  3216     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
  3217     // signals caught and handled by the JVM. To work around this, we reset the mach task
  3218     // signal handler that's placed on our process by CrashReporter. This disables
  3219     // CrashReporter-based reporting.
  3220     //
  3221     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
  3222     // on caught fatal signals.
  3223     //
  3224     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3225     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3226     // exception handling, while leaving the standard BSD signal handlers functional.
  3227     kern_return_t kr;
  3228     kr = task_set_exception_ports(mach_task_self(),
  3229         EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3230         MACH_PORT_NULL,
  3231         EXCEPTION_STATE_IDENTITY,
  3232         MACHINE_THREAD_STATE);
  3234     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3235 #endif
  3237     if (libjsig_is_loaded) {
  3238       // Tell libjsig jvm finishes setting signal handlers
  3239       (*end_signal_setting)();
  3242     // We don't activate signal checker if libjsig is in place, we trust ourselves
  3243     // and if UserSignalHandler is installed all bets are off
  3244     if (CheckJNICalls) {
  3245       if (libjsig_is_loaded) {
  3246         if (PrintJNIResolving) {
  3247           tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
  3249         check_signals = false;
  3251       if (AllowUserSignalHandlers) {
  3252         if (PrintJNIResolving) {
  3253           tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
  3255         check_signals = false;
  3262 /////
  3263 // glibc on Bsd platform uses non-documented flag
  3264 // to indicate, that some special sort of signal
  3265 // trampoline is used.
  3266 // We will never set this flag, and we should
  3267 // ignore this flag in our diagnostic
  3268 #ifdef SIGNIFICANT_SIGNAL_MASK
  3269 #undef SIGNIFICANT_SIGNAL_MASK
  3270 #endif
  3271 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3273 static const char* get_signal_handler_name(address handler,
  3274                                            char* buf, int buflen) {
  3275   int offset;
  3276   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
  3277   if (found) {
  3278     // skip directory names
  3279     const char *p1, *p2;
  3280     p1 = buf;
  3281     size_t len = strlen(os::file_separator());
  3282     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
  3283     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
  3284   } else {
  3285     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
  3287   return buf;
  3290 static void print_signal_handler(outputStream* st, int sig,
  3291                                  char* buf, size_t buflen) {
  3292   struct sigaction sa;
  3294   sigaction(sig, NULL, &sa);
  3296   // See comment for SIGNIFICANT_SIGNAL_MASK define
  3297   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3299   st->print("%s: ", os::exception_name(sig, buf, buflen));
  3301   address handler = (sa.sa_flags & SA_SIGINFO)
  3302     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
  3303     : CAST_FROM_FN_PTR(address, sa.sa_handler);
  3305   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
  3306     st->print("SIG_DFL");
  3307   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
  3308     st->print("SIG_IGN");
  3309   } else {
  3310     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
  3313   st->print(", sa_mask[0]=");
  3314   os::Posix::print_signal_set_short(st, &sa.sa_mask);
  3316   address rh = VMError::get_resetted_sighandler(sig);
  3317   // May be, handler was resetted by VMError?
  3318   if(rh != NULL) {
  3319     handler = rh;
  3320     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
  3323   st->print(", sa_flags=");
  3324   os::Posix::print_sa_flags(st, sa.sa_flags);
  3326   // Check: is it our handler?
  3327   if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3328      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3329     // It is our signal handler
  3330     // check for flags, reset system-used one!
  3331     if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3332       st->print(
  3333                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3334                 os::Bsd::get_our_sigflags(sig));
  3337   st->cr();
  3341 #define DO_SIGNAL_CHECK(sig) \
  3342   if (!sigismember(&check_signal_done, sig)) \
  3343     os::Bsd::check_signal_handler(sig)
  3345 // This method is a periodic task to check for misbehaving JNI applications
  3346 // under CheckJNI, we can add any periodic checks here
  3348 void os::run_periodic_checks() {
  3350   if (check_signals == false) return;
  3352   // SEGV and BUS if overridden could potentially prevent
  3353   // generation of hs*.log in the event of a crash, debugging
  3354   // such a case can be very challenging, so we absolutely
  3355   // check the following for a good measure:
  3356   DO_SIGNAL_CHECK(SIGSEGV);
  3357   DO_SIGNAL_CHECK(SIGILL);
  3358   DO_SIGNAL_CHECK(SIGFPE);
  3359   DO_SIGNAL_CHECK(SIGBUS);
  3360   DO_SIGNAL_CHECK(SIGPIPE);
  3361   DO_SIGNAL_CHECK(SIGXFSZ);
  3364   // ReduceSignalUsage allows the user to override these handlers
  3365   // see comments at the very top and jvm_solaris.h
  3366   if (!ReduceSignalUsage) {
  3367     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
  3368     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
  3369     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
  3370     DO_SIGNAL_CHECK(BREAK_SIGNAL);
  3373   DO_SIGNAL_CHECK(SR_signum);
  3374   DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
  3377 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
  3379 static os_sigaction_t os_sigaction = NULL;
  3381 void os::Bsd::check_signal_handler(int sig) {
  3382   char buf[O_BUFLEN];
  3383   address jvmHandler = NULL;
  3386   struct sigaction act;
  3387   if (os_sigaction == NULL) {
  3388     // only trust the default sigaction, in case it has been interposed
  3389     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
  3390     if (os_sigaction == NULL) return;
  3393   os_sigaction(sig, (struct sigaction*)NULL, &act);
  3396   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3398   address thisHandler = (act.sa_flags & SA_SIGINFO)
  3399     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
  3400     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
  3403   switch(sig) {
  3404   case SIGSEGV:
  3405   case SIGBUS:
  3406   case SIGFPE:
  3407   case SIGPIPE:
  3408   case SIGILL:
  3409   case SIGXFSZ:
  3410     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
  3411     break;
  3413   case SHUTDOWN1_SIGNAL:
  3414   case SHUTDOWN2_SIGNAL:
  3415   case SHUTDOWN3_SIGNAL:
  3416   case BREAK_SIGNAL:
  3417     jvmHandler = (address)user_handler();
  3418     break;
  3420   case INTERRUPT_SIGNAL:
  3421     jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
  3422     break;
  3424   default:
  3425     if (sig == SR_signum) {
  3426       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
  3427     } else {
  3428       return;
  3430     break;
  3433   if (thisHandler != jvmHandler) {
  3434     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
  3435     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
  3436     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
  3437     // No need to check this sig any longer
  3438     sigaddset(&check_signal_done, sig);
  3439   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3440     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
  3441     tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
  3442     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
  3443     // No need to check this sig any longer
  3444     sigaddset(&check_signal_done, sig);
  3447   // Dump all the signal
  3448   if (sigismember(&check_signal_done, sig)) {
  3449     print_signal_handlers(tty, buf, O_BUFLEN);
  3453 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3455 extern bool signal_name(int signo, char* buf, size_t len);
  3457 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3458   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3459     // signal
  3460     if (!signal_name(exception_code, buf, size)) {
  3461       jio_snprintf(buf, size, "SIG%d", exception_code);
  3463     return buf;
  3464   } else {
  3465     return NULL;
  3469 // this is called _before_ the most of global arguments have been parsed
  3470 void os::init(void) {
  3471   char dummy;   /* used to get a guess on initial stack address */
  3472 //  first_hrtime = gethrtime();
  3474   // With BsdThreads the JavaMain thread pid (primordial thread)
  3475   // is different than the pid of the java launcher thread.
  3476   // So, on Bsd, the launcher thread pid is passed to the VM
  3477   // via the sun.java.launcher.pid property.
  3478   // Use this property instead of getpid() if it was correctly passed.
  3479   // See bug 6351349.
  3480   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
  3482   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
  3484   clock_tics_per_sec = CLK_TCK;
  3486   init_random(1234567);
  3488   ThreadCritical::initialize();
  3490   Bsd::set_page_size(getpagesize());
  3491   if (Bsd::page_size() == -1) {
  3492     fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
  3493                   strerror(errno)));
  3495   init_page_sizes((size_t) Bsd::page_size());
  3497   Bsd::initialize_system_info();
  3499   // main_thread points to the aboriginal thread
  3500   Bsd::_main_thread = pthread_self();
  3502   Bsd::clock_init();
  3503   initial_time_count = os::elapsed_counter();
  3505 #ifdef __APPLE__
  3506   // XXXDARWIN
  3507   // Work around the unaligned VM callbacks in hotspot's
  3508   // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
  3509   // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
  3510   // alignment when doing symbol lookup. To work around this, we force early
  3511   // binding of all symbols now, thus binding when alignment is known-good.
  3512   _dyld_bind_fully_image_containing_address((const void *) &os::init);
  3513 #endif
  3516 // To install functions for atexit system call
  3517 extern "C" {
  3518   static void perfMemory_exit_helper() {
  3519     perfMemory_exit();
  3523 // this is called _after_ the global arguments have been parsed
  3524 jint os::init_2(void)
  3526   // Allocate a single page and mark it as readable for safepoint polling
  3527   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3528   guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
  3530   os::set_polling_page( polling_page );
  3532 #ifndef PRODUCT
  3533   if(Verbose && PrintMiscellaneous)
  3534     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3535 #endif
  3537   if (!UseMembar) {
  3538     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3539     guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3540     os::set_memory_serialize_page( mem_serialize_page );
  3542 #ifndef PRODUCT
  3543     if(Verbose && PrintMiscellaneous)
  3544       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3545 #endif
  3548   os::large_page_init();
  3550   // initialize suspend/resume support - must do this before signal_sets_init()
  3551   if (SR_initialize() != 0) {
  3552     perror("SR_initialize failed");
  3553     return JNI_ERR;
  3556   Bsd::signal_sets_init();
  3557   Bsd::install_signal_handlers();
  3559   // Check minimum allowable stack size for thread creation and to initialize
  3560   // the java system classes, including StackOverflowError - depends on page
  3561   // size.  Add a page for compiler2 recursion in main thread.
  3562   // Add in 2*BytesPerWord times page size to account for VM stack during
  3563   // class initialization depending on 32 or 64 bit VM.
  3564   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3565             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3566                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3568   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3569   if (threadStackSizeInBytes != 0 &&
  3570       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3571         tty->print_cr("\nThe stack size specified is too small, "
  3572                       "Specify at least %dk",
  3573                       os::Bsd::min_stack_allowed/ K);
  3574         return JNI_ERR;
  3577   // Make the stack size a multiple of the page size so that
  3578   // the yellow/red zones can be guarded.
  3579   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3580         vm_page_size()));
  3582   if (MaxFDLimit) {
  3583     // set the number of file descriptors to max. print out error
  3584     // if getrlimit/setrlimit fails but continue regardless.
  3585     struct rlimit nbr_files;
  3586     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3587     if (status != 0) {
  3588       if (PrintMiscellaneous && (Verbose || WizardMode))
  3589         perror("os::init_2 getrlimit failed");
  3590     } else {
  3591       nbr_files.rlim_cur = nbr_files.rlim_max;
  3593 #ifdef __APPLE__
  3594       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3595       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
  3596       // be used instead
  3597       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3598 #endif
  3600       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3601       if (status != 0) {
  3602         if (PrintMiscellaneous && (Verbose || WizardMode))
  3603           perror("os::init_2 setrlimit failed");
  3608   // at-exit methods are called in the reverse order of their registration.
  3609   // atexit functions are called on return from main or as a result of a
  3610   // call to exit(3C). There can be only 32 of these functions registered
  3611   // and atexit() does not set errno.
  3613   if (PerfAllowAtExitRegistration) {
  3614     // only register atexit functions if PerfAllowAtExitRegistration is set.
  3615     // atexit functions can be delayed until process exit time, which
  3616     // can be problematic for embedded VM situations. Embedded VMs should
  3617     // call DestroyJavaVM() to assure that VM resources are released.
  3619     // note: perfMemory_exit_helper atexit function may be removed in
  3620     // the future if the appropriate cleanup code can be added to the
  3621     // VM_Exit VMOperation's doit method.
  3622     if (atexit(perfMemory_exit_helper) != 0) {
  3623       warning("os::init2 atexit(perfMemory_exit_helper) failed");
  3627   // initialize thread priority policy
  3628   prio_init();
  3630 #ifdef __APPLE__
  3631   // dynamically link to objective c gc registration
  3632   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
  3633   if (handleLibObjc != NULL) {
  3634     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
  3636 #endif
  3638   return JNI_OK;
  3641 // this is called at the end of vm_initialization
  3642 void os::init_3(void) { }
  3644 // Mark the polling page as unreadable
  3645 void os::make_polling_page_unreadable(void) {
  3646   if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
  3647     fatal("Could not disable polling page");
  3648 };
  3650 // Mark the polling page as readable
  3651 void os::make_polling_page_readable(void) {
  3652   if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3653     fatal("Could not enable polling page");
  3655 };
  3657 int os::active_processor_count() {
  3658   return _processor_count;
  3661 void os::set_native_thread_name(const char *name) {
  3662 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  3663   // This is only supported in Snow Leopard and beyond
  3664   if (name != NULL) {
  3665     // Add a "Java: " prefix to the name
  3666     char buf[MAXTHREADNAMESIZE];
  3667     snprintf(buf, sizeof(buf), "Java: %s", name);
  3668     pthread_setname_np(buf);
  3670 #endif
  3673 bool os::distribute_processes(uint length, uint* distribution) {
  3674   // Not yet implemented.
  3675   return false;
  3678 bool os::bind_to_processor(uint processor_id) {
  3679   // Not yet implemented.
  3680   return false;
  3683 void os::SuspendedThreadTask::internal_do_task() {
  3684   if (do_suspend(_thread->osthread())) {
  3685     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
  3686     do_task(context);
  3687     do_resume(_thread->osthread());
  3691 ///
  3692 class PcFetcher : public os::SuspendedThreadTask {
  3693 public:
  3694   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
  3695   ExtendedPC result();
  3696 protected:
  3697   void do_task(const os::SuspendedThreadTaskContext& context);
  3698 private:
  3699   ExtendedPC _epc;
  3700 };
  3702 ExtendedPC PcFetcher::result() {
  3703   guarantee(is_done(), "task is not done yet.");
  3704   return _epc;
  3707 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
  3708   Thread* thread = context.thread();
  3709   OSThread* osthread = thread->osthread();
  3710   if (osthread->ucontext() != NULL) {
  3711     _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());
  3712   } else {
  3713     // NULL context is unexpected, double-check this is the VMThread
  3714     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
  3718 // Suspends the target using the signal mechanism and then grabs the PC before
  3719 // resuming the target. Used by the flat-profiler only
  3720 ExtendedPC os::get_thread_pc(Thread* thread) {
  3721   // Make sure that it is called by the watcher for the VMThread
  3722   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
  3723   assert(thread->is_VM_thread(), "Can only be called for VMThread");
  3725   PcFetcher fetcher(thread);
  3726   fetcher.run();
  3727   return fetcher.result();
  3730 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3732   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3735 ////////////////////////////////////////////////////////////////////////////////
  3736 // debug support
  3738 bool os::find(address addr, outputStream* st) {
  3739   Dl_info dlinfo;
  3740   memset(&dlinfo, 0, sizeof(dlinfo));
  3741   if (dladdr(addr, &dlinfo) != 0) {
  3742     st->print(PTR_FORMAT ": ", addr);
  3743     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
  3744       st->print("%s+%#x", dlinfo.dli_sname,
  3745                  addr - (intptr_t)dlinfo.dli_saddr);
  3746     } else if (dlinfo.dli_fbase != NULL) {
  3747       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3748     } else {
  3749       st->print("<absolute address>");
  3751     if (dlinfo.dli_fname != NULL) {
  3752       st->print(" in %s", dlinfo.dli_fname);
  3754     if (dlinfo.dli_fbase != NULL) {
  3755       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
  3757     st->cr();
  3759     if (Verbose) {
  3760       // decode some bytes around the PC
  3761       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
  3762       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
  3763       address       lowest = (address) dlinfo.dli_sname;
  3764       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3765       if (begin < lowest)  begin = lowest;
  3766       Dl_info dlinfo2;
  3767       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3768           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3769         end = (address) dlinfo2.dli_saddr;
  3770       Disassembler::decode(begin, end, st);
  3772     return true;
  3774   return false;
  3777 ////////////////////////////////////////////////////////////////////////////////
  3778 // misc
  3780 // This does not do anything on Bsd. This is basically a hook for being
  3781 // able to use structured exception handling (thread-local exception filters)
  3782 // on, e.g., Win32.
  3783 void
  3784 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3785                          JavaCallArguments* args, Thread* thread) {
  3786   f(value, method, args, thread);
  3789 void os::print_statistics() {
  3792 int os::message_box(const char* title, const char* message) {
  3793   int i;
  3794   fdStream err(defaultStream::error_fd());
  3795   for (i = 0; i < 78; i++) err.print_raw("=");
  3796   err.cr();
  3797   err.print_raw_cr(title);
  3798   for (i = 0; i < 78; i++) err.print_raw("-");
  3799   err.cr();
  3800   err.print_raw_cr(message);
  3801   for (i = 0; i < 78; i++) err.print_raw("=");
  3802   err.cr();
  3804   char buf[16];
  3805   // Prevent process from exiting upon "read error" without consuming all CPU
  3806   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
  3808   return buf[0] == 'y' || buf[0] == 'Y';
  3811 int os::stat(const char *path, struct stat *sbuf) {
  3812   char pathbuf[MAX_PATH];
  3813   if (strlen(path) > MAX_PATH - 1) {
  3814     errno = ENAMETOOLONG;
  3815     return -1;
  3817   os::native_path(strcpy(pathbuf, path));
  3818   return ::stat(pathbuf, sbuf);
  3821 bool os::check_heap(bool force) {
  3822   return true;
  3825 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
  3826   return ::vsnprintf(buf, count, format, args);
  3829 // Is a (classpath) directory empty?
  3830 bool os::dir_is_empty(const char* path) {
  3831   DIR *dir = NULL;
  3832   struct dirent *ptr;
  3834   dir = opendir(path);
  3835   if (dir == NULL) return true;
  3837   /* Scan the directory */
  3838   bool result = true;
  3839   char buf[sizeof(struct dirent) + MAX_PATH];
  3840   while (result && (ptr = ::readdir(dir)) != NULL) {
  3841     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3842       result = false;
  3845   closedir(dir);
  3846   return result;
  3849 // This code originates from JDK's sysOpen and open64_w
  3850 // from src/solaris/hpi/src/system_md.c
  3852 #ifndef O_DELETE
  3853 #define O_DELETE 0x10000
  3854 #endif
  3856 // Open a file. Unlink the file immediately after open returns
  3857 // if the specified oflag has the O_DELETE flag set.
  3858 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3860 int os::open(const char *path, int oflag, int mode) {
  3862   if (strlen(path) > MAX_PATH - 1) {
  3863     errno = ENAMETOOLONG;
  3864     return -1;
  3866   int fd;
  3867   int o_delete = (oflag & O_DELETE);
  3868   oflag = oflag & ~O_DELETE;
  3870   fd = ::open(path, oflag, mode);
  3871   if (fd == -1) return -1;
  3873   //If the open succeeded, the file might still be a directory
  3875     struct stat buf;
  3876     int ret = ::fstat(fd, &buf);
  3877     int st_mode = buf.st_mode;
  3879     if (ret != -1) {
  3880       if ((st_mode & S_IFMT) == S_IFDIR) {
  3881         errno = EISDIR;
  3882         ::close(fd);
  3883         return -1;
  3885     } else {
  3886       ::close(fd);
  3887       return -1;
  3891     /*
  3892      * All file descriptors that are opened in the JVM and not
  3893      * specifically destined for a subprocess should have the
  3894      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3895      * party native code might fork and exec without closing all
  3896      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3897      * UNIXProcess.c), and this in turn might:
  3899      * - cause end-of-file to fail to be detected on some file
  3900      *   descriptors, resulting in mysterious hangs, or
  3902      * - might cause an fopen in the subprocess to fail on a system
  3903      *   suffering from bug 1085341.
  3905      * (Yes, the default setting of the close-on-exec flag is a Unix
  3906      * design flaw)
  3908      * See:
  3909      * 1085341: 32-bit stdio routines should support file descriptors >255
  3910      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3911      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3912      */
  3913 #ifdef FD_CLOEXEC
  3915         int flags = ::fcntl(fd, F_GETFD);
  3916         if (flags != -1)
  3917             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3919 #endif
  3921   if (o_delete != 0) {
  3922     ::unlink(path);
  3924   return fd;
  3928 // create binary file, rewriting existing file if required
  3929 int os::create_binary_file(const char* path, bool rewrite_existing) {
  3930   int oflags = O_WRONLY | O_CREAT;
  3931   if (!rewrite_existing) {
  3932     oflags |= O_EXCL;
  3934   return ::open(path, oflags, S_IREAD | S_IWRITE);
  3937 // return current position of file pointer
  3938 jlong os::current_file_offset(int fd) {
  3939   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
  3942 // move file pointer to the specified offset
  3943 jlong os::seek_to_file_offset(int fd, jlong offset) {
  3944   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
  3947 // This code originates from JDK's sysAvailable
  3948 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
  3950 int os::available(int fd, jlong *bytes) {
  3951   jlong cur, end;
  3952   int mode;
  3953   struct stat buf;
  3955   if (::fstat(fd, &buf) >= 0) {
  3956     mode = buf.st_mode;
  3957     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3958       /*
  3959       * XXX: is the following call interruptible? If so, this might
  3960       * need to go through the INTERRUPT_IO() wrapper as for other
  3961       * blocking, interruptible calls in this file.
  3962       */
  3963       int n;
  3964       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3965         *bytes = n;
  3966         return 1;
  3970   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
  3971     return 0;
  3972   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
  3973     return 0;
  3974   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
  3975     return 0;
  3977   *bytes = end - cur;
  3978   return 1;
  3981 int os::socket_available(int fd, jint *pbytes) {
  3982    if (fd < 0)
  3983      return OS_OK;
  3985    int ret;
  3987    RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3989    //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  3990    // is expected to return 0 on failure and 1 on success to the jdk.
  3992    return (ret == OS_ERR) ? 0 : 1;
  3995 // Map a block of memory.
  3996 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  3997                      char *addr, size_t bytes, bool read_only,
  3998                      bool allow_exec) {
  3999   int prot;
  4000   int flags;
  4002   if (read_only) {
  4003     prot = PROT_READ;
  4004     flags = MAP_SHARED;
  4005   } else {
  4006     prot = PROT_READ | PROT_WRITE;
  4007     flags = MAP_PRIVATE;
  4010   if (allow_exec) {
  4011     prot |= PROT_EXEC;
  4014   if (addr != NULL) {
  4015     flags |= MAP_FIXED;
  4018   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
  4019                                      fd, file_offset);
  4020   if (mapped_address == MAP_FAILED) {
  4021     return NULL;
  4023   return mapped_address;
  4027 // Remap a block of memory.
  4028 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  4029                        char *addr, size_t bytes, bool read_only,
  4030                        bool allow_exec) {
  4031   // same as map_memory() on this OS
  4032   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  4033                         allow_exec);
  4037 // Unmap a block of memory.
  4038 bool os::pd_unmap_memory(char* addr, size_t bytes) {
  4039   return munmap(addr, bytes) == 0;
  4042 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  4043 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  4044 // of a thread.
  4045 //
  4046 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
  4047 // the fast estimate available on the platform.
  4049 jlong os::current_thread_cpu_time() {
  4050 #ifdef __APPLE__
  4051   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
  4052 #else
  4053   Unimplemented();
  4054   return 0;
  4055 #endif
  4058 jlong os::thread_cpu_time(Thread* thread) {
  4059 #ifdef __APPLE__
  4060   return os::thread_cpu_time(thread, true /* user + sys */);
  4061 #else
  4062   Unimplemented();
  4063   return 0;
  4064 #endif
  4067 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  4068 #ifdef __APPLE__
  4069   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  4070 #else
  4071   Unimplemented();
  4072   return 0;
  4073 #endif
  4076 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
  4077 #ifdef __APPLE__
  4078   struct thread_basic_info tinfo;
  4079   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
  4080   kern_return_t kr;
  4081   thread_t mach_thread;
  4083   mach_thread = thread->osthread()->thread_id();
  4084   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4085   if (kr != KERN_SUCCESS)
  4086     return -1;
  4088   if (user_sys_cpu_time) {
  4089     jlong nanos;
  4090     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4091     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4092     return nanos;
  4093   } else {
  4094     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
  4096 #else
  4097   Unimplemented();
  4098   return 0;
  4099 #endif
  4103 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  4104   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  4105   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  4106   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  4107   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  4110 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  4111   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  4112   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  4113   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  4114   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  4117 bool os::is_thread_cpu_time_supported() {
  4118 #ifdef __APPLE__
  4119   return true;
  4120 #else
  4121   return false;
  4122 #endif
  4125 // System loadavg support.  Returns -1 if load average cannot be obtained.
  4126 // Bsd doesn't yet have a (official) notion of processor sets,
  4127 // so just return the system wide load average.
  4128 int os::loadavg(double loadavg[], int nelem) {
  4129   return ::getloadavg(loadavg, nelem);
  4132 void os::pause() {
  4133   char filename[MAX_PATH];
  4134   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  4135     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  4136   } else {
  4137     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  4140   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4141   if (fd != -1) {
  4142     struct stat buf;
  4143     ::close(fd);
  4144     while (::stat(filename, &buf) == 0) {
  4145       (void)::poll(NULL, 0, 100);
  4147   } else {
  4148     jio_fprintf(stderr,
  4149       "Could not open pause file '%s', continuing immediately.\n", filename);
  4154 // Refer to the comments in os_solaris.cpp park-unpark.
  4155 //
  4156 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
  4157 // hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
  4158 // For specifics regarding the bug see GLIBC BUGID 261237 :
  4159 //    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
  4160 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
  4161 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
  4162 // is used.  (The simple C test-case provided in the GLIBC bug report manifests the
  4163 // hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
  4164 // and monitorenter when we're using 1-0 locking.  All those operations may result in
  4165 // calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
  4166 // of libpthread avoids the problem, but isn't practical.
  4167 //
  4168 // Possible remedies:
  4169 //
  4170 // 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
  4171 //      This is palliative and probabilistic, however.  If the thread is preempted
  4172 //      between the call to compute_abstime() and pthread_cond_timedwait(), more
  4173 //      than the minimum period may have passed, and the abstime may be stale (in the
  4174 //      past) resultin in a hang.   Using this technique reduces the odds of a hang
  4175 //      but the JVM is still vulnerable, particularly on heavily loaded systems.
  4176 //
  4177 // 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
  4178 //      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
  4179 //      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
  4180 //      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
  4181 //      thread.
  4182 //
  4183 // 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
  4184 //      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
  4185 //      a timeout request to the chron thread and then blocking via pthread_cond_wait().
  4186 //      This also works well.  In fact it avoids kernel-level scalability impediments
  4187 //      on certain platforms that don't handle lots of active pthread_cond_timedwait()
  4188 //      timers in a graceful fashion.
  4189 //
  4190 // 4.   When the abstime value is in the past it appears that control returns
  4191 //      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
  4192 //      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
  4193 //      can avoid the problem by reinitializing the condvar -- by cond_destroy()
  4194 //      followed by cond_init() -- after all calls to pthread_cond_timedwait().
  4195 //      It may be possible to avoid reinitialization by checking the return
  4196 //      value from pthread_cond_timedwait().  In addition to reinitializing the
  4197 //      condvar we must establish the invariant that cond_signal() is only called
  4198 //      within critical sections protected by the adjunct mutex.  This prevents
  4199 //      cond_signal() from "seeing" a condvar that's in the midst of being
  4200 //      reinitialized or that is corrupt.  Sadly, this invariant obviates the
  4201 //      desirable signal-after-unlock optimization that avoids futile context switching.
  4202 //
  4203 //      I'm also concerned that some versions of NTPL might allocate an auxilliary
  4204 //      structure when a condvar is used or initialized.  cond_destroy()  would
  4205 //      release the helper structure.  Our reinitialize-after-timedwait fix
  4206 //      put excessive stress on malloc/free and locks protecting the c-heap.
  4207 //
  4208 // We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
  4209 // It may be possible to refine (4) by checking the kernel and NTPL verisons
  4210 // and only enabling the work-around for vulnerable environments.
  4212 // utility to compute the abstime argument to timedwait:
  4213 // millis is the relative timeout time
  4214 // abstime will be the absolute timeout time
  4215 // TODO: replace compute_abstime() with unpackTime()
  4217 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4218   if (millis < 0)  millis = 0;
  4219   struct timeval now;
  4220   int status = gettimeofday(&now, NULL);
  4221   assert(status == 0, "gettimeofday");
  4222   jlong seconds = millis / 1000;
  4223   millis %= 1000;
  4224   if (seconds > 50000000) { // see man cond_timedwait(3T)
  4225     seconds = 50000000;
  4227   abstime->tv_sec = now.tv_sec  + seconds;
  4228   long       usec = now.tv_usec + millis * 1000;
  4229   if (usec >= 1000000) {
  4230     abstime->tv_sec += 1;
  4231     usec -= 1000000;
  4233   abstime->tv_nsec = usec * 1000;
  4234   return abstime;
  4238 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
  4239 // Conceptually TryPark() should be equivalent to park(0).
  4241 int os::PlatformEvent::TryPark() {
  4242   for (;;) {
  4243     const int v = _Event ;
  4244     guarantee ((v == 0) || (v == 1), "invariant") ;
  4245     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
  4249 void os::PlatformEvent::park() {       // AKA "down()"
  4250   // Invariant: Only the thread associated with the Event/PlatformEvent
  4251   // may call park().
  4252   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4253   int v ;
  4254   for (;;) {
  4255       v = _Event ;
  4256       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4258   guarantee (v >= 0, "invariant") ;
  4259   if (v == 0) {
  4260      // Do this the hard way by blocking ...
  4261      int status = pthread_mutex_lock(_mutex);
  4262      assert_status(status == 0, status, "mutex_lock");
  4263      guarantee (_nParked == 0, "invariant") ;
  4264      ++ _nParked ;
  4265      while (_Event < 0) {
  4266         status = pthread_cond_wait(_cond, _mutex);
  4267         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4268         // Treat this the same as if the wait was interrupted
  4269         if (status == ETIMEDOUT) { status = EINTR; }
  4270         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4272      -- _nParked ;
  4274     _Event = 0 ;
  4275      status = pthread_mutex_unlock(_mutex);
  4276      assert_status(status == 0, status, "mutex_unlock");
  4277     // Paranoia to ensure our locked and lock-free paths interact
  4278     // correctly with each other.
  4279     OrderAccess::fence();
  4281   guarantee (_Event >= 0, "invariant") ;
  4284 int os::PlatformEvent::park(jlong millis) {
  4285   guarantee (_nParked == 0, "invariant") ;
  4287   int v ;
  4288   for (;;) {
  4289       v = _Event ;
  4290       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4292   guarantee (v >= 0, "invariant") ;
  4293   if (v != 0) return OS_OK ;
  4295   // We do this the hard way, by blocking the thread.
  4296   // Consider enforcing a minimum timeout value.
  4297   struct timespec abst;
  4298   compute_abstime(&abst, millis);
  4300   int ret = OS_TIMEOUT;
  4301   int status = pthread_mutex_lock(_mutex);
  4302   assert_status(status == 0, status, "mutex_lock");
  4303   guarantee (_nParked == 0, "invariant") ;
  4304   ++_nParked ;
  4306   // Object.wait(timo) will return because of
  4307   // (a) notification
  4308   // (b) timeout
  4309   // (c) thread.interrupt
  4310   //
  4311   // Thread.interrupt and object.notify{All} both call Event::set.
  4312   // That is, we treat thread.interrupt as a special case of notification.
  4313   // The underlying Solaris implementation, cond_timedwait, admits
  4314   // spurious/premature wakeups, but the JLS/JVM spec prevents the
  4315   // JVM from making those visible to Java code.  As such, we must
  4316   // filter out spurious wakeups.  We assume all ETIME returns are valid.
  4317   //
  4318   // TODO: properly differentiate simultaneous notify+interrupt.
  4319   // In that case, we should propagate the notify to another waiter.
  4321   while (_Event < 0) {
  4322     status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
  4323     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4324       pthread_cond_destroy (_cond);
  4325       pthread_cond_init (_cond, NULL) ;
  4327     assert_status(status == 0 || status == EINTR ||
  4328                   status == ETIMEDOUT,
  4329                   status, "cond_timedwait");
  4330     if (!FilterSpuriousWakeups) break ;                 // previous semantics
  4331     if (status == ETIMEDOUT) break ;
  4332     // We consume and ignore EINTR and spurious wakeups.
  4334   --_nParked ;
  4335   if (_Event >= 0) {
  4336      ret = OS_OK;
  4338   _Event = 0 ;
  4339   status = pthread_mutex_unlock(_mutex);
  4340   assert_status(status == 0, status, "mutex_unlock");
  4341   assert (_nParked == 0, "invariant") ;
  4342   // Paranoia to ensure our locked and lock-free paths interact
  4343   // correctly with each other.
  4344   OrderAccess::fence();
  4345   return ret;
  4348 void os::PlatformEvent::unpark() {
  4349   // Transitions for _Event:
  4350   //    0 :=> 1
  4351   //    1 :=> 1
  4352   //   -1 :=> either 0 or 1; must signal target thread
  4353   //          That is, we can safely transition _Event from -1 to either
  4354   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
  4355   //          unpark() calls.
  4356   // See also: "Semaphores in Plan 9" by Mullender & Cox
  4357   //
  4358   // Note: Forcing a transition from "-1" to "1" on an unpark() means
  4359   // that it will take two back-to-back park() calls for the owning
  4360   // thread to block. This has the benefit of forcing a spurious return
  4361   // from the first park() call after an unpark() call which will help
  4362   // shake out uses of park() and unpark() without condition variables.
  4364   if (Atomic::xchg(1, &_Event) >= 0) return;
  4366   // Wait for the thread associated with the event to vacate
  4367   int status = pthread_mutex_lock(_mutex);
  4368   assert_status(status == 0, status, "mutex_lock");
  4369   int AnyWaiters = _nParked;
  4370   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
  4371   if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
  4372     AnyWaiters = 0;
  4373     pthread_cond_signal(_cond);
  4375   status = pthread_mutex_unlock(_mutex);
  4376   assert_status(status == 0, status, "mutex_unlock");
  4377   if (AnyWaiters != 0) {
  4378     status = pthread_cond_signal(_cond);
  4379     assert_status(status == 0, status, "cond_signal");
  4382   // Note that we signal() _after dropping the lock for "immortal" Events.
  4383   // This is safe and avoids a common class of  futile wakeups.  In rare
  4384   // circumstances this can cause a thread to return prematurely from
  4385   // cond_{timed}wait() but the spurious wakeup is benign and the victim will
  4386   // simply re-test the condition and re-park itself.
  4390 // JSR166
  4391 // -------------------------------------------------------
  4393 /*
  4394  * The solaris and bsd implementations of park/unpark are fairly
  4395  * conservative for now, but can be improved. They currently use a
  4396  * mutex/condvar pair, plus a a count.
  4397  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4398  * sets count to 1 and signals condvar.  Only one thread ever waits
  4399  * on the condvar. Contention seen when trying to park implies that someone
  4400  * is unparking you, so don't wait. And spurious returns are fine, so there
  4401  * is no need to track notifications.
  4402  */
  4404 #define MAX_SECS 100000000
  4405 /*
  4406  * This code is common to bsd and solaris and will be moved to a
  4407  * common place in dolphin.
  4409  * The passed in time value is either a relative time in nanoseconds
  4410  * or an absolute time in milliseconds. Either way it has to be unpacked
  4411  * into suitable seconds and nanoseconds components and stored in the
  4412  * given timespec structure.
  4413  * Given time is a 64-bit value and the time_t used in the timespec is only
  4414  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4415  * overflow if times way in the future are given. Further on Solaris versions
  4416  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4417  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4418  * As it will be 28 years before "now + 100000000" will overflow we can
  4419  * ignore overflow and just impose a hard-limit on seconds using the value
  4420  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4421  * years from "now".
  4422  */
  4424 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4425   assert (time > 0, "convertTime");
  4427   struct timeval now;
  4428   int status = gettimeofday(&now, NULL);
  4429   assert(status == 0, "gettimeofday");
  4431   time_t max_secs = now.tv_sec + MAX_SECS;
  4433   if (isAbsolute) {
  4434     jlong secs = time / 1000;
  4435     if (secs > max_secs) {
  4436       absTime->tv_sec = max_secs;
  4438     else {
  4439       absTime->tv_sec = secs;
  4441     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4443   else {
  4444     jlong secs = time / NANOSECS_PER_SEC;
  4445     if (secs >= MAX_SECS) {
  4446       absTime->tv_sec = max_secs;
  4447       absTime->tv_nsec = 0;
  4449     else {
  4450       absTime->tv_sec = now.tv_sec + secs;
  4451       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4452       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4453         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4454         ++absTime->tv_sec; // note: this must be <= max_secs
  4458   assert(absTime->tv_sec >= 0, "tv_sec < 0");
  4459   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
  4460   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
  4461   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
  4464 void Parker::park(bool isAbsolute, jlong time) {
  4465   // Ideally we'd do something useful while spinning, such
  4466   // as calling unpackTime().
  4468   // Optional fast-path check:
  4469   // Return immediately if a permit is available.
  4470   // We depend on Atomic::xchg() having full barrier semantics
  4471   // since we are doing a lock-free update to _counter.
  4472   if (Atomic::xchg(0, &_counter) > 0) return;
  4474   Thread* thread = Thread::current();
  4475   assert(thread->is_Java_thread(), "Must be JavaThread");
  4476   JavaThread *jt = (JavaThread *)thread;
  4478   // Optional optimization -- avoid state transitions if there's an interrupt pending.
  4479   // Check interrupt before trying to wait
  4480   if (Thread::is_interrupted(thread, false)) {
  4481     return;
  4484   // Next, demultiplex/decode time arguments
  4485   struct timespec absTime;
  4486   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
  4487     return;
  4489   if (time > 0) {
  4490     unpackTime(&absTime, isAbsolute, time);
  4494   // Enter safepoint region
  4495   // Beware of deadlocks such as 6317397.
  4496   // The per-thread Parker:: mutex is a classic leaf-lock.
  4497   // In particular a thread must never block on the Threads_lock while
  4498   // holding the Parker:: mutex.  If safepoints are pending both the
  4499   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
  4500   ThreadBlockInVM tbivm(jt);
  4502   // Don't wait if cannot get lock since interference arises from
  4503   // unblocking.  Also. check interrupt before trying wait
  4504   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
  4505     return;
  4508   int status ;
  4509   if (_counter > 0)  { // no wait needed
  4510     _counter = 0;
  4511     status = pthread_mutex_unlock(_mutex);
  4512     assert (status == 0, "invariant") ;
  4513     // Paranoia to ensure our locked and lock-free paths interact
  4514     // correctly with each other and Java-level accesses.
  4515     OrderAccess::fence();
  4516     return;
  4519 #ifdef ASSERT
  4520   // Don't catch signals while blocked; let the running threads have the signals.
  4521   // (This allows a debugger to break into the running thread.)
  4522   sigset_t oldsigs;
  4523   sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
  4524   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
  4525 #endif
  4527   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  4528   jt->set_suspend_equivalent();
  4529   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  4531   if (time == 0) {
  4532     status = pthread_cond_wait (_cond, _mutex) ;
  4533   } else {
  4534     status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
  4535     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4536       pthread_cond_destroy (_cond) ;
  4537       pthread_cond_init    (_cond, NULL);
  4540   assert_status(status == 0 || status == EINTR ||
  4541                 status == ETIMEDOUT,
  4542                 status, "cond_timedwait");
  4544 #ifdef ASSERT
  4545   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
  4546 #endif
  4548   _counter = 0 ;
  4549   status = pthread_mutex_unlock(_mutex) ;
  4550   assert_status(status == 0, status, "invariant") ;
  4551   // Paranoia to ensure our locked and lock-free paths interact
  4552   // correctly with each other and Java-level accesses.
  4553   OrderAccess::fence();
  4555   // If externally suspended while waiting, re-suspend
  4556   if (jt->handle_special_suspend_equivalent_condition()) {
  4557     jt->java_suspend_self();
  4561 void Parker::unpark() {
  4562   int s, status ;
  4563   status = pthread_mutex_lock(_mutex);
  4564   assert (status == 0, "invariant") ;
  4565   s = _counter;
  4566   _counter = 1;
  4567   if (s < 1) {
  4568      if (WorkAroundNPTLTimedWaitHang) {
  4569         status = pthread_cond_signal (_cond) ;
  4570         assert (status == 0, "invariant") ;
  4571         status = pthread_mutex_unlock(_mutex);
  4572         assert (status == 0, "invariant") ;
  4573      } else {
  4574         status = pthread_mutex_unlock(_mutex);
  4575         assert (status == 0, "invariant") ;
  4576         status = pthread_cond_signal (_cond) ;
  4577         assert (status == 0, "invariant") ;
  4579   } else {
  4580     pthread_mutex_unlock(_mutex);
  4581     assert (status == 0, "invariant") ;
  4586 /* Darwin has no "environ" in a dynamic library. */
  4587 #ifdef __APPLE__
  4588 #include <crt_externs.h>
  4589 #define environ (*_NSGetEnviron())
  4590 #else
  4591 extern char** environ;
  4592 #endif
  4594 // Run the specified command in a separate process. Return its exit value,
  4595 // or -1 on failure (e.g. can't fork a new process).
  4596 // Unlike system(), this function can be called from signal handler. It
  4597 // doesn't block SIGINT et al.
  4598 int os::fork_and_exec(char* cmd) {
  4599   const char * argv[4] = {"sh", "-c", cmd, NULL};
  4601   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
  4602   // pthread_atfork handlers and reset pthread library. All we need is a
  4603   // separate process to execve. Make a direct syscall to fork process.
  4604   // On IA64 there's no fork syscall, we have to use fork() and hope for
  4605   // the best...
  4606   pid_t pid = fork();
  4608   if (pid < 0) {
  4609     // fork failed
  4610     return -1;
  4612   } else if (pid == 0) {
  4613     // child process
  4615     // execve() in BsdThreads will call pthread_kill_other_threads_np()
  4616     // first to kill every thread on the thread list. Because this list is
  4617     // not reset by fork() (see notes above), execve() will instead kill
  4618     // every thread in the parent process. We know this is the only thread
  4619     // in the new process, so make a system call directly.
  4620     // IA64 should use normal execve() from glibc to match the glibc fork()
  4621     // above.
  4622     execve("/bin/sh", (char* const*)argv, environ);
  4624     // execve failed
  4625     _exit(-1);
  4627   } else  {
  4628     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
  4629     // care about the actual exit code, for now.
  4631     int status;
  4633     // Wait for the child process to exit.  This returns immediately if
  4634     // the child has already exited. */
  4635     while (waitpid(pid, &status, 0) < 0) {
  4636         switch (errno) {
  4637         case ECHILD: return 0;
  4638         case EINTR: break;
  4639         default: return -1;
  4643     if (WIFEXITED(status)) {
  4644        // The child exited normally; get its exit code.
  4645        return WEXITSTATUS(status);
  4646     } else if (WIFSIGNALED(status)) {
  4647        // The child exited because of a signal
  4648        // The best value to return is 0x80 + signal number,
  4649        // because that is what all Unix shells do, and because
  4650        // it allows callers to distinguish between process exit and
  4651        // process death by signal.
  4652        return 0x80 + WTERMSIG(status);
  4653     } else {
  4654        // Unknown exit code; pass it through
  4655        return status;
  4660 // is_headless_jre()
  4661 //
  4662 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
  4663 // in order to report if we are running in a headless jre
  4664 //
  4665 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4666 // as libawt.so, and renamed libawt_xawt.so
  4667 //
  4668 bool os::is_headless_jre() {
  4669     struct stat statbuf;
  4670     char buf[MAXPATHLEN];
  4671     char libmawtpath[MAXPATHLEN];
  4672     const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
  4673     const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
  4674     char *p;
  4676     // Get path to libjvm.so
  4677     os::jvm_path(buf, sizeof(buf));
  4679     // Get rid of libjvm.so
  4680     p = strrchr(buf, '/');
  4681     if (p == NULL) return false;
  4682     else *p = '\0';
  4684     // Get rid of client or server
  4685     p = strrchr(buf, '/');
  4686     if (p == NULL) return false;
  4687     else *p = '\0';
  4689     // check xawt/libmawt.so
  4690     strcpy(libmawtpath, buf);
  4691     strcat(libmawtpath, xawtstr);
  4692     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4694     // check libawt_xawt.so
  4695     strcpy(libmawtpath, buf);
  4696     strcat(libmawtpath, new_xawtstr);
  4697     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4699     return true;
  4702 // Get the default path to the core file
  4703 // Returns the length of the string
  4704 int os::get_core_path(char* buffer, size_t bufferSize) {
  4705   int n = jio_snprintf(buffer, bufferSize, "/cores");
  4707   // Truncate if theoretical string was longer than bufferSize
  4708   n = MIN2(n, (int)bufferSize);
  4710   return n;
  4713 #ifndef PRODUCT
  4714 void TestReserveMemorySpecial_test() {
  4715   // No tests available for this platform
  4717 #endif

mercurial