src/os/bsd/vm/os_bsd.cpp

Fri, 26 Jul 2013 00:59:18 +0200

author
goetz
date
Fri, 26 Jul 2013 00:59:18 +0200
changeset 6460
f42f2e2a1518
parent 6455
438e13354adf
child 6462
e2722a66aba7
permissions
-rw-r--r--

8020775: PPC64 (part 12): posix signal printing
Summary: Implement methods printing posix signal information and call them in unix os files.
Reviewed-by: kvn, dholmes, twisti
Contributed-by: thomas.stuefe@sap.com

     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() {
   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_self(), THREAD_IDENTIFIER_INFO,
   651               (thread_info_t) &m_ident_info, &count);
   652   return m_ident_info.thread_id;
   653 }
   654 #endif
   656 // Thread start routine for all newly created threads
   657 static void *java_start(Thread *thread) {
   658   // Try to randomize the cache line index of hot stack frames.
   659   // This helps when threads of the same stack traces evict each other's
   660   // cache lines. The threads can be either from the same JVM instance, or
   661   // from different JVM instances. The benefit is especially true for
   662   // processors with hyperthreading technology.
   663   static int counter = 0;
   664   int pid = os::current_process_id();
   665   alloca(((pid ^ counter++) & 7) * 128);
   667   ThreadLocalStorage::set_thread(thread);
   669   OSThread* osthread = thread->osthread();
   670   Monitor* sync = osthread->startThread_lock();
   672   // non floating stack BsdThreads needs extra check, see above
   673   if (!_thread_safety_check(thread)) {
   674     // notify parent thread
   675     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   676     osthread->set_state(ZOMBIE);
   677     sync->notify_all();
   678     return NULL;
   679   }
   681 #ifdef __APPLE__
   682   // thread_id is mach thread on macos
   683   osthread->set_thread_id(::mach_thread_self());
   684   osthread->set_unique_thread_id(locate_unique_thread_id());
   685 #else
   686   // thread_id is pthread_id on BSD
   687   osthread->set_thread_id(::pthread_self());
   688 #endif
   689   // initialize signal mask for this thread
   690   os::Bsd::hotspot_sigmask(thread);
   692   // initialize floating point control register
   693   os::Bsd::init_thread_fpu_state();
   695 #ifdef __APPLE__
   696   // register thread with objc gc
   697   if (objc_registerThreadWithCollectorFunction != NULL) {
   698     objc_registerThreadWithCollectorFunction();
   699   }
   700 #endif
   702   // handshaking with parent thread
   703   {
   704     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   706     // notify parent thread
   707     osthread->set_state(INITIALIZED);
   708     sync->notify_all();
   710     // wait until os::start_thread()
   711     while (osthread->get_state() == INITIALIZED) {
   712       sync->wait(Mutex::_no_safepoint_check_flag);
   713     }
   714   }
   716   // call one more level start routine
   717   thread->run();
   719   return 0;
   720 }
   722 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
   723   assert(thread->osthread() == NULL, "caller responsible");
   725   // Allocate the OSThread object
   726   OSThread* osthread = new OSThread(NULL, NULL);
   727   if (osthread == NULL) {
   728     return false;
   729   }
   731   // set the correct thread state
   732   osthread->set_thread_type(thr_type);
   734   // Initial state is ALLOCATED but not INITIALIZED
   735   osthread->set_state(ALLOCATED);
   737   thread->set_osthread(osthread);
   739   // init thread attributes
   740   pthread_attr_t attr;
   741   pthread_attr_init(&attr);
   742   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   744   // stack size
   745   if (os::Bsd::supports_variable_stack_size()) {
   746     // calculate stack size if it's not specified by caller
   747     if (stack_size == 0) {
   748       stack_size = os::Bsd::default_stack_size(thr_type);
   750       switch (thr_type) {
   751       case os::java_thread:
   752         // Java threads use ThreadStackSize which default value can be
   753         // changed with the flag -Xss
   754         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
   755         stack_size = JavaThread::stack_size_at_create();
   756         break;
   757       case os::compiler_thread:
   758         if (CompilerThreadStackSize > 0) {
   759           stack_size = (size_t)(CompilerThreadStackSize * K);
   760           break;
   761         } // else fall through:
   762           // use VMThreadStackSize if CompilerThreadStackSize is not defined
   763       case os::vm_thread:
   764       case os::pgc_thread:
   765       case os::cgc_thread:
   766       case os::watcher_thread:
   767         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
   768         break;
   769       }
   770     }
   772     stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
   773     pthread_attr_setstacksize(&attr, stack_size);
   774   } else {
   775     // let pthread_create() pick the default value.
   776   }
   778   ThreadState state;
   780   {
   781     pthread_t tid;
   782     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
   784     pthread_attr_destroy(&attr);
   786     if (ret != 0) {
   787       if (PrintMiscellaneous && (Verbose || WizardMode)) {
   788         perror("pthread_create()");
   789       }
   790       // Need to clean up stuff we've allocated so far
   791       thread->set_osthread(NULL);
   792       delete osthread;
   793       return false;
   794     }
   796     // Store pthread info into the OSThread
   797     osthread->set_pthread_id(tid);
   799     // Wait until child thread is either initialized or aborted
   800     {
   801       Monitor* sync_with_child = osthread->startThread_lock();
   802       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   803       while ((state = osthread->get_state()) == ALLOCATED) {
   804         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
   805       }
   806     }
   808   }
   810   // Aborted due to thread limit being reached
   811   if (state == ZOMBIE) {
   812       thread->set_osthread(NULL);
   813       delete osthread;
   814       return false;
   815   }
   817   // The thread is returned suspended (in state INITIALIZED),
   818   // and is started higher up in the call chain
   819   assert(state == INITIALIZED, "race condition");
   820   return true;
   821 }
   823 /////////////////////////////////////////////////////////////////////////////
   824 // attach existing thread
   826 // bootstrap the main thread
   827 bool os::create_main_thread(JavaThread* thread) {
   828   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
   829   return create_attached_thread(thread);
   830 }
   832 bool os::create_attached_thread(JavaThread* thread) {
   833 #ifdef ASSERT
   834     thread->verify_not_published();
   835 #endif
   837   // Allocate the OSThread object
   838   OSThread* osthread = new OSThread(NULL, NULL);
   840   if (osthread == NULL) {
   841     return false;
   842   }
   844   // Store pthread info into the OSThread
   845 #ifdef __APPLE__
   846   osthread->set_thread_id(::mach_thread_self());
   847   osthread->set_unique_thread_id(locate_unique_thread_id());
   848 #else
   849   osthread->set_thread_id(::pthread_self());
   850 #endif
   851   osthread->set_pthread_id(::pthread_self());
   853   // initialize floating point control register
   854   os::Bsd::init_thread_fpu_state();
   856   // Initial thread state is RUNNABLE
   857   osthread->set_state(RUNNABLE);
   859   thread->set_osthread(osthread);
   861   // initialize signal mask for this thread
   862   // and save the caller's signal mask
   863   os::Bsd::hotspot_sigmask(thread);
   865   return true;
   866 }
   868 void os::pd_start_thread(Thread* thread) {
   869   OSThread * osthread = thread->osthread();
   870   assert(osthread->get_state() != INITIALIZED, "just checking");
   871   Monitor* sync_with_child = osthread->startThread_lock();
   872   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   873   sync_with_child->notify();
   874 }
   876 // Free Bsd resources related to the OSThread
   877 void os::free_thread(OSThread* osthread) {
   878   assert(osthread != NULL, "osthread not set");
   880   if (Thread::current()->osthread() == osthread) {
   881     // Restore caller's signal mask
   882     sigset_t sigmask = osthread->caller_sigmask();
   883     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   884    }
   886   delete osthread;
   887 }
   889 //////////////////////////////////////////////////////////////////////////////
   890 // thread local storage
   892 int os::allocate_thread_local_storage() {
   893   pthread_key_t key;
   894   int rslt = pthread_key_create(&key, NULL);
   895   assert(rslt == 0, "cannot allocate thread local storage");
   896   return (int)key;
   897 }
   899 // Note: This is currently not used by VM, as we don't destroy TLS key
   900 // on VM exit.
   901 void os::free_thread_local_storage(int index) {
   902   int rslt = pthread_key_delete((pthread_key_t)index);
   903   assert(rslt == 0, "invalid index");
   904 }
   906 void os::thread_local_storage_at_put(int index, void* value) {
   907   int rslt = pthread_setspecific((pthread_key_t)index, value);
   908   assert(rslt == 0, "pthread_setspecific failed");
   909 }
   911 extern "C" Thread* get_thread() {
   912   return ThreadLocalStorage::thread();
   913 }
   916 ////////////////////////////////////////////////////////////////////////////////
   917 // time support
   919 // Time since start-up in seconds to a fine granularity.
   920 // Used by VMSelfDestructTimer and the MemProfiler.
   921 double os::elapsedTime() {
   923   return (double)(os::elapsed_counter()) * 0.000001;
   924 }
   926 jlong os::elapsed_counter() {
   927   timeval time;
   928   int status = gettimeofday(&time, NULL);
   929   return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
   930 }
   932 jlong os::elapsed_frequency() {
   933   return (1000 * 1000);
   934 }
   936 bool os::supports_vtime() { return true; }
   937 bool os::enable_vtime()   { return false; }
   938 bool os::vtime_enabled()  { return false; }
   940 double os::elapsedVTime() {
   941   // better than nothing, but not much
   942   return elapsedTime();
   943 }
   945 jlong os::javaTimeMillis() {
   946   timeval time;
   947   int status = gettimeofday(&time, NULL);
   948   assert(status != -1, "bsd error");
   949   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   950 }
   952 #ifndef CLOCK_MONOTONIC
   953 #define CLOCK_MONOTONIC (1)
   954 #endif
   956 #ifdef __APPLE__
   957 void os::Bsd::clock_init() {
   958         // XXXDARWIN: Investigate replacement monotonic clock
   959 }
   960 #else
   961 void os::Bsd::clock_init() {
   962   struct timespec res;
   963   struct timespec tp;
   964   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
   965       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
   966     // yes, monotonic clock is supported
   967     _clock_gettime = ::clock_gettime;
   968   }
   969 }
   970 #endif
   973 jlong os::javaTimeNanos() {
   974   if (Bsd::supports_monotonic_clock()) {
   975     struct timespec tp;
   976     int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
   977     assert(status == 0, "gettime error");
   978     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
   979     return result;
   980   } else {
   981     timeval time;
   982     int status = gettimeofday(&time, NULL);
   983     assert(status != -1, "bsd error");
   984     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
   985     return 1000 * usecs;
   986   }
   987 }
   989 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
   990   if (Bsd::supports_monotonic_clock()) {
   991     info_ptr->max_value = ALL_64_BITS;
   993     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
   994     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
   995     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
   996   } else {
   997     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
   998     info_ptr->max_value = ALL_64_BITS;
  1000     // gettimeofday is a real time clock so it skips
  1001     info_ptr->may_skip_backward = true;
  1002     info_ptr->may_skip_forward = true;
  1005   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
  1008 // Return the real, user, and system times in seconds from an
  1009 // arbitrary fixed point in the past.
  1010 bool os::getTimesSecs(double* process_real_time,
  1011                       double* process_user_time,
  1012                       double* process_system_time) {
  1013   struct tms ticks;
  1014   clock_t real_ticks = times(&ticks);
  1016   if (real_ticks == (clock_t) (-1)) {
  1017     return false;
  1018   } else {
  1019     double ticks_per_second = (double) clock_tics_per_sec;
  1020     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
  1021     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
  1022     *process_real_time = ((double) real_ticks) / ticks_per_second;
  1024     return true;
  1029 char * os::local_time_string(char *buf, size_t buflen) {
  1030   struct tm t;
  1031   time_t long_time;
  1032   time(&long_time);
  1033   localtime_r(&long_time, &t);
  1034   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  1035                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
  1036                t.tm_hour, t.tm_min, t.tm_sec);
  1037   return buf;
  1040 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
  1041   return localtime_r(clock, res);
  1044 ////////////////////////////////////////////////////////////////////////////////
  1045 // runtime exit support
  1047 // Note: os::shutdown() might be called very early during initialization, or
  1048 // called from signal handler. Before adding something to os::shutdown(), make
  1049 // sure it is async-safe and can handle partially initialized VM.
  1050 void os::shutdown() {
  1052   // allow PerfMemory to attempt cleanup of any persistent resources
  1053   perfMemory_exit();
  1055   // needs to remove object in file system
  1056   AttachListener::abort();
  1058   // flush buffered output, finish log files
  1059   ostream_abort();
  1061   // Check for abort hook
  1062   abort_hook_t abort_hook = Arguments::abort_hook();
  1063   if (abort_hook != NULL) {
  1064     abort_hook();
  1069 // Note: os::abort() might be called very early during initialization, or
  1070 // called from signal handler. Before adding something to os::abort(), make
  1071 // sure it is async-safe and can handle partially initialized VM.
  1072 void os::abort(bool dump_core) {
  1073   os::shutdown();
  1074   if (dump_core) {
  1075 #ifndef PRODUCT
  1076     fdStream out(defaultStream::output_fd());
  1077     out.print_raw("Current thread is ");
  1078     char buf[16];
  1079     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
  1080     out.print_raw_cr(buf);
  1081     out.print_raw_cr("Dumping core ...");
  1082 #endif
  1083     ::abort(); // dump core
  1086   ::exit(1);
  1089 // Die immediately, no exit hook, no abort hook, no cleanup.
  1090 void os::die() {
  1091   // _exit() on BsdThreads only kills current thread
  1092   ::abort();
  1095 // unused on bsd for now.
  1096 void os::set_error_file(const char *logfile) {}
  1099 // This method is a copy of JDK's sysGetLastErrorString
  1100 // from src/solaris/hpi/src/system_md.c
  1102 size_t os::lasterror(char *buf, size_t len) {
  1104   if (errno == 0)  return 0;
  1106   const char *s = ::strerror(errno);
  1107   size_t n = ::strlen(s);
  1108   if (n >= len) {
  1109     n = len - 1;
  1111   ::strncpy(buf, s, n);
  1112   buf[n] = '\0';
  1113   return n;
  1116 intx os::current_thread_id() {
  1117 #ifdef __APPLE__
  1118   return (intx)::mach_thread_self();
  1119 #else
  1120   return (intx)::pthread_self();
  1121 #endif
  1123 int os::current_process_id() {
  1125   // Under the old bsd thread library, bsd gives each thread
  1126   // its own process id. Because of this each thread will return
  1127   // a different pid if this method were to return the result
  1128   // of getpid(2). Bsd provides no api that returns the pid
  1129   // of the launcher thread for the vm. This implementation
  1130   // returns a unique pid, the pid of the launcher thread
  1131   // that starts the vm 'process'.
  1133   // Under the NPTL, getpid() returns the same pid as the
  1134   // launcher thread rather than a unique pid per thread.
  1135   // Use gettid() if you want the old pre NPTL behaviour.
  1137   // if you are looking for the result of a call to getpid() that
  1138   // returns a unique pid for the calling thread, then look at the
  1139   // OSThread::thread_id() method in osThread_bsd.hpp file
  1141   return (int)(_initial_pid ? _initial_pid : getpid());
  1144 // DLL functions
  1146 #define JNI_LIB_PREFIX "lib"
  1147 #ifdef __APPLE__
  1148 #define JNI_LIB_SUFFIX ".dylib"
  1149 #else
  1150 #define JNI_LIB_SUFFIX ".so"
  1151 #endif
  1153 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1155 // This must be hard coded because it's the system's temporary
  1156 // directory not the java application's temp directory, ala java.io.tmpdir.
  1157 #ifdef __APPLE__
  1158 // macosx has a secure per-user temporary directory
  1159 char temp_path_storage[PATH_MAX];
  1160 const char* os::get_temp_directory() {
  1161   static char *temp_path = NULL;
  1162   if (temp_path == NULL) {
  1163     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
  1164     if (pathSize == 0 || pathSize > PATH_MAX) {
  1165       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
  1167     temp_path = temp_path_storage;
  1169   return temp_path;
  1171 #else /* __APPLE__ */
  1172 const char* os::get_temp_directory() { return "/tmp"; }
  1173 #endif /* __APPLE__ */
  1175 static bool file_exists(const char* filename) {
  1176   struct stat statbuf;
  1177   if (filename == NULL || strlen(filename) == 0) {
  1178     return false;
  1180   return os::stat(filename, &statbuf) == 0;
  1183 bool os::dll_build_name(char* buffer, size_t buflen,
  1184                         const char* pname, const char* fname) {
  1185   bool retval = false;
  1186   // Copied from libhpi
  1187   const size_t pnamelen = pname ? strlen(pname) : 0;
  1189   // Return error on buffer overflow.
  1190   if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
  1191     return retval;
  1194   if (pnamelen == 0) {
  1195     snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
  1196     retval = true;
  1197   } else if (strchr(pname, *os::path_separator()) != NULL) {
  1198     int n;
  1199     char** pelements = split_path(pname, &n);
  1200     if (pelements == NULL) {
  1201       return false;
  1203     for (int i = 0 ; i < n ; i++) {
  1204       // Really shouldn't be NULL, but check can't hurt
  1205       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1206         continue; // skip the empty path values
  1208       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1209           pelements[i], fname);
  1210       if (file_exists(buffer)) {
  1211         retval = true;
  1212         break;
  1215     // release the storage
  1216     for (int i = 0 ; i < n ; i++) {
  1217       if (pelements[i] != NULL) {
  1218         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
  1221     if (pelements != NULL) {
  1222       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
  1224   } else {
  1225     snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
  1226     retval = true;
  1228   return retval;
  1231 // check if addr is inside libjvm.so
  1232 bool os::address_is_in_vm(address addr) {
  1233   static address libjvm_base_addr;
  1234   Dl_info dlinfo;
  1236   if (libjvm_base_addr == NULL) {
  1237     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
  1238       libjvm_base_addr = (address)dlinfo.dli_fbase;
  1240     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
  1243   if (dladdr((void *)addr, &dlinfo) != 0) {
  1244     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
  1247   return false;
  1251 #define MACH_MAXSYMLEN 256
  1253 bool os::dll_address_to_function_name(address addr, char *buf,
  1254                                       int buflen, int *offset) {
  1255   // buf is not optional, but offset is optional
  1256   assert(buf != NULL, "sanity check");
  1258   Dl_info dlinfo;
  1259   char localbuf[MACH_MAXSYMLEN];
  1261   if (dladdr((void*)addr, &dlinfo) != 0) {
  1262     // see if we have a matching symbol
  1263     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
  1264       if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1265         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
  1267       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1268       return true;
  1270     // no matching symbol so try for just file info
  1271     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1272       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1273                           buf, buflen, offset, dlinfo.dli_fname)) {
  1274          return true;
  1278     // Handle non-dynamic manually:
  1279     if (dlinfo.dli_fbase != NULL &&
  1280         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
  1281                         dlinfo.dli_fbase)) {
  1282       if (!Decoder::demangle(localbuf, buf, buflen)) {
  1283         jio_snprintf(buf, buflen, "%s", localbuf);
  1285       return true;
  1288   buf[0] = '\0';
  1289   if (offset != NULL) *offset = -1;
  1290   return false;
  1293 // ported from solaris version
  1294 bool os::dll_address_to_library_name(address addr, char* buf,
  1295                                      int buflen, int* offset) {
  1296   // buf is not optional, but offset is optional
  1297   assert(buf != NULL, "sanity check");
  1299   Dl_info dlinfo;
  1301   if (dladdr((void*)addr, &dlinfo) != 0) {
  1302     if (dlinfo.dli_fname != NULL) {
  1303       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
  1305     if (dlinfo.dli_fbase != NULL && offset != NULL) {
  1306       *offset = addr - (address)dlinfo.dli_fbase;
  1308     return true;
  1311   buf[0] = '\0';
  1312   if (offset) *offset = -1;
  1313   return false;
  1316 // Loads .dll/.so and
  1317 // in case of error it checks if .dll/.so was built for the
  1318 // same architecture as Hotspot is running on
  1320 #ifdef __APPLE__
  1321 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
  1322   void * result= ::dlopen(filename, RTLD_LAZY);
  1323   if (result != NULL) {
  1324     // Successful loading
  1325     return result;
  1328   // Read system error message into ebuf
  1329   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1330   ebuf[ebuflen-1]='\0';
  1332   return NULL;
  1334 #else
  1335 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1337   void * result= ::dlopen(filename, RTLD_LAZY);
  1338   if (result != NULL) {
  1339     // Successful loading
  1340     return result;
  1343   Elf32_Ehdr elf_head;
  1345   // Read system error message into ebuf
  1346   // It may or may not be overwritten below
  1347   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1348   ebuf[ebuflen-1]='\0';
  1349   int diag_msg_max_length=ebuflen-strlen(ebuf);
  1350   char* diag_msg_buf=ebuf+strlen(ebuf);
  1352   if (diag_msg_max_length==0) {
  1353     // No more space in ebuf for additional diagnostics message
  1354     return NULL;
  1358   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
  1360   if (file_descriptor < 0) {
  1361     // Can't open library, report dlerror() message
  1362     return NULL;
  1365   bool failed_to_read_elf_head=
  1366     (sizeof(elf_head)!=
  1367         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
  1369   ::close(file_descriptor);
  1370   if (failed_to_read_elf_head) {
  1371     // file i/o error - report dlerror() msg
  1372     return NULL;
  1375   typedef struct {
  1376     Elf32_Half  code;         // Actual value as defined in elf.h
  1377     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
  1378     char        elf_class;    // 32 or 64 bit
  1379     char        endianess;    // MSB or LSB
  1380     char*       name;         // String representation
  1381   } arch_t;
  1383   #ifndef EM_486
  1384   #define EM_486          6               /* Intel 80486 */
  1385   #endif
  1387   #ifndef EM_MIPS_RS3_LE
  1388   #define EM_MIPS_RS3_LE  10              /* MIPS */
  1389   #endif
  1391   #ifndef EM_PPC64
  1392   #define EM_PPC64        21              /* PowerPC64 */
  1393   #endif
  1395   #ifndef EM_S390
  1396   #define EM_S390         22              /* IBM System/390 */
  1397   #endif
  1399   #ifndef EM_IA_64
  1400   #define EM_IA_64        50              /* HP/Intel IA-64 */
  1401   #endif
  1403   #ifndef EM_X86_64
  1404   #define EM_X86_64       62              /* AMD x86-64 */
  1405   #endif
  1407   static const arch_t arch_array[]={
  1408     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1409     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1410     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
  1411     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
  1412     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1413     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1414     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
  1415     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
  1416     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
  1417     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
  1418     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
  1419     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
  1420     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
  1421     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
  1422     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1423     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1424   };
  1426   #if  (defined IA32)
  1427     static  Elf32_Half running_arch_code=EM_386;
  1428   #elif   (defined AMD64)
  1429     static  Elf32_Half running_arch_code=EM_X86_64;
  1430   #elif  (defined IA64)
  1431     static  Elf32_Half running_arch_code=EM_IA_64;
  1432   #elif  (defined __sparc) && (defined _LP64)
  1433     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1434   #elif  (defined __sparc) && (!defined _LP64)
  1435     static  Elf32_Half running_arch_code=EM_SPARC;
  1436   #elif  (defined __powerpc64__)
  1437     static  Elf32_Half running_arch_code=EM_PPC64;
  1438   #elif  (defined __powerpc__)
  1439     static  Elf32_Half running_arch_code=EM_PPC;
  1440   #elif  (defined ARM)
  1441     static  Elf32_Half running_arch_code=EM_ARM;
  1442   #elif  (defined S390)
  1443     static  Elf32_Half running_arch_code=EM_S390;
  1444   #elif  (defined ALPHA)
  1445     static  Elf32_Half running_arch_code=EM_ALPHA;
  1446   #elif  (defined MIPSEL)
  1447     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1448   #elif  (defined PARISC)
  1449     static  Elf32_Half running_arch_code=EM_PARISC;
  1450   #elif  (defined MIPS)
  1451     static  Elf32_Half running_arch_code=EM_MIPS;
  1452   #elif  (defined M68K)
  1453     static  Elf32_Half running_arch_code=EM_68K;
  1454   #else
  1455     #error Method os::dll_load requires that one of following is defined:\
  1456          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1457   #endif
  1459   // Identify compatability class for VM's architecture and library's architecture
  1460   // Obtain string descriptions for architectures
  1462   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
  1463   int running_arch_index=-1;
  1465   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
  1466     if (running_arch_code == arch_array[i].code) {
  1467       running_arch_index    = i;
  1469     if (lib_arch.code == arch_array[i].code) {
  1470       lib_arch.compat_class = arch_array[i].compat_class;
  1471       lib_arch.name         = arch_array[i].name;
  1475   assert(running_arch_index != -1,
  1476     "Didn't find running architecture code (running_arch_code) in arch_array");
  1477   if (running_arch_index == -1) {
  1478     // Even though running architecture detection failed
  1479     // we may still continue with reporting dlerror() message
  1480     return NULL;
  1483   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
  1484     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
  1485     return NULL;
  1488 #ifndef S390
  1489   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
  1490     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
  1491     return NULL;
  1493 #endif // !S390
  1495   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1496     if ( lib_arch.name!=NULL ) {
  1497       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1498         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1499         lib_arch.name, arch_array[running_arch_index].name);
  1500     } else {
  1501       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1502       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1503         lib_arch.code,
  1504         arch_array[running_arch_index].name);
  1508   return NULL;
  1510 #endif /* !__APPLE__ */
  1512 // XXX: Do we need a lock around this as per Linux?
  1513 void* os::dll_lookup(void* handle, const char* name) {
  1514   return dlsym(handle, name);
  1518 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1519   int fd = ::open(filename, O_RDONLY);
  1520   if (fd == -1) {
  1521      return false;
  1524   char buf[32];
  1525   int bytes;
  1526   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1527     st->print_raw(buf, bytes);
  1530   ::close(fd);
  1532   return true;
  1535 void os::print_dll_info(outputStream *st) {
  1536   st->print_cr("Dynamic libraries:");
  1537 #ifdef RTLD_DI_LINKMAP
  1538   Dl_info dli;
  1539   void *handle;
  1540   Link_map *map;
  1541   Link_map *p;
  1543   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
  1544       dli.dli_fname == NULL) {
  1545     st->print_cr("Error: Cannot print dynamic libraries.");
  1546     return;
  1548   handle = dlopen(dli.dli_fname, RTLD_LAZY);
  1549   if (handle == NULL) {
  1550     st->print_cr("Error: Cannot print dynamic libraries.");
  1551     return;
  1553   dlinfo(handle, RTLD_DI_LINKMAP, &map);
  1554   if (map == NULL) {
  1555     st->print_cr("Error: Cannot print dynamic libraries.");
  1556     return;
  1559   while (map->l_prev != NULL)
  1560     map = map->l_prev;
  1562   while (map != NULL) {
  1563     st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
  1564     map = map->l_next;
  1567   dlclose(handle);
  1568 #elif defined(__APPLE__)
  1569   uint32_t count;
  1570   uint32_t i;
  1572   count = _dyld_image_count();
  1573   for (i = 1; i < count; i++) {
  1574     const char *name = _dyld_get_image_name(i);
  1575     intptr_t slide = _dyld_get_image_vmaddr_slide(i);
  1576     st->print_cr(PTR_FORMAT " \t%s", slide, name);
  1578 #else
  1579   st->print_cr("Error: Cannot print dynamic libraries.");
  1580 #endif
  1583 void os::print_os_info_brief(outputStream* st) {
  1584   st->print("Bsd");
  1586   os::Posix::print_uname_info(st);
  1589 void os::print_os_info(outputStream* st) {
  1590   st->print("OS:");
  1591   st->print("Bsd");
  1593   os::Posix::print_uname_info(st);
  1595   os::Posix::print_rlimit_info(st);
  1597   os::Posix::print_load_average(st);
  1600 void os::pd_print_cpu_info(outputStream* st) {
  1601   // Nothing to do for now.
  1604 void os::print_memory_info(outputStream* st) {
  1606   st->print("Memory:");
  1607   st->print(" %dk page", os::vm_page_size()>>10);
  1609   st->print(", physical " UINT64_FORMAT "k",
  1610             os::physical_memory() >> 10);
  1611   st->print("(" UINT64_FORMAT "k free)",
  1612             os::available_memory() >> 10);
  1613   st->cr();
  1615   // meminfo
  1616   st->print("\n/proc/meminfo:\n");
  1617   _print_ascii_file("/proc/meminfo", st);
  1618   st->cr();
  1621 void os::print_siginfo(outputStream* st, void* siginfo) {
  1622   const siginfo_t* si = (const siginfo_t*)siginfo;
  1624   os::Posix::print_siginfo_brief(st, si);
  1626   if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
  1627       UseSharedSpaces) {
  1628     FileMapInfo* mapinfo = FileMapInfo::current_info();
  1629     if (mapinfo->is_in_shared_space(si->si_addr)) {
  1630       st->print("\n\nError accessing class data sharing archive."   \
  1631                 " Mapped file inaccessible during execution, "      \
  1632                 " possible disk/network problem.");
  1635   st->cr();
  1639 static void print_signal_handler(outputStream* st, int sig,
  1640                                  char* buf, size_t buflen);
  1642 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  1643   st->print_cr("Signal Handlers:");
  1644   print_signal_handler(st, SIGSEGV, buf, buflen);
  1645   print_signal_handler(st, SIGBUS , buf, buflen);
  1646   print_signal_handler(st, SIGFPE , buf, buflen);
  1647   print_signal_handler(st, SIGPIPE, buf, buflen);
  1648   print_signal_handler(st, SIGXFSZ, buf, buflen);
  1649   print_signal_handler(st, SIGILL , buf, buflen);
  1650   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
  1651   print_signal_handler(st, SR_signum, buf, buflen);
  1652   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
  1653   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
  1654   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
  1655   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
  1658 static char saved_jvm_path[MAXPATHLEN] = {0};
  1660 // Find the full path to the current module, libjvm
  1661 void os::jvm_path(char *buf, jint buflen) {
  1662   // Error checking.
  1663   if (buflen < MAXPATHLEN) {
  1664     assert(false, "must use a large-enough buffer");
  1665     buf[0] = '\0';
  1666     return;
  1668   // Lazy resolve the path to current module.
  1669   if (saved_jvm_path[0] != 0) {
  1670     strcpy(buf, saved_jvm_path);
  1671     return;
  1674   char dli_fname[MAXPATHLEN];
  1675   bool ret = dll_address_to_library_name(
  1676                 CAST_FROM_FN_PTR(address, os::jvm_path),
  1677                 dli_fname, sizeof(dli_fname), NULL);
  1678   assert(ret, "cannot locate libjvm");
  1679   char *rp = NULL;
  1680   if (ret && dli_fname[0] != '\0') {
  1681     rp = realpath(dli_fname, buf);
  1683   if (rp == NULL)
  1684     return;
  1686   if (Arguments::created_by_gamma_launcher()) {
  1687     // Support for the gamma launcher.  Typical value for buf is
  1688     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm".  If "/jre/lib/" appears at
  1689     // the right place in the string, then assume we are installed in a JDK and
  1690     // we're done.  Otherwise, check for a JAVA_HOME environment variable and
  1691     // construct a path to the JVM being overridden.
  1693     const char *p = buf + strlen(buf) - 1;
  1694     for (int count = 0; p > buf && count < 5; ++count) {
  1695       for (--p; p > buf && *p != '/'; --p)
  1696         /* empty */ ;
  1699     if (strncmp(p, "/jre/lib/", 9) != 0) {
  1700       // Look for JAVA_HOME in the environment.
  1701       char* java_home_var = ::getenv("JAVA_HOME");
  1702       if (java_home_var != NULL && java_home_var[0] != 0) {
  1703         char* jrelib_p;
  1704         int len;
  1706         // Check the current module name "libjvm"
  1707         p = strrchr(buf, '/');
  1708         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1710         rp = realpath(java_home_var, buf);
  1711         if (rp == NULL)
  1712           return;
  1714         // determine if this is a legacy image or modules image
  1715         // modules image doesn't have "jre" subdirectory
  1716         len = strlen(buf);
  1717         jrelib_p = buf + len;
  1719         // Add the appropriate library subdir
  1720         snprintf(jrelib_p, buflen-len, "/jre/lib");
  1721         if (0 != access(buf, F_OK)) {
  1722           snprintf(jrelib_p, buflen-len, "/lib");
  1725         // Add the appropriate client or server subdir
  1726         len = strlen(buf);
  1727         jrelib_p = buf + len;
  1728         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
  1729         if (0 != access(buf, F_OK)) {
  1730           snprintf(jrelib_p, buflen-len, "");
  1733         // If the path exists within JAVA_HOME, add the JVM library name
  1734         // to complete the path to JVM being overridden.  Otherwise fallback
  1735         // to the path to the current library.
  1736         if (0 == access(buf, F_OK)) {
  1737           // Use current module name "libjvm"
  1738           len = strlen(buf);
  1739           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1740         } else {
  1741           // Fall back to path of current library
  1742           rp = realpath(dli_fname, buf);
  1743           if (rp == NULL)
  1744             return;
  1750   strcpy(saved_jvm_path, buf);
  1753 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  1754   // no prefix required, not even "_"
  1757 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  1758   // no suffix required
  1761 ////////////////////////////////////////////////////////////////////////////////
  1762 // sun.misc.Signal support
  1764 static volatile jint sigint_count = 0;
  1766 static void
  1767 UserHandler(int sig, void *siginfo, void *context) {
  1768   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1769   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1770   // don't want to flood the manager thread with sem_post requests.
  1771   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1772       return;
  1774   // Ctrl-C is pressed during error reporting, likely because the error
  1775   // handler fails to abort. Let VM die immediately.
  1776   if (sig == SIGINT && is_error_reported()) {
  1777      os::die();
  1780   os::signal_notify(sig);
  1783 void* os::user_handler() {
  1784   return CAST_FROM_FN_PTR(void*, UserHandler);
  1787 extern "C" {
  1788   typedef void (*sa_handler_t)(int);
  1789   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  1792 void* os::signal(int signal_number, void* handler) {
  1793   struct sigaction sigAct, oldSigAct;
  1795   sigfillset(&(sigAct.sa_mask));
  1796   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
  1797   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
  1799   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
  1800     // -1 means registration failed
  1801     return (void *)-1;
  1804   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
  1807 void os::signal_raise(int signal_number) {
  1808   ::raise(signal_number);
  1811 /*
  1812  * The following code is moved from os.cpp for making this
  1813  * code platform specific, which it is by its very nature.
  1814  */
  1816 // Will be modified when max signal is changed to be dynamic
  1817 int os::sigexitnum_pd() {
  1818   return NSIG;
  1821 // a counter for each possible signal value
  1822 static volatile jint pending_signals[NSIG+1] = { 0 };
  1824 // Bsd(POSIX) specific hand shaking semaphore.
  1825 #ifdef __APPLE__
  1826 typedef semaphore_t os_semaphore_t;
  1827 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1828 #define SEM_WAIT(sem)           semaphore_wait(sem)
  1829 #define SEM_POST(sem)           semaphore_signal(sem)
  1830 #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1831 #else
  1832 typedef sem_t os_semaphore_t;
  1833 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1834 #define SEM_WAIT(sem)           sem_wait(&sem)
  1835 #define SEM_POST(sem)           sem_post(&sem)
  1836 #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1837 #endif
  1839 class Semaphore : public StackObj {
  1840   public:
  1841     Semaphore();
  1842     ~Semaphore();
  1843     void signal();
  1844     void wait();
  1845     bool trywait();
  1846     bool timedwait(unsigned int sec, int nsec);
  1847   private:
  1848     jlong currenttime() const;
  1849     semaphore_t _semaphore;
  1850 };
  1852 Semaphore::Semaphore() : _semaphore(0) {
  1853   SEM_INIT(_semaphore, 0);
  1856 Semaphore::~Semaphore() {
  1857   SEM_DESTROY(_semaphore);
  1860 void Semaphore::signal() {
  1861   SEM_POST(_semaphore);
  1864 void Semaphore::wait() {
  1865   SEM_WAIT(_semaphore);
  1868 jlong Semaphore::currenttime() const {
  1869     struct timeval tv;
  1870     gettimeofday(&tv, NULL);
  1871     return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
  1874 #ifdef __APPLE__
  1875 bool Semaphore::trywait() {
  1876   return timedwait(0, 0);
  1879 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  1880   kern_return_t kr = KERN_ABORTED;
  1881   mach_timespec_t waitspec;
  1882   waitspec.tv_sec = sec;
  1883   waitspec.tv_nsec = nsec;
  1885   jlong starttime = currenttime();
  1887   kr = semaphore_timedwait(_semaphore, waitspec);
  1888   while (kr == KERN_ABORTED) {
  1889     jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
  1891     jlong current = currenttime();
  1892     jlong passedtime = current - starttime;
  1894     if (passedtime >= totalwait) {
  1895       waitspec.tv_sec = 0;
  1896       waitspec.tv_nsec = 0;
  1897     } else {
  1898       jlong waittime = totalwait - (current - starttime);
  1899       waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
  1900       waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
  1903     kr = semaphore_timedwait(_semaphore, waitspec);
  1906   return kr == KERN_SUCCESS;
  1909 #else
  1911 bool Semaphore::trywait() {
  1912   return sem_trywait(&_semaphore) == 0;
  1915 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  1916   struct timespec ts;
  1917   jlong endtime = unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
  1919   while (1) {
  1920     int result = sem_timedwait(&_semaphore, &ts);
  1921     if (result == 0) {
  1922       return true;
  1923     } else if (errno == EINTR) {
  1924       continue;
  1925     } else if (errno == ETIMEDOUT) {
  1926       return false;
  1927     } else {
  1928       return false;
  1933 #endif // __APPLE__
  1935 static os_semaphore_t sig_sem;
  1936 static Semaphore sr_semaphore;
  1938 void os::signal_init_pd() {
  1939   // Initialize signal structures
  1940   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
  1942   // Initialize signal semaphore
  1943   ::SEM_INIT(sig_sem, 0);
  1946 void os::signal_notify(int sig) {
  1947   Atomic::inc(&pending_signals[sig]);
  1948   ::SEM_POST(sig_sem);
  1951 static int check_pending_signals(bool wait) {
  1952   Atomic::store(0, &sigint_count);
  1953   for (;;) {
  1954     for (int i = 0; i < NSIG + 1; i++) {
  1955       jint n = pending_signals[i];
  1956       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  1957         return i;
  1960     if (!wait) {
  1961       return -1;
  1963     JavaThread *thread = JavaThread::current();
  1964     ThreadBlockInVM tbivm(thread);
  1966     bool threadIsSuspended;
  1967     do {
  1968       thread->set_suspend_equivalent();
  1969       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  1970       ::SEM_WAIT(sig_sem);
  1972       // were we externally suspended while we were waiting?
  1973       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  1974       if (threadIsSuspended) {
  1975         //
  1976         // The semaphore has been incremented, but while we were waiting
  1977         // another thread suspended us. We don't want to continue running
  1978         // while suspended because that would surprise the thread that
  1979         // suspended us.
  1980         //
  1981         ::SEM_POST(sig_sem);
  1983         thread->java_suspend_self();
  1985     } while (threadIsSuspended);
  1989 int os::signal_lookup() {
  1990   return check_pending_signals(false);
  1993 int os::signal_wait() {
  1994   return check_pending_signals(true);
  1997 ////////////////////////////////////////////////////////////////////////////////
  1998 // Virtual Memory
  2000 int os::vm_page_size() {
  2001   // Seems redundant as all get out
  2002   assert(os::Bsd::page_size() != -1, "must call os::init");
  2003   return os::Bsd::page_size();
  2006 // Solaris allocates memory by pages.
  2007 int os::vm_allocation_granularity() {
  2008   assert(os::Bsd::page_size() != -1, "must call os::init");
  2009   return os::Bsd::page_size();
  2012 // Rationale behind this function:
  2013 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
  2014 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
  2015 //  samples for JITted code. Here we create private executable mapping over the code cache
  2016 //  and then we can use standard (well, almost, as mapping can change) way to provide
  2017 //  info for the reporting script by storing timestamp and location of symbol
  2018 void bsd_wrap_code(char* base, size_t size) {
  2019   static volatile jint cnt = 0;
  2021   if (!UseOprofile) {
  2022     return;
  2025   char buf[PATH_MAX + 1];
  2026   int num = Atomic::add(1, &cnt);
  2028   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
  2029            os::get_temp_directory(), os::current_process_id(), num);
  2030   unlink(buf);
  2032   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
  2034   if (fd != -1) {
  2035     off_t rv = ::lseek(fd, size-2, SEEK_SET);
  2036     if (rv != (off_t)-1) {
  2037       if (::write(fd, "", 1) == 1) {
  2038         mmap(base, size,
  2039              PROT_READ|PROT_WRITE|PROT_EXEC,
  2040              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
  2043     ::close(fd);
  2044     unlink(buf);
  2048 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
  2049                                     int err) {
  2050   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
  2051           ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
  2052           strerror(err), err);
  2055 // NOTE: Bsd kernel does not really reserve the pages for us.
  2056 //       All it does is to check if there are enough free pages
  2057 //       left at the time of mmap(). This could be a potential
  2058 //       problem.
  2059 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
  2060   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
  2061 #ifdef __OpenBSD__
  2062   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2063   if (::mprotect(addr, size, prot) == 0) {
  2064     return true;
  2066 #else
  2067   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2068                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2069   if (res != (uintptr_t) MAP_FAILED) {
  2070     return true;
  2072 #endif
  2074   // Warn about any commit errors we see in non-product builds just
  2075   // in case mmap() doesn't work as described on the man page.
  2076   NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
  2078   return false;
  2081 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2082                        bool exec) {
  2083   // alignment_hint is ignored on this OS
  2084   return pd_commit_memory(addr, size, exec);
  2087 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
  2088                                   const char* mesg) {
  2089   assert(mesg != NULL, "mesg must be specified");
  2090   if (!pd_commit_memory(addr, size, exec)) {
  2091     // add extra info in product mode for vm_exit_out_of_memory():
  2092     PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
  2093     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
  2097 void os::pd_commit_memory_or_exit(char* addr, size_t size,
  2098                                   size_t alignment_hint, bool exec,
  2099                                   const char* mesg) {
  2100   // alignment_hint is ignored on this OS
  2101   pd_commit_memory_or_exit(addr, size, exec, mesg);
  2104 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2107 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2108   ::madvise(addr, bytes, MADV_DONTNEED);
  2111 void os::numa_make_global(char *addr, size_t bytes) {
  2114 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
  2117 bool os::numa_topology_changed()   { return false; }
  2119 size_t os::numa_get_groups_num() {
  2120   return 1;
  2123 int os::numa_get_group_id() {
  2124   return 0;
  2127 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2128   if (size > 0) {
  2129     ids[0] = 0;
  2130     return 1;
  2132   return 0;
  2135 bool os::get_page_info(char *start, page_info* info) {
  2136   return false;
  2139 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2140   return end;
  2144 bool os::pd_uncommit_memory(char* addr, size_t size) {
  2145 #ifdef __OpenBSD__
  2146   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2147   return ::mprotect(addr, size, PROT_NONE) == 0;
  2148 #else
  2149   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2150                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2151   return res  != (uintptr_t) MAP_FAILED;
  2152 #endif
  2155 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2156   return os::commit_memory(addr, size, !ExecMem);
  2159 // If this is a growable mapping, remove the guard pages entirely by
  2160 // munmap()ping them.  If not, just call uncommit_memory().
  2161 bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2162   return os::uncommit_memory(addr, size);
  2165 static address _highest_vm_reserved_address = NULL;
  2167 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
  2168 // at 'requested_addr'. If there are existing memory mappings at the same
  2169 // location, however, they will be overwritten. If 'fixed' is false,
  2170 // 'requested_addr' is only treated as a hint, the return value may or
  2171 // may not start from the requested address. Unlike Bsd mmap(), this
  2172 // function returns NULL to indicate failure.
  2173 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
  2174   char * addr;
  2175   int flags;
  2177   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
  2178   if (fixed) {
  2179     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
  2180     flags |= MAP_FIXED;
  2183   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
  2184   // touch an uncommitted page. Otherwise, the read/write might
  2185   // succeed if we have enough swap space to back the physical page.
  2186   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
  2187                        flags, -1, 0);
  2189   if (addr != MAP_FAILED) {
  2190     // anon_mmap() should only get called during VM initialization,
  2191     // don't need lock (actually we can skip locking even it can be called
  2192     // from multiple threads, because _highest_vm_reserved_address is just a
  2193     // hint about the upper limit of non-stack memory regions.)
  2194     if ((address)addr + bytes > _highest_vm_reserved_address) {
  2195       _highest_vm_reserved_address = (address)addr + bytes;
  2199   return addr == MAP_FAILED ? NULL : addr;
  2202 // Don't update _highest_vm_reserved_address, because there might be memory
  2203 // regions above addr + size. If so, releasing a memory region only creates
  2204 // a hole in the address space, it doesn't help prevent heap-stack collision.
  2205 //
  2206 static int anon_munmap(char * addr, size_t size) {
  2207   return ::munmap(addr, size) == 0;
  2210 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2211                          size_t alignment_hint) {
  2212   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2215 bool os::pd_release_memory(char* addr, size_t size) {
  2216   return anon_munmap(addr, size);
  2219 static bool bsd_mprotect(char* addr, size_t size, int prot) {
  2220   // Bsd wants the mprotect address argument to be page aligned.
  2221   char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
  2223   // According to SUSv3, mprotect() should only be used with mappings
  2224   // established by mmap(), and mmap() always maps whole pages. Unaligned
  2225   // 'addr' likely indicates problem in the VM (e.g. trying to change
  2226   // protection of malloc'ed or statically allocated memory). Check the
  2227   // caller if you hit this assert.
  2228   assert(addr == bottom, "sanity check");
  2230   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
  2231   return ::mprotect(bottom, size, prot) == 0;
  2234 // Set protections specified
  2235 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  2236                         bool is_committed) {
  2237   unsigned int p = 0;
  2238   switch (prot) {
  2239   case MEM_PROT_NONE: p = PROT_NONE; break;
  2240   case MEM_PROT_READ: p = PROT_READ; break;
  2241   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
  2242   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
  2243   default:
  2244     ShouldNotReachHere();
  2246   // is_committed is unused.
  2247   return bsd_mprotect(addr, bytes, p);
  2250 bool os::guard_memory(char* addr, size_t size) {
  2251   return bsd_mprotect(addr, size, PROT_NONE);
  2254 bool os::unguard_memory(char* addr, size_t size) {
  2255   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
  2258 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
  2259   return false;
  2262 // Large page support
  2264 static size_t _large_page_size = 0;
  2266 void os::large_page_init() {
  2270 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
  2271   // "exec" is passed in but not used.  Creating the shared image for
  2272   // the code cache doesn't have an SHM_X executable permission to check.
  2273   assert(UseLargePages && UseSHM, "only for SHM large pages");
  2275   key_t key = IPC_PRIVATE;
  2276   char *addr;
  2278   bool warn_on_failure = UseLargePages &&
  2279                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2280                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2281                         );
  2282   char msg[128];
  2284   // Create a large shared memory region to attach to based on size.
  2285   // Currently, size is the total size of the heap
  2286   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2287   if (shmid == -1) {
  2288      // Possible reasons for shmget failure:
  2289      // 1. shmmax is too small for Java heap.
  2290      //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2291      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2292      // 2. not enough large page memory.
  2293      //    > check available large pages: cat /proc/meminfo
  2294      //    > increase amount of large pages:
  2295      //          echo new_value > /proc/sys/vm/nr_hugepages
  2296      //      Note 1: different Bsd may use different name for this property,
  2297      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2298      //      Note 2: it's possible there's enough physical memory available but
  2299      //            they are so fragmented after a long run that they can't
  2300      //            coalesce into large pages. Try to reserve large pages when
  2301      //            the system is still "fresh".
  2302      if (warn_on_failure) {
  2303        jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
  2304        warning(msg);
  2306      return NULL;
  2309   // attach to the region
  2310   addr = (char*)shmat(shmid, req_addr, 0);
  2311   int err = errno;
  2313   // Remove shmid. If shmat() is successful, the actual shared memory segment
  2314   // will be deleted when it's detached by shmdt() or when the process
  2315   // terminates. If shmat() is not successful this will remove the shared
  2316   // segment immediately.
  2317   shmctl(shmid, IPC_RMID, NULL);
  2319   if ((intptr_t)addr == -1) {
  2320      if (warn_on_failure) {
  2321        jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
  2322        warning(msg);
  2324      return NULL;
  2327   // The memory is committed
  2328   MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
  2330   return addr;
  2333 bool os::release_memory_special(char* base, size_t bytes) {
  2334   MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
  2335   // detaching the SHM segment will also delete it, see reserve_memory_special()
  2336   int rslt = shmdt(base);
  2337   if (rslt == 0) {
  2338     tkr.record((address)base, bytes);
  2339     return true;
  2340   } else {
  2341     tkr.discard();
  2342     return false;
  2347 size_t os::large_page_size() {
  2348   return _large_page_size;
  2351 // HugeTLBFS allows application to commit large page memory on demand;
  2352 // with SysV SHM the entire memory region must be allocated as shared
  2353 // memory.
  2354 bool os::can_commit_large_page_memory() {
  2355   return UseHugeTLBFS;
  2358 bool os::can_execute_large_page_memory() {
  2359   return UseHugeTLBFS;
  2362 // Reserve memory at an arbitrary address, only if that area is
  2363 // available (and not reserved for something else).
  2365 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2366   const int max_tries = 10;
  2367   char* base[max_tries];
  2368   size_t size[max_tries];
  2369   const size_t gap = 0x000000;
  2371   // Assert only that the size is a multiple of the page size, since
  2372   // that's all that mmap requires, and since that's all we really know
  2373   // about at this low abstraction level.  If we need higher alignment,
  2374   // we can either pass an alignment to this method or verify alignment
  2375   // in one of the methods further up the call chain.  See bug 5044738.
  2376   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
  2378   // Repeatedly allocate blocks until the block is allocated at the
  2379   // right spot. Give up after max_tries. Note that reserve_memory() will
  2380   // automatically update _highest_vm_reserved_address if the call is
  2381   // successful. The variable tracks the highest memory address every reserved
  2382   // by JVM. It is used to detect heap-stack collision if running with
  2383   // fixed-stack BsdThreads. Because here we may attempt to reserve more
  2384   // space than needed, it could confuse the collision detecting code. To
  2385   // solve the problem, save current _highest_vm_reserved_address and
  2386   // calculate the correct value before return.
  2387   address old_highest = _highest_vm_reserved_address;
  2389   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2390   // if kernel honors the hint then we can return immediately.
  2391   char * addr = anon_mmap(requested_addr, bytes, false);
  2392   if (addr == requested_addr) {
  2393      return requested_addr;
  2396   if (addr != NULL) {
  2397      // mmap() is successful but it fails to reserve at the requested address
  2398      anon_munmap(addr, bytes);
  2401   int i;
  2402   for (i = 0; i < max_tries; ++i) {
  2403     base[i] = reserve_memory(bytes);
  2405     if (base[i] != NULL) {
  2406       // Is this the block we wanted?
  2407       if (base[i] == requested_addr) {
  2408         size[i] = bytes;
  2409         break;
  2412       // Does this overlap the block we wanted? Give back the overlapped
  2413       // parts and try again.
  2415       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
  2416       if (top_overlap >= 0 && top_overlap < bytes) {
  2417         unmap_memory(base[i], top_overlap);
  2418         base[i] += top_overlap;
  2419         size[i] = bytes - top_overlap;
  2420       } else {
  2421         size_t bottom_overlap = base[i] + bytes - requested_addr;
  2422         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
  2423           unmap_memory(requested_addr, bottom_overlap);
  2424           size[i] = bytes - bottom_overlap;
  2425         } else {
  2426           size[i] = bytes;
  2432   // Give back the unused reserved pieces.
  2434   for (int j = 0; j < i; ++j) {
  2435     if (base[j] != NULL) {
  2436       unmap_memory(base[j], size[j]);
  2440   if (i < max_tries) {
  2441     _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
  2442     return requested_addr;
  2443   } else {
  2444     _highest_vm_reserved_address = old_highest;
  2445     return NULL;
  2449 size_t os::read(int fd, void *buf, unsigned int nBytes) {
  2450   RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
  2453 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
  2454 // Solaris uses poll(), bsd uses park().
  2455 // Poll() is likely a better choice, assuming that Thread.interrupt()
  2456 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
  2457 // SIGSEGV, see 4355769.
  2459 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  2460   assert(thread == Thread::current(),  "thread consistency check");
  2462   ParkEvent * const slp = thread->_SleepEvent ;
  2463   slp->reset() ;
  2464   OrderAccess::fence() ;
  2466   if (interruptible) {
  2467     jlong prevtime = javaTimeNanos();
  2469     for (;;) {
  2470       if (os::is_interrupted(thread, true)) {
  2471         return OS_INTRPT;
  2474       jlong newtime = javaTimeNanos();
  2476       if (newtime - prevtime < 0) {
  2477         // time moving backwards, should only happen if no monotonic clock
  2478         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2479         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2480       } else {
  2481         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2484       if(millis <= 0) {
  2485         return OS_OK;
  2488       prevtime = newtime;
  2491         assert(thread->is_Java_thread(), "sanity check");
  2492         JavaThread *jt = (JavaThread *) thread;
  2493         ThreadBlockInVM tbivm(jt);
  2494         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
  2496         jt->set_suspend_equivalent();
  2497         // cleared by handle_special_suspend_equivalent_condition() or
  2498         // java_suspend_self() via check_and_wait_while_suspended()
  2500         slp->park(millis);
  2502         // were we externally suspended while we were waiting?
  2503         jt->check_and_wait_while_suspended();
  2506   } else {
  2507     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  2508     jlong prevtime = javaTimeNanos();
  2510     for (;;) {
  2511       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
  2512       // the 1st iteration ...
  2513       jlong newtime = javaTimeNanos();
  2515       if (newtime - prevtime < 0) {
  2516         // time moving backwards, should only happen if no monotonic clock
  2517         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2518         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2519       } else {
  2520         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2523       if(millis <= 0) break ;
  2525       prevtime = newtime;
  2526       slp->park(millis);
  2528     return OS_OK ;
  2532 int os::naked_sleep() {
  2533   // %% make the sleep time an integer flag. for now use 1 millisec.
  2534   return os::sleep(Thread::current(), 1, false);
  2537 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  2538 void os::infinite_sleep() {
  2539   while (true) {    // sleep forever ...
  2540     ::sleep(100);   // ... 100 seconds at a time
  2544 // Used to convert frequent JVM_Yield() to nops
  2545 bool os::dont_yield() {
  2546   return DontYieldALot;
  2549 void os::yield() {
  2550   sched_yield();
  2553 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
  2555 void os::yield_all(int attempts) {
  2556   // Yields to all threads, including threads with lower priorities
  2557   // Threads on Bsd are all with same priority. The Solaris style
  2558   // os::yield_all() with nanosleep(1ms) is not necessary.
  2559   sched_yield();
  2562 // Called from the tight loops to possibly influence time-sharing heuristics
  2563 void os::loop_breaker(int attempts) {
  2564   os::yield_all(attempts);
  2567 ////////////////////////////////////////////////////////////////////////////////
  2568 // thread priority support
  2570 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
  2571 // only supports dynamic priority, static priority must be zero. For real-time
  2572 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
  2573 // However, for large multi-threaded applications, SCHED_RR is not only slower
  2574 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
  2575 // of 5 runs - Sep 2005).
  2576 //
  2577 // The following code actually changes the niceness of kernel-thread/LWP. It
  2578 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
  2579 // not the entire user process, and user level threads are 1:1 mapped to kernel
  2580 // threads. It has always been the case, but could change in the future. For
  2581 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
  2582 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
  2584 #if !defined(__APPLE__)
  2585 int os::java_to_os_priority[CriticalPriority + 1] = {
  2586   19,              // 0 Entry should never be used
  2588    0,              // 1 MinPriority
  2589    3,              // 2
  2590    6,              // 3
  2592   10,              // 4
  2593   15,              // 5 NormPriority
  2594   18,              // 6
  2596   21,              // 7
  2597   25,              // 8
  2598   28,              // 9 NearMaxPriority
  2600   31,              // 10 MaxPriority
  2602   31               // 11 CriticalPriority
  2603 };
  2604 #else
  2605 /* Using Mach high-level priority assignments */
  2606 int os::java_to_os_priority[CriticalPriority + 1] = {
  2607    0,              // 0 Entry should never be used (MINPRI_USER)
  2609   27,              // 1 MinPriority
  2610   28,              // 2
  2611   29,              // 3
  2613   30,              // 4
  2614   31,              // 5 NormPriority (BASEPRI_DEFAULT)
  2615   32,              // 6
  2617   33,              // 7
  2618   34,              // 8
  2619   35,              // 9 NearMaxPriority
  2621   36,              // 10 MaxPriority
  2623   36               // 11 CriticalPriority
  2624 };
  2625 #endif
  2627 static int prio_init() {
  2628   if (ThreadPriorityPolicy == 1) {
  2629     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
  2630     // if effective uid is not root. Perhaps, a more elegant way of doing
  2631     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
  2632     if (geteuid() != 0) {
  2633       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
  2634         warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
  2636       ThreadPriorityPolicy = 0;
  2639   if (UseCriticalJavaThreadPriority) {
  2640     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
  2642   return 0;
  2645 OSReturn os::set_native_priority(Thread* thread, int newpri) {
  2646   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
  2648 #ifdef __OpenBSD__
  2649   // OpenBSD pthread_setprio starves low priority threads
  2650   return OS_OK;
  2651 #elif defined(__FreeBSD__)
  2652   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
  2653 #elif defined(__APPLE__) || defined(__NetBSD__)
  2654   struct sched_param sp;
  2655   int policy;
  2656   pthread_t self = pthread_self();
  2658   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2659     return OS_ERR;
  2661   sp.sched_priority = newpri;
  2662   if (pthread_setschedparam(self, policy, &sp) != 0)
  2663     return OS_ERR;
  2665   return OS_OK;
  2666 #else
  2667   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2668   return (ret == 0) ? OS_OK : OS_ERR;
  2669 #endif
  2672 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
  2673   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
  2674     *priority_ptr = java_to_os_priority[NormPriority];
  2675     return OS_OK;
  2678   errno = 0;
  2679 #if defined(__OpenBSD__) || defined(__FreeBSD__)
  2680   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
  2681 #elif defined(__APPLE__) || defined(__NetBSD__)
  2682   int policy;
  2683   struct sched_param sp;
  2685   pthread_getschedparam(pthread_self(), &policy, &sp);
  2686   *priority_ptr = sp.sched_priority;
  2687 #else
  2688   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
  2689 #endif
  2690   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
  2693 // Hint to the underlying OS that a task switch would not be good.
  2694 // Void return because it's a hint and can fail.
  2695 void os::hint_no_preempt() {}
  2697 ////////////////////////////////////////////////////////////////////////////////
  2698 // suspend/resume support
  2700 //  the low-level signal-based suspend/resume support is a remnant from the
  2701 //  old VM-suspension that used to be for java-suspension, safepoints etc,
  2702 //  within hotspot. Now there is a single use-case for this:
  2703 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
  2704 //      that runs in the watcher thread.
  2705 //  The remaining code is greatly simplified from the more general suspension
  2706 //  code that used to be used.
  2707 //
  2708 //  The protocol is quite simple:
  2709 //  - suspend:
  2710 //      - sends a signal to the target thread
  2711 //      - polls the suspend state of the osthread using a yield loop
  2712 //      - target thread signal handler (SR_handler) sets suspend state
  2713 //        and blocks in sigsuspend until continued
  2714 //  - resume:
  2715 //      - sets target osthread state to continue
  2716 //      - sends signal to end the sigsuspend loop in the SR_handler
  2717 //
  2718 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2719 //
  2721 static void resume_clear_context(OSThread *osthread) {
  2722   osthread->set_ucontext(NULL);
  2723   osthread->set_siginfo(NULL);
  2726 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2727   osthread->set_ucontext(context);
  2728   osthread->set_siginfo(siginfo);
  2731 //
  2732 // Handler function invoked when a thread's execution is suspended or
  2733 // resumed. We have to be careful that only async-safe functions are
  2734 // called here (Note: most pthread functions are not async safe and
  2735 // should be avoided.)
  2736 //
  2737 // Note: sigwait() is a more natural fit than sigsuspend() from an
  2738 // interface point of view, but sigwait() prevents the signal hander
  2739 // from being run. libpthread would get very confused by not having
  2740 // its signal handlers run and prevents sigwait()'s use with the
  2741 // mutex granting granting signal.
  2742 //
  2743 // Currently only ever called on the VMThread or JavaThread
  2744 //
  2745 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
  2746   // Save and restore errno to avoid confusing native code with EINTR
  2747   // after sigsuspend.
  2748   int old_errno = errno;
  2750   Thread* thread = Thread::current();
  2751   OSThread* osthread = thread->osthread();
  2752   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
  2754   os::SuspendResume::State current = osthread->sr.state();
  2755   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
  2756     suspend_save_context(osthread, siginfo, context);
  2758     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
  2759     os::SuspendResume::State state = osthread->sr.suspended();
  2760     if (state == os::SuspendResume::SR_SUSPENDED) {
  2761       sigset_t suspend_set;  // signals for sigsuspend()
  2763       // get current set of blocked signals and unblock resume signal
  2764       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
  2765       sigdelset(&suspend_set, SR_signum);
  2767       sr_semaphore.signal();
  2768       // wait here until we are resumed
  2769       while (1) {
  2770         sigsuspend(&suspend_set);
  2772         os::SuspendResume::State result = osthread->sr.running();
  2773         if (result == os::SuspendResume::SR_RUNNING) {
  2774           sr_semaphore.signal();
  2775           break;
  2776         } else if (result != os::SuspendResume::SR_SUSPENDED) {
  2777           ShouldNotReachHere();
  2781     } else if (state == os::SuspendResume::SR_RUNNING) {
  2782       // request was cancelled, continue
  2783     } else {
  2784       ShouldNotReachHere();
  2787     resume_clear_context(osthread);
  2788   } else if (current == os::SuspendResume::SR_RUNNING) {
  2789     // request was cancelled, continue
  2790   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
  2791     // ignore
  2792   } else {
  2793     // ignore
  2796   errno = old_errno;
  2800 static int SR_initialize() {
  2801   struct sigaction act;
  2802   char *s;
  2803   /* Get signal number to use for suspend/resume */
  2804   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2805     int sig = ::strtol(s, 0, 10);
  2806     if (sig > 0 || sig < NSIG) {
  2807         SR_signum = sig;
  2811   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2812         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2814   sigemptyset(&SR_sigset);
  2815   sigaddset(&SR_sigset, SR_signum);
  2817   /* Set up signal handler for suspend/resume */
  2818   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2819   act.sa_handler = (void (*)(int)) SR_handler;
  2821   // SR_signum is blocked by default.
  2822   // 4528190 - We also need to block pthread restart signal (32 on all
  2823   // supported Bsd platforms). Note that BsdThreads need to block
  2824   // this signal for all threads to work properly. So we don't have
  2825   // to use hard-coded signal number when setting up the mask.
  2826   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
  2828   if (sigaction(SR_signum, &act, 0) == -1) {
  2829     return -1;
  2832   // Save signal flag
  2833   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
  2834   return 0;
  2837 static int sr_notify(OSThread* osthread) {
  2838   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2839   assert_status(status == 0, status, "pthread_kill");
  2840   return status;
  2843 // "Randomly" selected value for how long we want to spin
  2844 // before bailing out on suspending a thread, also how often
  2845 // we send a signal to a thread we want to resume
  2846 static const int RANDOMLY_LARGE_INTEGER = 1000000;
  2847 static const int RANDOMLY_LARGE_INTEGER2 = 100;
  2849 // returns true on success and false on error - really an error is fatal
  2850 // but this seems the normal response to library errors
  2851 static bool do_suspend(OSThread* osthread) {
  2852   assert(osthread->sr.is_running(), "thread should be running");
  2853   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
  2855   // mark as suspended and send signal
  2856   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
  2857     // failed to switch, state wasn't running?
  2858     ShouldNotReachHere();
  2859     return false;
  2862   if (sr_notify(osthread) != 0) {
  2863     ShouldNotReachHere();
  2866   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
  2867   while (true) {
  2868     if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  2869       break;
  2870     } else {
  2871       // timeout
  2872       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
  2873       if (cancelled == os::SuspendResume::SR_RUNNING) {
  2874         return false;
  2875       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
  2876         // make sure that we consume the signal on the semaphore as well
  2877         sr_semaphore.wait();
  2878         break;
  2879       } else {
  2880         ShouldNotReachHere();
  2881         return false;
  2886   guarantee(osthread->sr.is_suspended(), "Must be suspended");
  2887   return true;
  2890 static void do_resume(OSThread* osthread) {
  2891   assert(osthread->sr.is_suspended(), "thread should be suspended");
  2892   assert(!sr_semaphore.trywait(), "invalid semaphore state");
  2894   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
  2895     // failed to switch to WAKEUP_REQUEST
  2896     ShouldNotReachHere();
  2897     return;
  2900   while (true) {
  2901     if (sr_notify(osthread) == 0) {
  2902       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  2903         if (osthread->sr.is_running()) {
  2904           return;
  2907     } else {
  2908       ShouldNotReachHere();
  2912   guarantee(osthread->sr.is_running(), "Must be running!");
  2915 ////////////////////////////////////////////////////////////////////////////////
  2916 // interrupt support
  2918 void os::interrupt(Thread* thread) {
  2919   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2920     "possibility of dangling Thread pointer");
  2922   OSThread* osthread = thread->osthread();
  2924   if (!osthread->interrupted()) {
  2925     osthread->set_interrupted(true);
  2926     // More than one thread can get here with the same value of osthread,
  2927     // resulting in multiple notifications.  We do, however, want the store
  2928     // to interrupted() to be visible to other threads before we execute unpark().
  2929     OrderAccess::fence();
  2930     ParkEvent * const slp = thread->_SleepEvent ;
  2931     if (slp != NULL) slp->unpark() ;
  2934   // For JSR166. Unpark even if interrupt status already was set
  2935   if (thread->is_Java_thread())
  2936     ((JavaThread*)thread)->parker()->unpark();
  2938   ParkEvent * ev = thread->_ParkEvent ;
  2939   if (ev != NULL) ev->unpark() ;
  2943 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  2944   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2945     "possibility of dangling Thread pointer");
  2947   OSThread* osthread = thread->osthread();
  2949   bool interrupted = osthread->interrupted();
  2951   if (interrupted && clear_interrupted) {
  2952     osthread->set_interrupted(false);
  2953     // consider thread->_SleepEvent->reset() ... optional optimization
  2956   return interrupted;
  2959 ///////////////////////////////////////////////////////////////////////////////////
  2960 // signal handling (except suspend/resume)
  2962 // This routine may be used by user applications as a "hook" to catch signals.
  2963 // The user-defined signal handler must pass unrecognized signals to this
  2964 // routine, and if it returns true (non-zero), then the signal handler must
  2965 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
  2966 // routine will never retun false (zero), but instead will execute a VM panic
  2967 // routine kill the process.
  2968 //
  2969 // If this routine returns false, it is OK to call it again.  This allows
  2970 // the user-defined signal handler to perform checks either before or after
  2971 // the VM performs its own checks.  Naturally, the user code would be making
  2972 // a serious error if it tried to handle an exception (such as a null check
  2973 // or breakpoint) that the VM was generating for its own correct operation.
  2974 //
  2975 // This routine may recognize any of the following kinds of signals:
  2976 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
  2977 // It should be consulted by handlers for any of those signals.
  2978 //
  2979 // The caller of this routine must pass in the three arguments supplied
  2980 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
  2981 // field of the structure passed to sigaction().  This routine assumes that
  2982 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2983 //
  2984 // Note that the VM will print warnings if it detects conflicting signal
  2985 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2986 //
  2987 extern "C" JNIEXPORT int
  2988 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2989                         void* ucontext, int abort_if_unrecognized);
  2991 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2992   assert(info != NULL && uc != NULL, "it must be old kernel");
  2993   int orig_errno = errno;  // Preserve errno value over signal handler.
  2994   JVM_handle_bsd_signal(sig, info, uc, true);
  2995   errno = orig_errno;
  2999 // This boolean allows users to forward their own non-matching signals
  3000 // to JVM_handle_bsd_signal, harmlessly.
  3001 bool os::Bsd::signal_handlers_are_installed = false;
  3003 // For signal-chaining
  3004 struct sigaction os::Bsd::sigact[MAXSIGNUM];
  3005 unsigned int os::Bsd::sigs = 0;
  3006 bool os::Bsd::libjsig_is_loaded = false;
  3007 typedef struct sigaction *(*get_signal_t)(int);
  3008 get_signal_t os::Bsd::get_signal_action = NULL;
  3010 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
  3011   struct sigaction *actp = NULL;
  3013   if (libjsig_is_loaded) {
  3014     // Retrieve the old signal handler from libjsig
  3015     actp = (*get_signal_action)(sig);
  3017   if (actp == NULL) {
  3018     // Retrieve the preinstalled signal handler from jvm
  3019     actp = get_preinstalled_handler(sig);
  3022   return actp;
  3025 static bool call_chained_handler(struct sigaction *actp, int sig,
  3026                                  siginfo_t *siginfo, void *context) {
  3027   // Call the old signal handler
  3028   if (actp->sa_handler == SIG_DFL) {
  3029     // It's more reasonable to let jvm treat it as an unexpected exception
  3030     // instead of taking the default action.
  3031     return false;
  3032   } else if (actp->sa_handler != SIG_IGN) {
  3033     if ((actp->sa_flags & SA_NODEFER) == 0) {
  3034       // automaticlly block the signal
  3035       sigaddset(&(actp->sa_mask), sig);
  3038     sa_handler_t hand;
  3039     sa_sigaction_t sa;
  3040     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
  3041     // retrieve the chained handler
  3042     if (siginfo_flag_set) {
  3043       sa = actp->sa_sigaction;
  3044     } else {
  3045       hand = actp->sa_handler;
  3048     if ((actp->sa_flags & SA_RESETHAND) != 0) {
  3049       actp->sa_handler = SIG_DFL;
  3052     // try to honor the signal mask
  3053     sigset_t oset;
  3054     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
  3056     // call into the chained handler
  3057     if (siginfo_flag_set) {
  3058       (*sa)(sig, siginfo, context);
  3059     } else {
  3060       (*hand)(sig);
  3063     // restore the signal mask
  3064     pthread_sigmask(SIG_SETMASK, &oset, 0);
  3066   // Tell jvm's signal handler the signal is taken care of.
  3067   return true;
  3070 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
  3071   bool chained = false;
  3072   // signal-chaining
  3073   if (UseSignalChaining) {
  3074     struct sigaction *actp = get_chained_signal_action(sig);
  3075     if (actp != NULL) {
  3076       chained = call_chained_handler(actp, sig, siginfo, context);
  3079   return chained;
  3082 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
  3083   if ((( (unsigned int)1 << sig ) & sigs) != 0) {
  3084     return &sigact[sig];
  3086   return NULL;
  3089 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
  3090   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3091   sigact[sig] = oldAct;
  3092   sigs |= (unsigned int)1 << sig;
  3095 // for diagnostic
  3096 int os::Bsd::sigflags[MAXSIGNUM];
  3098 int os::Bsd::get_our_sigflags(int sig) {
  3099   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3100   return sigflags[sig];
  3103 void os::Bsd::set_our_sigflags(int sig, int flags) {
  3104   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3105   sigflags[sig] = flags;
  3108 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
  3109   // Check for overwrite.
  3110   struct sigaction oldAct;
  3111   sigaction(sig, (struct sigaction*)NULL, &oldAct);
  3113   void* oldhand = oldAct.sa_sigaction
  3114                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
  3115                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
  3116   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
  3117       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
  3118       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
  3119     if (AllowUserSignalHandlers || !set_installed) {
  3120       // Do not overwrite; user takes responsibility to forward to us.
  3121       return;
  3122     } else if (UseSignalChaining) {
  3123       // save the old handler in jvm
  3124       save_preinstalled_handler(sig, oldAct);
  3125       // libjsig also interposes the sigaction() call below and saves the
  3126       // old sigaction on it own.
  3127     } else {
  3128       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
  3129                     "%#lx for signal %d.", (long)oldhand, sig));
  3133   struct sigaction sigAct;
  3134   sigfillset(&(sigAct.sa_mask));
  3135   sigAct.sa_handler = SIG_DFL;
  3136   if (!set_installed) {
  3137     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3138   } else {
  3139     sigAct.sa_sigaction = signalHandler;
  3140     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3142 #if __APPLE__
  3143   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
  3144   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
  3145   // if the signal handler declares it will handle it on alternate stack.
  3146   // Notice we only declare we will handle it on alt stack, but we are not
  3147   // actually going to use real alt stack - this is just a workaround.
  3148   // Please see ux_exception.c, method catch_mach_exception_raise for details
  3149   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
  3150   if (sig == SIGSEGV) {
  3151     sigAct.sa_flags |= SA_ONSTACK;
  3153 #endif
  3155   // Save flags, which are set by ours
  3156   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3157   sigflags[sig] = sigAct.sa_flags;
  3159   int ret = sigaction(sig, &sigAct, &oldAct);
  3160   assert(ret == 0, "check");
  3162   void* oldhand2  = oldAct.sa_sigaction
  3163                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
  3164                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
  3165   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
  3168 // install signal handlers for signals that HotSpot needs to
  3169 // handle in order to support Java-level exception handling.
  3171 void os::Bsd::install_signal_handlers() {
  3172   if (!signal_handlers_are_installed) {
  3173     signal_handlers_are_installed = true;
  3175     // signal-chaining
  3176     typedef void (*signal_setting_t)();
  3177     signal_setting_t begin_signal_setting = NULL;
  3178     signal_setting_t end_signal_setting = NULL;
  3179     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3180                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3181     if (begin_signal_setting != NULL) {
  3182       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3183                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3184       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3185                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3186       libjsig_is_loaded = true;
  3187       assert(UseSignalChaining, "should enable signal-chaining");
  3189     if (libjsig_is_loaded) {
  3190       // Tell libjsig jvm is setting signal handlers
  3191       (*begin_signal_setting)();
  3194     set_signal_handler(SIGSEGV, true);
  3195     set_signal_handler(SIGPIPE, true);
  3196     set_signal_handler(SIGBUS, true);
  3197     set_signal_handler(SIGILL, true);
  3198     set_signal_handler(SIGFPE, true);
  3199     set_signal_handler(SIGXFSZ, true);
  3201 #if defined(__APPLE__)
  3202     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
  3203     // signals caught and handled by the JVM. To work around this, we reset the mach task
  3204     // signal handler that's placed on our process by CrashReporter. This disables
  3205     // CrashReporter-based reporting.
  3206     //
  3207     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
  3208     // on caught fatal signals.
  3209     //
  3210     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3211     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3212     // exception handling, while leaving the standard BSD signal handlers functional.
  3213     kern_return_t kr;
  3214     kr = task_set_exception_ports(mach_task_self(),
  3215         EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3216         MACH_PORT_NULL,
  3217         EXCEPTION_STATE_IDENTITY,
  3218         MACHINE_THREAD_STATE);
  3220     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3221 #endif
  3223     if (libjsig_is_loaded) {
  3224       // Tell libjsig jvm finishes setting signal handlers
  3225       (*end_signal_setting)();
  3228     // We don't activate signal checker if libjsig is in place, we trust ourselves
  3229     // and if UserSignalHandler is installed all bets are off
  3230     if (CheckJNICalls) {
  3231       if (libjsig_is_loaded) {
  3232         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
  3233         check_signals = false;
  3235       if (AllowUserSignalHandlers) {
  3236         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
  3237         check_signals = false;
  3244 /////
  3245 // glibc on Bsd platform uses non-documented flag
  3246 // to indicate, that some special sort of signal
  3247 // trampoline is used.
  3248 // We will never set this flag, and we should
  3249 // ignore this flag in our diagnostic
  3250 #ifdef SIGNIFICANT_SIGNAL_MASK
  3251 #undef SIGNIFICANT_SIGNAL_MASK
  3252 #endif
  3253 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3255 static const char* get_signal_handler_name(address handler,
  3256                                            char* buf, int buflen) {
  3257   int offset;
  3258   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
  3259   if (found) {
  3260     // skip directory names
  3261     const char *p1, *p2;
  3262     p1 = buf;
  3263     size_t len = strlen(os::file_separator());
  3264     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
  3265     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
  3266   } else {
  3267     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
  3269   return buf;
  3272 static void print_signal_handler(outputStream* st, int sig,
  3273                                  char* buf, size_t buflen) {
  3274   struct sigaction sa;
  3276   sigaction(sig, NULL, &sa);
  3278   // See comment for SIGNIFICANT_SIGNAL_MASK define
  3279   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3281   st->print("%s: ", os::exception_name(sig, buf, buflen));
  3283   address handler = (sa.sa_flags & SA_SIGINFO)
  3284     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
  3285     : CAST_FROM_FN_PTR(address, sa.sa_handler);
  3287   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
  3288     st->print("SIG_DFL");
  3289   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
  3290     st->print("SIG_IGN");
  3291   } else {
  3292     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
  3295   st->print(", sa_mask[0]=");
  3296   os::Posix::print_signal_set_short(st, &sa.sa_mask);
  3298   address rh = VMError::get_resetted_sighandler(sig);
  3299   // May be, handler was resetted by VMError?
  3300   if(rh != NULL) {
  3301     handler = rh;
  3302     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
  3305   st->print(", sa_flags=");
  3306   os::Posix::print_sa_flags(st, sa.sa_flags);
  3308   // Check: is it our handler?
  3309   if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3310      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3311     // It is our signal handler
  3312     // check for flags, reset system-used one!
  3313     if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3314       st->print(
  3315                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3316                 os::Bsd::get_our_sigflags(sig));
  3319   st->cr();
  3323 #define DO_SIGNAL_CHECK(sig) \
  3324   if (!sigismember(&check_signal_done, sig)) \
  3325     os::Bsd::check_signal_handler(sig)
  3327 // This method is a periodic task to check for misbehaving JNI applications
  3328 // under CheckJNI, we can add any periodic checks here
  3330 void os::run_periodic_checks() {
  3332   if (check_signals == false) return;
  3334   // SEGV and BUS if overridden could potentially prevent
  3335   // generation of hs*.log in the event of a crash, debugging
  3336   // such a case can be very challenging, so we absolutely
  3337   // check the following for a good measure:
  3338   DO_SIGNAL_CHECK(SIGSEGV);
  3339   DO_SIGNAL_CHECK(SIGILL);
  3340   DO_SIGNAL_CHECK(SIGFPE);
  3341   DO_SIGNAL_CHECK(SIGBUS);
  3342   DO_SIGNAL_CHECK(SIGPIPE);
  3343   DO_SIGNAL_CHECK(SIGXFSZ);
  3346   // ReduceSignalUsage allows the user to override these handlers
  3347   // see comments at the very top and jvm_solaris.h
  3348   if (!ReduceSignalUsage) {
  3349     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
  3350     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
  3351     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
  3352     DO_SIGNAL_CHECK(BREAK_SIGNAL);
  3355   DO_SIGNAL_CHECK(SR_signum);
  3356   DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
  3359 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
  3361 static os_sigaction_t os_sigaction = NULL;
  3363 void os::Bsd::check_signal_handler(int sig) {
  3364   char buf[O_BUFLEN];
  3365   address jvmHandler = NULL;
  3368   struct sigaction act;
  3369   if (os_sigaction == NULL) {
  3370     // only trust the default sigaction, in case it has been interposed
  3371     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
  3372     if (os_sigaction == NULL) return;
  3375   os_sigaction(sig, (struct sigaction*)NULL, &act);
  3378   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3380   address thisHandler = (act.sa_flags & SA_SIGINFO)
  3381     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
  3382     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
  3385   switch(sig) {
  3386   case SIGSEGV:
  3387   case SIGBUS:
  3388   case SIGFPE:
  3389   case SIGPIPE:
  3390   case SIGILL:
  3391   case SIGXFSZ:
  3392     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
  3393     break;
  3395   case SHUTDOWN1_SIGNAL:
  3396   case SHUTDOWN2_SIGNAL:
  3397   case SHUTDOWN3_SIGNAL:
  3398   case BREAK_SIGNAL:
  3399     jvmHandler = (address)user_handler();
  3400     break;
  3402   case INTERRUPT_SIGNAL:
  3403     jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
  3404     break;
  3406   default:
  3407     if (sig == SR_signum) {
  3408       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
  3409     } else {
  3410       return;
  3412     break;
  3415   if (thisHandler != jvmHandler) {
  3416     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
  3417     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
  3418     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
  3419     // No need to check this sig any longer
  3420     sigaddset(&check_signal_done, sig);
  3421   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3422     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
  3423     tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
  3424     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
  3425     // No need to check this sig any longer
  3426     sigaddset(&check_signal_done, sig);
  3429   // Dump all the signal
  3430   if (sigismember(&check_signal_done, sig)) {
  3431     print_signal_handlers(tty, buf, O_BUFLEN);
  3435 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3437 extern bool signal_name(int signo, char* buf, size_t len);
  3439 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3440   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3441     // signal
  3442     if (!signal_name(exception_code, buf, size)) {
  3443       jio_snprintf(buf, size, "SIG%d", exception_code);
  3445     return buf;
  3446   } else {
  3447     return NULL;
  3451 // this is called _before_ the most of global arguments have been parsed
  3452 void os::init(void) {
  3453   char dummy;   /* used to get a guess on initial stack address */
  3454 //  first_hrtime = gethrtime();
  3456   // With BsdThreads the JavaMain thread pid (primordial thread)
  3457   // is different than the pid of the java launcher thread.
  3458   // So, on Bsd, the launcher thread pid is passed to the VM
  3459   // via the sun.java.launcher.pid property.
  3460   // Use this property instead of getpid() if it was correctly passed.
  3461   // See bug 6351349.
  3462   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
  3464   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
  3466   clock_tics_per_sec = CLK_TCK;
  3468   init_random(1234567);
  3470   ThreadCritical::initialize();
  3472   Bsd::set_page_size(getpagesize());
  3473   if (Bsd::page_size() == -1) {
  3474     fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
  3475                   strerror(errno)));
  3477   init_page_sizes((size_t) Bsd::page_size());
  3479   Bsd::initialize_system_info();
  3481   // main_thread points to the aboriginal thread
  3482   Bsd::_main_thread = pthread_self();
  3484   Bsd::clock_init();
  3485   initial_time_count = os::elapsed_counter();
  3487 #ifdef __APPLE__
  3488   // XXXDARWIN
  3489   // Work around the unaligned VM callbacks in hotspot's
  3490   // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
  3491   // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
  3492   // alignment when doing symbol lookup. To work around this, we force early
  3493   // binding of all symbols now, thus binding when alignment is known-good.
  3494   _dyld_bind_fully_image_containing_address((const void *) &os::init);
  3495 #endif
  3498 // To install functions for atexit system call
  3499 extern "C" {
  3500   static void perfMemory_exit_helper() {
  3501     perfMemory_exit();
  3505 // this is called _after_ the global arguments have been parsed
  3506 jint os::init_2(void)
  3508   // Allocate a single page and mark it as readable for safepoint polling
  3509   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3510   guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
  3512   os::set_polling_page( polling_page );
  3514 #ifndef PRODUCT
  3515   if(Verbose && PrintMiscellaneous)
  3516     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3517 #endif
  3519   if (!UseMembar) {
  3520     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3521     guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3522     os::set_memory_serialize_page( mem_serialize_page );
  3524 #ifndef PRODUCT
  3525     if(Verbose && PrintMiscellaneous)
  3526       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3527 #endif
  3530   os::large_page_init();
  3532   // initialize suspend/resume support - must do this before signal_sets_init()
  3533   if (SR_initialize() != 0) {
  3534     perror("SR_initialize failed");
  3535     return JNI_ERR;
  3538   Bsd::signal_sets_init();
  3539   Bsd::install_signal_handlers();
  3541   // Check minimum allowable stack size for thread creation and to initialize
  3542   // the java system classes, including StackOverflowError - depends on page
  3543   // size.  Add a page for compiler2 recursion in main thread.
  3544   // Add in 2*BytesPerWord times page size to account for VM stack during
  3545   // class initialization depending on 32 or 64 bit VM.
  3546   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3547             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3548                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3550   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3551   if (threadStackSizeInBytes != 0 &&
  3552       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3553         tty->print_cr("\nThe stack size specified is too small, "
  3554                       "Specify at least %dk",
  3555                       os::Bsd::min_stack_allowed/ K);
  3556         return JNI_ERR;
  3559   // Make the stack size a multiple of the page size so that
  3560   // the yellow/red zones can be guarded.
  3561   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3562         vm_page_size()));
  3564   if (MaxFDLimit) {
  3565     // set the number of file descriptors to max. print out error
  3566     // if getrlimit/setrlimit fails but continue regardless.
  3567     struct rlimit nbr_files;
  3568     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3569     if (status != 0) {
  3570       if (PrintMiscellaneous && (Verbose || WizardMode))
  3571         perror("os::init_2 getrlimit failed");
  3572     } else {
  3573       nbr_files.rlim_cur = nbr_files.rlim_max;
  3575 #ifdef __APPLE__
  3576       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3577       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
  3578       // be used instead
  3579       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3580 #endif
  3582       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3583       if (status != 0) {
  3584         if (PrintMiscellaneous && (Verbose || WizardMode))
  3585           perror("os::init_2 setrlimit failed");
  3590   // at-exit methods are called in the reverse order of their registration.
  3591   // atexit functions are called on return from main or as a result of a
  3592   // call to exit(3C). There can be only 32 of these functions registered
  3593   // and atexit() does not set errno.
  3595   if (PerfAllowAtExitRegistration) {
  3596     // only register atexit functions if PerfAllowAtExitRegistration is set.
  3597     // atexit functions can be delayed until process exit time, which
  3598     // can be problematic for embedded VM situations. Embedded VMs should
  3599     // call DestroyJavaVM() to assure that VM resources are released.
  3601     // note: perfMemory_exit_helper atexit function may be removed in
  3602     // the future if the appropriate cleanup code can be added to the
  3603     // VM_Exit VMOperation's doit method.
  3604     if (atexit(perfMemory_exit_helper) != 0) {
  3605       warning("os::init2 atexit(perfMemory_exit_helper) failed");
  3609   // initialize thread priority policy
  3610   prio_init();
  3612 #ifdef __APPLE__
  3613   // dynamically link to objective c gc registration
  3614   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
  3615   if (handleLibObjc != NULL) {
  3616     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
  3618 #endif
  3620   return JNI_OK;
  3623 // this is called at the end of vm_initialization
  3624 void os::init_3(void) { }
  3626 // Mark the polling page as unreadable
  3627 void os::make_polling_page_unreadable(void) {
  3628   if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
  3629     fatal("Could not disable polling page");
  3630 };
  3632 // Mark the polling page as readable
  3633 void os::make_polling_page_readable(void) {
  3634   if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3635     fatal("Could not enable polling page");
  3637 };
  3639 int os::active_processor_count() {
  3640   return _processor_count;
  3643 void os::set_native_thread_name(const char *name) {
  3644 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  3645   // This is only supported in Snow Leopard and beyond
  3646   if (name != NULL) {
  3647     // Add a "Java: " prefix to the name
  3648     char buf[MAXTHREADNAMESIZE];
  3649     snprintf(buf, sizeof(buf), "Java: %s", name);
  3650     pthread_setname_np(buf);
  3652 #endif
  3655 bool os::distribute_processes(uint length, uint* distribution) {
  3656   // Not yet implemented.
  3657   return false;
  3660 bool os::bind_to_processor(uint processor_id) {
  3661   // Not yet implemented.
  3662   return false;
  3665 void os::SuspendedThreadTask::internal_do_task() {
  3666   if (do_suspend(_thread->osthread())) {
  3667     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
  3668     do_task(context);
  3669     do_resume(_thread->osthread());
  3673 ///
  3674 class PcFetcher : public os::SuspendedThreadTask {
  3675 public:
  3676   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
  3677   ExtendedPC result();
  3678 protected:
  3679   void do_task(const os::SuspendedThreadTaskContext& context);
  3680 private:
  3681   ExtendedPC _epc;
  3682 };
  3684 ExtendedPC PcFetcher::result() {
  3685   guarantee(is_done(), "task is not done yet.");
  3686   return _epc;
  3689 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
  3690   Thread* thread = context.thread();
  3691   OSThread* osthread = thread->osthread();
  3692   if (osthread->ucontext() != NULL) {
  3693     _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());
  3694   } else {
  3695     // NULL context is unexpected, double-check this is the VMThread
  3696     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
  3700 // Suspends the target using the signal mechanism and then grabs the PC before
  3701 // resuming the target. Used by the flat-profiler only
  3702 ExtendedPC os::get_thread_pc(Thread* thread) {
  3703   // Make sure that it is called by the watcher for the VMThread
  3704   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
  3705   assert(thread->is_VM_thread(), "Can only be called for VMThread");
  3707   PcFetcher fetcher(thread);
  3708   fetcher.run();
  3709   return fetcher.result();
  3712 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3714   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3717 ////////////////////////////////////////////////////////////////////////////////
  3718 // debug support
  3720 bool os::find(address addr, outputStream* st) {
  3721   Dl_info dlinfo;
  3722   memset(&dlinfo, 0, sizeof(dlinfo));
  3723   if (dladdr(addr, &dlinfo) != 0) {
  3724     st->print(PTR_FORMAT ": ", addr);
  3725     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
  3726       st->print("%s+%#x", dlinfo.dli_sname,
  3727                  addr - (intptr_t)dlinfo.dli_saddr);
  3728     } else if (dlinfo.dli_fbase != NULL) {
  3729       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3730     } else {
  3731       st->print("<absolute address>");
  3733     if (dlinfo.dli_fname != NULL) {
  3734       st->print(" in %s", dlinfo.dli_fname);
  3736     if (dlinfo.dli_fbase != NULL) {
  3737       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
  3739     st->cr();
  3741     if (Verbose) {
  3742       // decode some bytes around the PC
  3743       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
  3744       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
  3745       address       lowest = (address) dlinfo.dli_sname;
  3746       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3747       if (begin < lowest)  begin = lowest;
  3748       Dl_info dlinfo2;
  3749       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3750           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3751         end = (address) dlinfo2.dli_saddr;
  3752       Disassembler::decode(begin, end, st);
  3754     return true;
  3756   return false;
  3759 ////////////////////////////////////////////////////////////////////////////////
  3760 // misc
  3762 // This does not do anything on Bsd. This is basically a hook for being
  3763 // able to use structured exception handling (thread-local exception filters)
  3764 // on, e.g., Win32.
  3765 void
  3766 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3767                          JavaCallArguments* args, Thread* thread) {
  3768   f(value, method, args, thread);
  3771 void os::print_statistics() {
  3774 int os::message_box(const char* title, const char* message) {
  3775   int i;
  3776   fdStream err(defaultStream::error_fd());
  3777   for (i = 0; i < 78; i++) err.print_raw("=");
  3778   err.cr();
  3779   err.print_raw_cr(title);
  3780   for (i = 0; i < 78; i++) err.print_raw("-");
  3781   err.cr();
  3782   err.print_raw_cr(message);
  3783   for (i = 0; i < 78; i++) err.print_raw("=");
  3784   err.cr();
  3786   char buf[16];
  3787   // Prevent process from exiting upon "read error" without consuming all CPU
  3788   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
  3790   return buf[0] == 'y' || buf[0] == 'Y';
  3793 int os::stat(const char *path, struct stat *sbuf) {
  3794   char pathbuf[MAX_PATH];
  3795   if (strlen(path) > MAX_PATH - 1) {
  3796     errno = ENAMETOOLONG;
  3797     return -1;
  3799   os::native_path(strcpy(pathbuf, path));
  3800   return ::stat(pathbuf, sbuf);
  3803 bool os::check_heap(bool force) {
  3804   return true;
  3807 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
  3808   return ::vsnprintf(buf, count, format, args);
  3811 // Is a (classpath) directory empty?
  3812 bool os::dir_is_empty(const char* path) {
  3813   DIR *dir = NULL;
  3814   struct dirent *ptr;
  3816   dir = opendir(path);
  3817   if (dir == NULL) return true;
  3819   /* Scan the directory */
  3820   bool result = true;
  3821   char buf[sizeof(struct dirent) + MAX_PATH];
  3822   while (result && (ptr = ::readdir(dir)) != NULL) {
  3823     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3824       result = false;
  3827   closedir(dir);
  3828   return result;
  3831 // This code originates from JDK's sysOpen and open64_w
  3832 // from src/solaris/hpi/src/system_md.c
  3834 #ifndef O_DELETE
  3835 #define O_DELETE 0x10000
  3836 #endif
  3838 // Open a file. Unlink the file immediately after open returns
  3839 // if the specified oflag has the O_DELETE flag set.
  3840 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3842 int os::open(const char *path, int oflag, int mode) {
  3844   if (strlen(path) > MAX_PATH - 1) {
  3845     errno = ENAMETOOLONG;
  3846     return -1;
  3848   int fd;
  3849   int o_delete = (oflag & O_DELETE);
  3850   oflag = oflag & ~O_DELETE;
  3852   fd = ::open(path, oflag, mode);
  3853   if (fd == -1) return -1;
  3855   //If the open succeeded, the file might still be a directory
  3857     struct stat buf;
  3858     int ret = ::fstat(fd, &buf);
  3859     int st_mode = buf.st_mode;
  3861     if (ret != -1) {
  3862       if ((st_mode & S_IFMT) == S_IFDIR) {
  3863         errno = EISDIR;
  3864         ::close(fd);
  3865         return -1;
  3867     } else {
  3868       ::close(fd);
  3869       return -1;
  3873     /*
  3874      * All file descriptors that are opened in the JVM and not
  3875      * specifically destined for a subprocess should have the
  3876      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3877      * party native code might fork and exec without closing all
  3878      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3879      * UNIXProcess.c), and this in turn might:
  3881      * - cause end-of-file to fail to be detected on some file
  3882      *   descriptors, resulting in mysterious hangs, or
  3884      * - might cause an fopen in the subprocess to fail on a system
  3885      *   suffering from bug 1085341.
  3887      * (Yes, the default setting of the close-on-exec flag is a Unix
  3888      * design flaw)
  3890      * See:
  3891      * 1085341: 32-bit stdio routines should support file descriptors >255
  3892      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3893      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3894      */
  3895 #ifdef FD_CLOEXEC
  3897         int flags = ::fcntl(fd, F_GETFD);
  3898         if (flags != -1)
  3899             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3901 #endif
  3903   if (o_delete != 0) {
  3904     ::unlink(path);
  3906   return fd;
  3910 // create binary file, rewriting existing file if required
  3911 int os::create_binary_file(const char* path, bool rewrite_existing) {
  3912   int oflags = O_WRONLY | O_CREAT;
  3913   if (!rewrite_existing) {
  3914     oflags |= O_EXCL;
  3916   return ::open(path, oflags, S_IREAD | S_IWRITE);
  3919 // return current position of file pointer
  3920 jlong os::current_file_offset(int fd) {
  3921   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
  3924 // move file pointer to the specified offset
  3925 jlong os::seek_to_file_offset(int fd, jlong offset) {
  3926   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
  3929 // This code originates from JDK's sysAvailable
  3930 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
  3932 int os::available(int fd, jlong *bytes) {
  3933   jlong cur, end;
  3934   int mode;
  3935   struct stat buf;
  3937   if (::fstat(fd, &buf) >= 0) {
  3938     mode = buf.st_mode;
  3939     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3940       /*
  3941       * XXX: is the following call interruptible? If so, this might
  3942       * need to go through the INTERRUPT_IO() wrapper as for other
  3943       * blocking, interruptible calls in this file.
  3944       */
  3945       int n;
  3946       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3947         *bytes = n;
  3948         return 1;
  3952   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
  3953     return 0;
  3954   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
  3955     return 0;
  3956   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
  3957     return 0;
  3959   *bytes = end - cur;
  3960   return 1;
  3963 int os::socket_available(int fd, jint *pbytes) {
  3964    if (fd < 0)
  3965      return OS_OK;
  3967    int ret;
  3969    RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3971    //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  3972    // is expected to return 0 on failure and 1 on success to the jdk.
  3974    return (ret == OS_ERR) ? 0 : 1;
  3977 // Map a block of memory.
  3978 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  3979                      char *addr, size_t bytes, bool read_only,
  3980                      bool allow_exec) {
  3981   int prot;
  3982   int flags;
  3984   if (read_only) {
  3985     prot = PROT_READ;
  3986     flags = MAP_SHARED;
  3987   } else {
  3988     prot = PROT_READ | PROT_WRITE;
  3989     flags = MAP_PRIVATE;
  3992   if (allow_exec) {
  3993     prot |= PROT_EXEC;
  3996   if (addr != NULL) {
  3997     flags |= MAP_FIXED;
  4000   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
  4001                                      fd, file_offset);
  4002   if (mapped_address == MAP_FAILED) {
  4003     return NULL;
  4005   return mapped_address;
  4009 // Remap a block of memory.
  4010 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  4011                        char *addr, size_t bytes, bool read_only,
  4012                        bool allow_exec) {
  4013   // same as map_memory() on this OS
  4014   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  4015                         allow_exec);
  4019 // Unmap a block of memory.
  4020 bool os::pd_unmap_memory(char* addr, size_t bytes) {
  4021   return munmap(addr, bytes) == 0;
  4024 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  4025 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  4026 // of a thread.
  4027 //
  4028 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
  4029 // the fast estimate available on the platform.
  4031 jlong os::current_thread_cpu_time() {
  4032 #ifdef __APPLE__
  4033   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
  4034 #else
  4035   Unimplemented();
  4036   return 0;
  4037 #endif
  4040 jlong os::thread_cpu_time(Thread* thread) {
  4041 #ifdef __APPLE__
  4042   return os::thread_cpu_time(thread, true /* user + sys */);
  4043 #else
  4044   Unimplemented();
  4045   return 0;
  4046 #endif
  4049 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  4050 #ifdef __APPLE__
  4051   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  4052 #else
  4053   Unimplemented();
  4054   return 0;
  4055 #endif
  4058 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
  4059 #ifdef __APPLE__
  4060   struct thread_basic_info tinfo;
  4061   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
  4062   kern_return_t kr;
  4063   thread_t mach_thread;
  4065   mach_thread = thread->osthread()->thread_id();
  4066   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4067   if (kr != KERN_SUCCESS)
  4068     return -1;
  4070   if (user_sys_cpu_time) {
  4071     jlong nanos;
  4072     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4073     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4074     return nanos;
  4075   } else {
  4076     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
  4078 #else
  4079   Unimplemented();
  4080   return 0;
  4081 #endif
  4085 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  4086   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  4087   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  4088   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  4089   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  4092 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  4093   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  4094   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  4095   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  4096   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  4099 bool os::is_thread_cpu_time_supported() {
  4100 #ifdef __APPLE__
  4101   return true;
  4102 #else
  4103   return false;
  4104 #endif
  4107 // System loadavg support.  Returns -1 if load average cannot be obtained.
  4108 // Bsd doesn't yet have a (official) notion of processor sets,
  4109 // so just return the system wide load average.
  4110 int os::loadavg(double loadavg[], int nelem) {
  4111   return ::getloadavg(loadavg, nelem);
  4114 void os::pause() {
  4115   char filename[MAX_PATH];
  4116   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  4117     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  4118   } else {
  4119     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  4122   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4123   if (fd != -1) {
  4124     struct stat buf;
  4125     ::close(fd);
  4126     while (::stat(filename, &buf) == 0) {
  4127       (void)::poll(NULL, 0, 100);
  4129   } else {
  4130     jio_fprintf(stderr,
  4131       "Could not open pause file '%s', continuing immediately.\n", filename);
  4136 // Refer to the comments in os_solaris.cpp park-unpark.
  4137 //
  4138 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
  4139 // hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
  4140 // For specifics regarding the bug see GLIBC BUGID 261237 :
  4141 //    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
  4142 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
  4143 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
  4144 // is used.  (The simple C test-case provided in the GLIBC bug report manifests the
  4145 // hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
  4146 // and monitorenter when we're using 1-0 locking.  All those operations may result in
  4147 // calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
  4148 // of libpthread avoids the problem, but isn't practical.
  4149 //
  4150 // Possible remedies:
  4151 //
  4152 // 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
  4153 //      This is palliative and probabilistic, however.  If the thread is preempted
  4154 //      between the call to compute_abstime() and pthread_cond_timedwait(), more
  4155 //      than the minimum period may have passed, and the abstime may be stale (in the
  4156 //      past) resultin in a hang.   Using this technique reduces the odds of a hang
  4157 //      but the JVM is still vulnerable, particularly on heavily loaded systems.
  4158 //
  4159 // 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
  4160 //      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
  4161 //      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
  4162 //      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
  4163 //      thread.
  4164 //
  4165 // 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
  4166 //      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
  4167 //      a timeout request to the chron thread and then blocking via pthread_cond_wait().
  4168 //      This also works well.  In fact it avoids kernel-level scalability impediments
  4169 //      on certain platforms that don't handle lots of active pthread_cond_timedwait()
  4170 //      timers in a graceful fashion.
  4171 //
  4172 // 4.   When the abstime value is in the past it appears that control returns
  4173 //      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
  4174 //      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
  4175 //      can avoid the problem by reinitializing the condvar -- by cond_destroy()
  4176 //      followed by cond_init() -- after all calls to pthread_cond_timedwait().
  4177 //      It may be possible to avoid reinitialization by checking the return
  4178 //      value from pthread_cond_timedwait().  In addition to reinitializing the
  4179 //      condvar we must establish the invariant that cond_signal() is only called
  4180 //      within critical sections protected by the adjunct mutex.  This prevents
  4181 //      cond_signal() from "seeing" a condvar that's in the midst of being
  4182 //      reinitialized or that is corrupt.  Sadly, this invariant obviates the
  4183 //      desirable signal-after-unlock optimization that avoids futile context switching.
  4184 //
  4185 //      I'm also concerned that some versions of NTPL might allocate an auxilliary
  4186 //      structure when a condvar is used or initialized.  cond_destroy()  would
  4187 //      release the helper structure.  Our reinitialize-after-timedwait fix
  4188 //      put excessive stress on malloc/free and locks protecting the c-heap.
  4189 //
  4190 // We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
  4191 // It may be possible to refine (4) by checking the kernel and NTPL verisons
  4192 // and only enabling the work-around for vulnerable environments.
  4194 // utility to compute the abstime argument to timedwait:
  4195 // millis is the relative timeout time
  4196 // abstime will be the absolute timeout time
  4197 // TODO: replace compute_abstime() with unpackTime()
  4199 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4200   if (millis < 0)  millis = 0;
  4201   struct timeval now;
  4202   int status = gettimeofday(&now, NULL);
  4203   assert(status == 0, "gettimeofday");
  4204   jlong seconds = millis / 1000;
  4205   millis %= 1000;
  4206   if (seconds > 50000000) { // see man cond_timedwait(3T)
  4207     seconds = 50000000;
  4209   abstime->tv_sec = now.tv_sec  + seconds;
  4210   long       usec = now.tv_usec + millis * 1000;
  4211   if (usec >= 1000000) {
  4212     abstime->tv_sec += 1;
  4213     usec -= 1000000;
  4215   abstime->tv_nsec = usec * 1000;
  4216   return abstime;
  4220 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
  4221 // Conceptually TryPark() should be equivalent to park(0).
  4223 int os::PlatformEvent::TryPark() {
  4224   for (;;) {
  4225     const int v = _Event ;
  4226     guarantee ((v == 0) || (v == 1), "invariant") ;
  4227     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
  4231 void os::PlatformEvent::park() {       // AKA "down()"
  4232   // Invariant: Only the thread associated with the Event/PlatformEvent
  4233   // may call park().
  4234   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4235   int v ;
  4236   for (;;) {
  4237       v = _Event ;
  4238       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4240   guarantee (v >= 0, "invariant") ;
  4241   if (v == 0) {
  4242      // Do this the hard way by blocking ...
  4243      int status = pthread_mutex_lock(_mutex);
  4244      assert_status(status == 0, status, "mutex_lock");
  4245      guarantee (_nParked == 0, "invariant") ;
  4246      ++ _nParked ;
  4247      while (_Event < 0) {
  4248         status = pthread_cond_wait(_cond, _mutex);
  4249         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4250         // Treat this the same as if the wait was interrupted
  4251         if (status == ETIMEDOUT) { status = EINTR; }
  4252         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4254      -- _nParked ;
  4256     _Event = 0 ;
  4257      status = pthread_mutex_unlock(_mutex);
  4258      assert_status(status == 0, status, "mutex_unlock");
  4259     // Paranoia to ensure our locked and lock-free paths interact
  4260     // correctly with each other.
  4261     OrderAccess::fence();
  4263   guarantee (_Event >= 0, "invariant") ;
  4266 int os::PlatformEvent::park(jlong millis) {
  4267   guarantee (_nParked == 0, "invariant") ;
  4269   int v ;
  4270   for (;;) {
  4271       v = _Event ;
  4272       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4274   guarantee (v >= 0, "invariant") ;
  4275   if (v != 0) return OS_OK ;
  4277   // We do this the hard way, by blocking the thread.
  4278   // Consider enforcing a minimum timeout value.
  4279   struct timespec abst;
  4280   compute_abstime(&abst, millis);
  4282   int ret = OS_TIMEOUT;
  4283   int status = pthread_mutex_lock(_mutex);
  4284   assert_status(status == 0, status, "mutex_lock");
  4285   guarantee (_nParked == 0, "invariant") ;
  4286   ++_nParked ;
  4288   // Object.wait(timo) will return because of
  4289   // (a) notification
  4290   // (b) timeout
  4291   // (c) thread.interrupt
  4292   //
  4293   // Thread.interrupt and object.notify{All} both call Event::set.
  4294   // That is, we treat thread.interrupt as a special case of notification.
  4295   // The underlying Solaris implementation, cond_timedwait, admits
  4296   // spurious/premature wakeups, but the JLS/JVM spec prevents the
  4297   // JVM from making those visible to Java code.  As such, we must
  4298   // filter out spurious wakeups.  We assume all ETIME returns are valid.
  4299   //
  4300   // TODO: properly differentiate simultaneous notify+interrupt.
  4301   // In that case, we should propagate the notify to another waiter.
  4303   while (_Event < 0) {
  4304     status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
  4305     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4306       pthread_cond_destroy (_cond);
  4307       pthread_cond_init (_cond, NULL) ;
  4309     assert_status(status == 0 || status == EINTR ||
  4310                   status == ETIMEDOUT,
  4311                   status, "cond_timedwait");
  4312     if (!FilterSpuriousWakeups) break ;                 // previous semantics
  4313     if (status == ETIMEDOUT) break ;
  4314     // We consume and ignore EINTR and spurious wakeups.
  4316   --_nParked ;
  4317   if (_Event >= 0) {
  4318      ret = OS_OK;
  4320   _Event = 0 ;
  4321   status = pthread_mutex_unlock(_mutex);
  4322   assert_status(status == 0, status, "mutex_unlock");
  4323   assert (_nParked == 0, "invariant") ;
  4324   // Paranoia to ensure our locked and lock-free paths interact
  4325   // correctly with each other.
  4326   OrderAccess::fence();
  4327   return ret;
  4330 void os::PlatformEvent::unpark() {
  4331   // Transitions for _Event:
  4332   //    0 :=> 1
  4333   //    1 :=> 1
  4334   //   -1 :=> either 0 or 1; must signal target thread
  4335   //          That is, we can safely transition _Event from -1 to either
  4336   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
  4337   //          unpark() calls.
  4338   // See also: "Semaphores in Plan 9" by Mullender & Cox
  4339   //
  4340   // Note: Forcing a transition from "-1" to "1" on an unpark() means
  4341   // that it will take two back-to-back park() calls for the owning
  4342   // thread to block. This has the benefit of forcing a spurious return
  4343   // from the first park() call after an unpark() call which will help
  4344   // shake out uses of park() and unpark() without condition variables.
  4346   if (Atomic::xchg(1, &_Event) >= 0) return;
  4348   // Wait for the thread associated with the event to vacate
  4349   int status = pthread_mutex_lock(_mutex);
  4350   assert_status(status == 0, status, "mutex_lock");
  4351   int AnyWaiters = _nParked;
  4352   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
  4353   if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
  4354     AnyWaiters = 0;
  4355     pthread_cond_signal(_cond);
  4357   status = pthread_mutex_unlock(_mutex);
  4358   assert_status(status == 0, status, "mutex_unlock");
  4359   if (AnyWaiters != 0) {
  4360     status = pthread_cond_signal(_cond);
  4361     assert_status(status == 0, status, "cond_signal");
  4364   // Note that we signal() _after dropping the lock for "immortal" Events.
  4365   // This is safe and avoids a common class of  futile wakeups.  In rare
  4366   // circumstances this can cause a thread to return prematurely from
  4367   // cond_{timed}wait() but the spurious wakeup is benign and the victim will
  4368   // simply re-test the condition and re-park itself.
  4372 // JSR166
  4373 // -------------------------------------------------------
  4375 /*
  4376  * The solaris and bsd implementations of park/unpark are fairly
  4377  * conservative for now, but can be improved. They currently use a
  4378  * mutex/condvar pair, plus a a count.
  4379  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4380  * sets count to 1 and signals condvar.  Only one thread ever waits
  4381  * on the condvar. Contention seen when trying to park implies that someone
  4382  * is unparking you, so don't wait. And spurious returns are fine, so there
  4383  * is no need to track notifications.
  4384  */
  4386 #define MAX_SECS 100000000
  4387 /*
  4388  * This code is common to bsd and solaris and will be moved to a
  4389  * common place in dolphin.
  4391  * The passed in time value is either a relative time in nanoseconds
  4392  * or an absolute time in milliseconds. Either way it has to be unpacked
  4393  * into suitable seconds and nanoseconds components and stored in the
  4394  * given timespec structure.
  4395  * Given time is a 64-bit value and the time_t used in the timespec is only
  4396  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4397  * overflow if times way in the future are given. Further on Solaris versions
  4398  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4399  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4400  * As it will be 28 years before "now + 100000000" will overflow we can
  4401  * ignore overflow and just impose a hard-limit on seconds using the value
  4402  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4403  * years from "now".
  4404  */
  4406 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4407   assert (time > 0, "convertTime");
  4409   struct timeval now;
  4410   int status = gettimeofday(&now, NULL);
  4411   assert(status == 0, "gettimeofday");
  4413   time_t max_secs = now.tv_sec + MAX_SECS;
  4415   if (isAbsolute) {
  4416     jlong secs = time / 1000;
  4417     if (secs > max_secs) {
  4418       absTime->tv_sec = max_secs;
  4420     else {
  4421       absTime->tv_sec = secs;
  4423     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4425   else {
  4426     jlong secs = time / NANOSECS_PER_SEC;
  4427     if (secs >= MAX_SECS) {
  4428       absTime->tv_sec = max_secs;
  4429       absTime->tv_nsec = 0;
  4431     else {
  4432       absTime->tv_sec = now.tv_sec + secs;
  4433       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4434       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4435         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4436         ++absTime->tv_sec; // note: this must be <= max_secs
  4440   assert(absTime->tv_sec >= 0, "tv_sec < 0");
  4441   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
  4442   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
  4443   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
  4446 void Parker::park(bool isAbsolute, jlong time) {
  4447   // Ideally we'd do something useful while spinning, such
  4448   // as calling unpackTime().
  4450   // Optional fast-path check:
  4451   // Return immediately if a permit is available.
  4452   // We depend on Atomic::xchg() having full barrier semantics
  4453   // since we are doing a lock-free update to _counter.
  4454   if (Atomic::xchg(0, &_counter) > 0) return;
  4456   Thread* thread = Thread::current();
  4457   assert(thread->is_Java_thread(), "Must be JavaThread");
  4458   JavaThread *jt = (JavaThread *)thread;
  4460   // Optional optimization -- avoid state transitions if there's an interrupt pending.
  4461   // Check interrupt before trying to wait
  4462   if (Thread::is_interrupted(thread, false)) {
  4463     return;
  4466   // Next, demultiplex/decode time arguments
  4467   struct timespec absTime;
  4468   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
  4469     return;
  4471   if (time > 0) {
  4472     unpackTime(&absTime, isAbsolute, time);
  4476   // Enter safepoint region
  4477   // Beware of deadlocks such as 6317397.
  4478   // The per-thread Parker:: mutex is a classic leaf-lock.
  4479   // In particular a thread must never block on the Threads_lock while
  4480   // holding the Parker:: mutex.  If safepoints are pending both the
  4481   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
  4482   ThreadBlockInVM tbivm(jt);
  4484   // Don't wait if cannot get lock since interference arises from
  4485   // unblocking.  Also. check interrupt before trying wait
  4486   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
  4487     return;
  4490   int status ;
  4491   if (_counter > 0)  { // no wait needed
  4492     _counter = 0;
  4493     status = pthread_mutex_unlock(_mutex);
  4494     assert (status == 0, "invariant") ;
  4495     // Paranoia to ensure our locked and lock-free paths interact
  4496     // correctly with each other and Java-level accesses.
  4497     OrderAccess::fence();
  4498     return;
  4501 #ifdef ASSERT
  4502   // Don't catch signals while blocked; let the running threads have the signals.
  4503   // (This allows a debugger to break into the running thread.)
  4504   sigset_t oldsigs;
  4505   sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
  4506   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
  4507 #endif
  4509   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  4510   jt->set_suspend_equivalent();
  4511   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  4513   if (time == 0) {
  4514     status = pthread_cond_wait (_cond, _mutex) ;
  4515   } else {
  4516     status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
  4517     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4518       pthread_cond_destroy (_cond) ;
  4519       pthread_cond_init    (_cond, NULL);
  4522   assert_status(status == 0 || status == EINTR ||
  4523                 status == ETIMEDOUT,
  4524                 status, "cond_timedwait");
  4526 #ifdef ASSERT
  4527   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
  4528 #endif
  4530   _counter = 0 ;
  4531   status = pthread_mutex_unlock(_mutex) ;
  4532   assert_status(status == 0, status, "invariant") ;
  4533   // Paranoia to ensure our locked and lock-free paths interact
  4534   // correctly with each other and Java-level accesses.
  4535   OrderAccess::fence();
  4537   // If externally suspended while waiting, re-suspend
  4538   if (jt->handle_special_suspend_equivalent_condition()) {
  4539     jt->java_suspend_self();
  4543 void Parker::unpark() {
  4544   int s, status ;
  4545   status = pthread_mutex_lock(_mutex);
  4546   assert (status == 0, "invariant") ;
  4547   s = _counter;
  4548   _counter = 1;
  4549   if (s < 1) {
  4550      if (WorkAroundNPTLTimedWaitHang) {
  4551         status = pthread_cond_signal (_cond) ;
  4552         assert (status == 0, "invariant") ;
  4553         status = pthread_mutex_unlock(_mutex);
  4554         assert (status == 0, "invariant") ;
  4555      } else {
  4556         status = pthread_mutex_unlock(_mutex);
  4557         assert (status == 0, "invariant") ;
  4558         status = pthread_cond_signal (_cond) ;
  4559         assert (status == 0, "invariant") ;
  4561   } else {
  4562     pthread_mutex_unlock(_mutex);
  4563     assert (status == 0, "invariant") ;
  4568 /* Darwin has no "environ" in a dynamic library. */
  4569 #ifdef __APPLE__
  4570 #include <crt_externs.h>
  4571 #define environ (*_NSGetEnviron())
  4572 #else
  4573 extern char** environ;
  4574 #endif
  4576 // Run the specified command in a separate process. Return its exit value,
  4577 // or -1 on failure (e.g. can't fork a new process).
  4578 // Unlike system(), this function can be called from signal handler. It
  4579 // doesn't block SIGINT et al.
  4580 int os::fork_and_exec(char* cmd) {
  4581   const char * argv[4] = {"sh", "-c", cmd, NULL};
  4583   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
  4584   // pthread_atfork handlers and reset pthread library. All we need is a
  4585   // separate process to execve. Make a direct syscall to fork process.
  4586   // On IA64 there's no fork syscall, we have to use fork() and hope for
  4587   // the best...
  4588   pid_t pid = fork();
  4590   if (pid < 0) {
  4591     // fork failed
  4592     return -1;
  4594   } else if (pid == 0) {
  4595     // child process
  4597     // execve() in BsdThreads will call pthread_kill_other_threads_np()
  4598     // first to kill every thread on the thread list. Because this list is
  4599     // not reset by fork() (see notes above), execve() will instead kill
  4600     // every thread in the parent process. We know this is the only thread
  4601     // in the new process, so make a system call directly.
  4602     // IA64 should use normal execve() from glibc to match the glibc fork()
  4603     // above.
  4604     execve("/bin/sh", (char* const*)argv, environ);
  4606     // execve failed
  4607     _exit(-1);
  4609   } else  {
  4610     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
  4611     // care about the actual exit code, for now.
  4613     int status;
  4615     // Wait for the child process to exit.  This returns immediately if
  4616     // the child has already exited. */
  4617     while (waitpid(pid, &status, 0) < 0) {
  4618         switch (errno) {
  4619         case ECHILD: return 0;
  4620         case EINTR: break;
  4621         default: return -1;
  4625     if (WIFEXITED(status)) {
  4626        // The child exited normally; get its exit code.
  4627        return WEXITSTATUS(status);
  4628     } else if (WIFSIGNALED(status)) {
  4629        // The child exited because of a signal
  4630        // The best value to return is 0x80 + signal number,
  4631        // because that is what all Unix shells do, and because
  4632        // it allows callers to distinguish between process exit and
  4633        // process death by signal.
  4634        return 0x80 + WTERMSIG(status);
  4635     } else {
  4636        // Unknown exit code; pass it through
  4637        return status;
  4642 // is_headless_jre()
  4643 //
  4644 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
  4645 // in order to report if we are running in a headless jre
  4646 //
  4647 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4648 // as libawt.so, and renamed libawt_xawt.so
  4649 //
  4650 bool os::is_headless_jre() {
  4651     struct stat statbuf;
  4652     char buf[MAXPATHLEN];
  4653     char libmawtpath[MAXPATHLEN];
  4654     const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
  4655     const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
  4656     char *p;
  4658     // Get path to libjvm.so
  4659     os::jvm_path(buf, sizeof(buf));
  4661     // Get rid of libjvm.so
  4662     p = strrchr(buf, '/');
  4663     if (p == NULL) return false;
  4664     else *p = '\0';
  4666     // Get rid of client or server
  4667     p = strrchr(buf, '/');
  4668     if (p == NULL) return false;
  4669     else *p = '\0';
  4671     // check xawt/libmawt.so
  4672     strcpy(libmawtpath, buf);
  4673     strcat(libmawtpath, xawtstr);
  4674     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4676     // check libawt_xawt.so
  4677     strcpy(libmawtpath, buf);
  4678     strcat(libmawtpath, new_xawtstr);
  4679     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4681     return true;
  4684 // Get the default path to the core file
  4685 // Returns the length of the string
  4686 int os::get_core_path(char* buffer, size_t bufferSize) {
  4687   int n = jio_snprintf(buffer, bufferSize, "/cores");
  4689   // Truncate if theoretical string was longer than bufferSize
  4690   n = MIN2(n, (int)bufferSize);
  4692   return n;

mercurial