src/os/bsd/vm/os_bsd.cpp

Thu, 07 Mar 2013 14:46:20 -0800

author
morris
date
Thu, 07 Mar 2013 14:46:20 -0800
changeset 4696
bdb602473679
parent 4675
63e54c37ac64
parent 4689
bf06968a8a00
child 4713
252ad8d5f22b
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 // no precompiled headers
    26 #include "classfile/classLoader.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "classfile/vmSymbols.hpp"
    29 #include "code/icBuffer.hpp"
    30 #include "code/vtableStubs.hpp"
    31 #include "compiler/compileBroker.hpp"
    32 #include "compiler/disassembler.hpp"
    33 #include "interpreter/interpreter.hpp"
    34 #include "jvm_bsd.h"
    35 #include "memory/allocation.inline.hpp"
    36 #include "memory/filemap.hpp"
    37 #include "mutex_bsd.inline.hpp"
    38 #include "oops/oop.inline.hpp"
    39 #include "os_share_bsd.hpp"
    40 #include "prims/jniFastGetField.hpp"
    41 #include "prims/jvm.h"
    42 #include "prims/jvm_misc.hpp"
    43 #include "runtime/arguments.hpp"
    44 #include "runtime/extendedPC.hpp"
    45 #include "runtime/globals.hpp"
    46 #include "runtime/interfaceSupport.hpp"
    47 #include "runtime/java.hpp"
    48 #include "runtime/javaCalls.hpp"
    49 #include "runtime/mutexLocker.hpp"
    50 #include "runtime/objectMonitor.hpp"
    51 #include "runtime/osThread.hpp"
    52 #include "runtime/perfMemory.hpp"
    53 #include "runtime/sharedRuntime.hpp"
    54 #include "runtime/statSampler.hpp"
    55 #include "runtime/stubRoutines.hpp"
    56 #include "runtime/thread.inline.hpp"
    57 #include "runtime/threadCritical.hpp"
    58 #include "runtime/timer.hpp"
    59 #include "services/attachListener.hpp"
    60 #include "services/runtimeService.hpp"
    61 #include "utilities/decoder.hpp"
    62 #include "utilities/defaultStream.hpp"
    63 #include "utilities/events.hpp"
    64 #include "utilities/growableArray.hpp"
    65 #include "utilities/vmError.hpp"
    67 // put OS-includes here
    68 # include <sys/types.h>
    69 # include <sys/mman.h>
    70 # include <sys/stat.h>
    71 # include <sys/select.h>
    72 # include <pthread.h>
    73 # include <signal.h>
    74 # include <errno.h>
    75 # include <dlfcn.h>
    76 # include <stdio.h>
    77 # include <unistd.h>
    78 # include <sys/resource.h>
    79 # include <pthread.h>
    80 # include <sys/stat.h>
    81 # include <sys/time.h>
    82 # include <sys/times.h>
    83 # include <sys/utsname.h>
    84 # include <sys/socket.h>
    85 # include <sys/wait.h>
    86 # include <time.h>
    87 # include <pwd.h>
    88 # include <poll.h>
    89 # include <semaphore.h>
    90 # include <fcntl.h>
    91 # include <string.h>
    92 # include <sys/param.h>
    93 # include <sys/sysctl.h>
    94 # include <sys/ipc.h>
    95 # include <sys/shm.h>
    96 #ifndef __APPLE__
    97 # include <link.h>
    98 #endif
    99 # include <stdint.h>
   100 # include <inttypes.h>
   101 # include <sys/ioctl.h>
   103 #if defined(__FreeBSD__) || defined(__NetBSD__)
   104 # include <elf.h>
   105 #endif
   107 #ifdef __APPLE__
   108 # include <mach/mach.h> // semaphore_* API
   109 # include <mach-o/dyld.h>
   110 # include <sys/proc_info.h>
   111 # include <objc/objc-auto.h>
   112 #endif
   114 #ifndef MAP_ANONYMOUS
   115 #define MAP_ANONYMOUS MAP_ANON
   116 #endif
   118 #define MAX_PATH    (2 * K)
   120 // for timer info max values which include all bits
   121 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
   123 #define LARGEPAGES_BIT (1 << 6)
   124 ////////////////////////////////////////////////////////////////////////////////
   125 // global variables
   126 julong os::Bsd::_physical_memory = 0;
   129 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
   130 pthread_t os::Bsd::_main_thread;
   131 int os::Bsd::_page_size = -1;
   133 static jlong initial_time_count=0;
   135 static int clock_tics_per_sec = 100;
   137 // For diagnostics to print a message once. see run_periodic_checks
   138 static sigset_t check_signal_done;
   139 static bool check_signals = true;
   141 static pid_t _initial_pid = 0;
   143 /* Signal number used to suspend/resume a thread */
   145 /* do not use any signal number less than SIGSEGV, see 4355769 */
   146 static int SR_signum = SIGUSR2;
   147 sigset_t SR_sigset;
   150 ////////////////////////////////////////////////////////////////////////////////
   151 // utility functions
   153 static int SR_initialize();
   154 static int SR_finalize();
   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 julong os::allocatable_physical_memory(julong size) {
   170 #ifdef _LP64
   171   return size;
   172 #else
   173   julong result = MIN2(size, (julong)3800*M);
   174    if (!is_allocatable(result)) {
   175      // See comments under solaris for alignment considerations
   176      julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
   177      result =  MIN2(size, reasonable_size);
   178    }
   179    return result;
   180 #endif // _LP64
   181 }
   183 ////////////////////////////////////////////////////////////////////////////////
   184 // environment support
   186 bool os::getenv(const char* name, char* buf, int len) {
   187   const char* val = ::getenv(name);
   188   if (val != NULL && strlen(val) < (size_t)len) {
   189     strcpy(buf, val);
   190     return true;
   191   }
   192   if (len > 0) buf[0] = 0;  // return a null string
   193   return false;
   194 }
   197 // Return true if user is running as root.
   199 bool os::have_special_privileges() {
   200   static bool init = false;
   201   static bool privileges = false;
   202   if (!init) {
   203     privileges = (getuid() != geteuid()) || (getgid() != getegid());
   204     init = true;
   205   }
   206   return privileges;
   207 }
   211 // Cpu architecture string
   212 #if   defined(ZERO)
   213 static char cpu_arch[] = ZERO_LIBARCH;
   214 #elif defined(IA64)
   215 static char cpu_arch[] = "ia64";
   216 #elif defined(IA32)
   217 static char cpu_arch[] = "i386";
   218 #elif defined(AMD64)
   219 static char cpu_arch[] = "amd64";
   220 #elif defined(ARM)
   221 static char cpu_arch[] = "arm";
   222 #elif defined(PPC)
   223 static char cpu_arch[] = "ppc";
   224 #elif defined(SPARC)
   225 #  ifdef _LP64
   226 static char cpu_arch[] = "sparcv9";
   227 #  else
   228 static char cpu_arch[] = "sparc";
   229 #  endif
   230 #else
   231 #error Add appropriate cpu_arch setting
   232 #endif
   234 // Compiler variant
   235 #ifdef COMPILER2
   236 #define COMPILER_VARIANT "server"
   237 #else
   238 #define COMPILER_VARIANT "client"
   239 #endif
   242 void os::Bsd::initialize_system_info() {
   243   int mib[2];
   244   size_t len;
   245   int cpu_val;
   246   julong mem_val;
   248   /* get processors count via hw.ncpus sysctl */
   249   mib[0] = CTL_HW;
   250   mib[1] = HW_NCPU;
   251   len = sizeof(cpu_val);
   252   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
   253        assert(len == sizeof(cpu_val), "unexpected data size");
   254        set_processor_count(cpu_val);
   255   }
   256   else {
   257        set_processor_count(1);   // fallback
   258   }
   260   /* get physical memory via hw.memsize sysctl (hw.memsize is used
   261    * since it returns a 64 bit value)
   262    */
   263   mib[0] = CTL_HW;
   264   mib[1] = HW_MEMSIZE;
   265   len = sizeof(mem_val);
   266   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
   267        assert(len == sizeof(mem_val), "unexpected data size");
   268        _physical_memory = mem_val;
   269   } else {
   270        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
   271   }
   273 #ifdef __OpenBSD__
   274   {
   275        // limit _physical_memory memory view on OpenBSD since
   276        // datasize rlimit restricts us anyway.
   277        struct rlimit limits;
   278        getrlimit(RLIMIT_DATA, &limits);
   279        _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
   280   }
   281 #endif
   282 }
   284 #ifdef __APPLE__
   285 static const char *get_home() {
   286   const char *home_dir = ::getenv("HOME");
   287   if ((home_dir == NULL) || (*home_dir == '\0')) {
   288     struct passwd *passwd_info = getpwuid(geteuid());
   289     if (passwd_info != NULL) {
   290       home_dir = passwd_info->pw_dir;
   291     }
   292   }
   294   return home_dir;
   295 }
   296 #endif
   298 void os::init_system_properties_values() {
   299 //  char arch[12];
   300 //  sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
   302   // The next steps are taken in the product version:
   303   //
   304   // Obtain the JAVA_HOME value from the location of libjvm.so.
   305   // This library should be located at:
   306   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
   307   //
   308   // If "/jre/lib/" appears at the right place in the path, then we
   309   // assume libjvm.so is installed in a JDK and we use this path.
   310   //
   311   // Otherwise exit with message: "Could not create the Java virtual machine."
   312   //
   313   // The following extra steps are taken in the debugging version:
   314   //
   315   // If "/jre/lib/" does NOT appear at the right place in the path
   316   // instead of exit check for $JAVA_HOME environment variable.
   317   //
   318   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
   319   // then we append a fake suffix "hotspot/libjvm.so" to this path so
   320   // it looks like libjvm.so is installed there
   321   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
   322   //
   323   // Otherwise exit.
   324   //
   325   // Important note: if the location of libjvm.so changes this
   326   // code needs to be changed accordingly.
   328   // The next few definitions allow the code to be verbatim:
   329 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
   330 #define getenv(n) ::getenv(n)
   332 /*
   333  * See ld(1):
   334  *      The linker uses the following search paths to locate required
   335  *      shared libraries:
   336  *        1: ...
   337  *        ...
   338  *        7: The default directories, normally /lib and /usr/lib.
   339  */
   340 #ifndef DEFAULT_LIBPATH
   341 #define DEFAULT_LIBPATH "/lib:/usr/lib"
   342 #endif
   344 #define EXTENSIONS_DIR  "/lib/ext"
   345 #define ENDORSED_DIR    "/lib/endorsed"
   346 #define REG_DIR         "/usr/java/packages"
   348 #ifdef __APPLE__
   349 #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
   350 #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
   351         const char *user_home_dir = get_home();
   352         // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
   353         int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
   354             sizeof(SYS_EXTENSIONS_DIRS);
   355 #endif
   357   {
   358     /* sysclasspath, java_home, dll_dir */
   359     {
   360         char *home_path;
   361         char *dll_path;
   362         char *pslash;
   363         char buf[MAXPATHLEN];
   364         os::jvm_path(buf, sizeof(buf));
   366         // Found the full path to libjvm.so.
   367         // Now cut the path to <java_home>/jre if we can.
   368         *(strrchr(buf, '/')) = '\0';  /* get rid of /libjvm.so */
   369         pslash = strrchr(buf, '/');
   370         if (pslash != NULL)
   371             *pslash = '\0';           /* get rid of /{client|server|hotspot} */
   372         dll_path = malloc(strlen(buf) + 1);
   373         if (dll_path == NULL)
   374             return;
   375         strcpy(dll_path, buf);
   376         Arguments::set_dll_dir(dll_path);
   378         if (pslash != NULL) {
   379             pslash = strrchr(buf, '/');
   380             if (pslash != NULL) {
   381                 *pslash = '\0';       /* get rid of /<arch> (/lib on macosx) */
   382 #ifndef __APPLE__
   383                 pslash = strrchr(buf, '/');
   384                 if (pslash != NULL)
   385                     *pslash = '\0';   /* get rid of /lib */
   386 #endif
   387             }
   388         }
   390         home_path = malloc(strlen(buf) + 1);
   391         if (home_path == NULL)
   392             return;
   393         strcpy(home_path, buf);
   394         Arguments::set_java_home(home_path);
   396         if (!set_boot_path('/', ':'))
   397             return;
   398     }
   400     /*
   401      * Where to look for native libraries
   402      *
   403      * Note: Due to a legacy implementation, most of the library path
   404      * is set in the launcher.  This was to accomodate linking restrictions
   405      * on legacy Bsd implementations (which are no longer supported).
   406      * Eventually, all the library path setting will be done here.
   407      *
   408      * However, to prevent the proliferation of improperly built native
   409      * libraries, the new path component /usr/java/packages is added here.
   410      * Eventually, all the library path setting will be done here.
   411      */
   412     {
   413         char *ld_library_path;
   415         /*
   416          * Construct the invariant part of ld_library_path. Note that the
   417          * space for the colon and the trailing null are provided by the
   418          * nulls included by the sizeof operator (so actually we allocate
   419          * a byte more than necessary).
   420          */
   421 #ifdef __APPLE__
   422         ld_library_path = (char *) malloc(system_ext_size);
   423         sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir);
   424 #else
   425         ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
   426             strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
   427         sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
   428 #endif
   430         /*
   431          * Get the user setting of LD_LIBRARY_PATH, and prepended it.  It
   432          * should always exist (until the legacy problem cited above is
   433          * addressed).
   434          */
   435 #ifdef __APPLE__
   436         // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
   437         char *l = getenv("JAVA_LIBRARY_PATH");
   438         if (l != NULL) {
   439             char *t = ld_library_path;
   440             /* That's +1 for the colon and +1 for the trailing '\0' */
   441             ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1);
   442             sprintf(ld_library_path, "%s:%s", l, t);
   443             free(t);
   444         }
   446         char *v = getenv("DYLD_LIBRARY_PATH");
   447 #else
   448         char *v = getenv("LD_LIBRARY_PATH");
   449 #endif
   450         if (v != NULL) {
   451             char *t = ld_library_path;
   452             /* That's +1 for the colon and +1 for the trailing '\0' */
   453             ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
   454             sprintf(ld_library_path, "%s:%s", v, t);
   455             free(t);
   456         }
   458 #ifdef __APPLE__
   459         // Apple's Java6 has "." at the beginning of java.library.path.
   460         // OpenJDK on Windows has "." at the end of java.library.path.
   461         // OpenJDK on Linux and Solaris don't have "." in java.library.path
   462         // at all. To ease the transition from Apple's Java6 to OpenJDK7,
   463         // "." is appended to the end of java.library.path. Yes, this
   464         // could cause a change in behavior, but Apple's Java6 behavior
   465         // can be achieved by putting "." at the beginning of the
   466         // JAVA_LIBRARY_PATH environment variable.
   467         {
   468             char *t = ld_library_path;
   469             // that's +3 for appending ":." and the trailing '\0'
   470             ld_library_path = (char *) malloc(strlen(t) + 3);
   471             sprintf(ld_library_path, "%s:%s", t, ".");
   472             free(t);
   473         }
   474 #endif
   476         Arguments::set_library_path(ld_library_path);
   477     }
   479     /*
   480      * Extensions directories.
   481      *
   482      * Note that the space for the colon and the trailing null are provided
   483      * by the nulls included by the sizeof operator (so actually one byte more
   484      * than necessary is allocated).
   485      */
   486     {
   487 #ifdef __APPLE__
   488         char *buf = malloc(strlen(Arguments::get_java_home()) +
   489             sizeof(EXTENSIONS_DIR) + system_ext_size);
   490         sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":"
   491             SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home());
   492 #else
   493         char *buf = malloc(strlen(Arguments::get_java_home()) +
   494             sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
   495         sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
   496             Arguments::get_java_home());
   497 #endif
   499         Arguments::set_ext_dirs(buf);
   500     }
   502     /* Endorsed standards default directory. */
   503     {
   504         char * buf;
   505         buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
   506         sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
   507         Arguments::set_endorsed_dirs(buf);
   508     }
   509   }
   511 #ifdef __APPLE__
   512 #undef SYS_EXTENSIONS_DIR
   513 #endif
   514 #undef malloc
   515 #undef getenv
   516 #undef EXTENSIONS_DIR
   517 #undef ENDORSED_DIR
   519   // Done
   520   return;
   521 }
   523 ////////////////////////////////////////////////////////////////////////////////
   524 // breakpoint support
   526 void os::breakpoint() {
   527   BREAKPOINT;
   528 }
   530 extern "C" void breakpoint() {
   531   // use debugger to set breakpoint here
   532 }
   534 ////////////////////////////////////////////////////////////////////////////////
   535 // signal support
   537 debug_only(static bool signal_sets_initialized = false);
   538 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
   540 bool os::Bsd::is_sig_ignored(int sig) {
   541       struct sigaction oact;
   542       sigaction(sig, (struct sigaction*)NULL, &oact);
   543       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
   544                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
   545       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
   546            return true;
   547       else
   548            return false;
   549 }
   551 void os::Bsd::signal_sets_init() {
   552   // Should also have an assertion stating we are still single-threaded.
   553   assert(!signal_sets_initialized, "Already initialized");
   554   // Fill in signals that are necessarily unblocked for all threads in
   555   // the VM. Currently, we unblock the following signals:
   556   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
   557   //                         by -Xrs (=ReduceSignalUsage));
   558   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
   559   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
   560   // the dispositions or masks wrt these signals.
   561   // Programs embedding the VM that want to use the above signals for their
   562   // own purposes must, at this time, use the "-Xrs" option to prevent
   563   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
   564   // (See bug 4345157, and other related bugs).
   565   // In reality, though, unblocking these signals is really a nop, since
   566   // these signals are not blocked by default.
   567   sigemptyset(&unblocked_sigs);
   568   sigemptyset(&allowdebug_blocked_sigs);
   569   sigaddset(&unblocked_sigs, SIGILL);
   570   sigaddset(&unblocked_sigs, SIGSEGV);
   571   sigaddset(&unblocked_sigs, SIGBUS);
   572   sigaddset(&unblocked_sigs, SIGFPE);
   573   sigaddset(&unblocked_sigs, SR_signum);
   575   if (!ReduceSignalUsage) {
   576    if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
   577       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
   578       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
   579    }
   580    if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
   581       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
   582       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
   583    }
   584    if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
   585       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
   586       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
   587    }
   588   }
   589   // Fill in signals that are blocked by all but the VM thread.
   590   sigemptyset(&vm_sigs);
   591   if (!ReduceSignalUsage)
   592     sigaddset(&vm_sigs, BREAK_SIGNAL);
   593   debug_only(signal_sets_initialized = true);
   595 }
   597 // These are signals that are unblocked while a thread is running Java.
   598 // (For some reason, they get blocked by default.)
   599 sigset_t* os::Bsd::unblocked_signals() {
   600   assert(signal_sets_initialized, "Not initialized");
   601   return &unblocked_sigs;
   602 }
   604 // These are the signals that are blocked while a (non-VM) thread is
   605 // running Java. Only the VM thread handles these signals.
   606 sigset_t* os::Bsd::vm_signals() {
   607   assert(signal_sets_initialized, "Not initialized");
   608   return &vm_sigs;
   609 }
   611 // These are signals that are blocked during cond_wait to allow debugger in
   612 sigset_t* os::Bsd::allowdebug_blocked_signals() {
   613   assert(signal_sets_initialized, "Not initialized");
   614   return &allowdebug_blocked_sigs;
   615 }
   617 void os::Bsd::hotspot_sigmask(Thread* thread) {
   619   //Save caller's signal mask before setting VM signal mask
   620   sigset_t caller_sigmask;
   621   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
   623   OSThread* osthread = thread->osthread();
   624   osthread->set_caller_sigmask(caller_sigmask);
   626   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
   628   if (!ReduceSignalUsage) {
   629     if (thread->is_VM_thread()) {
   630       // Only the VM thread handles BREAK_SIGNAL ...
   631       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
   632     } else {
   633       // ... all other threads block BREAK_SIGNAL
   634       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
   635     }
   636   }
   637 }
   640 //////////////////////////////////////////////////////////////////////////////
   641 // create new thread
   643 static address highest_vm_reserved_address();
   645 // check if it's safe to start a new thread
   646 static bool _thread_safety_check(Thread* thread) {
   647   return true;
   648 }
   650 #ifdef __APPLE__
   651 // library handle for calling objc_registerThreadWithCollector()
   652 // without static linking to the libobjc library
   653 #define OBJC_LIB "/usr/lib/libobjc.dylib"
   654 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
   655 typedef void (*objc_registerThreadWithCollector_t)();
   656 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
   657 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
   658 #endif
   660 #ifdef __APPLE__
   661 static uint64_t locate_unique_thread_id() {
   662   // Additional thread_id used to correlate threads in SA
   663   thread_identifier_info_data_t     m_ident_info;
   664   mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
   666   thread_info(::mach_thread_self(), THREAD_IDENTIFIER_INFO,
   667               (thread_info_t) &m_ident_info, &count);
   668   return m_ident_info.thread_id;
   669 }
   670 #endif
   672 // Thread start routine for all newly created threads
   673 static void *java_start(Thread *thread) {
   674   // Try to randomize the cache line index of hot stack frames.
   675   // This helps when threads of the same stack traces evict each other's
   676   // cache lines. The threads can be either from the same JVM instance, or
   677   // from different JVM instances. The benefit is especially true for
   678   // processors with hyperthreading technology.
   679   static int counter = 0;
   680   int pid = os::current_process_id();
   681   alloca(((pid ^ counter++) & 7) * 128);
   683   ThreadLocalStorage::set_thread(thread);
   685   OSThread* osthread = thread->osthread();
   686   Monitor* sync = osthread->startThread_lock();
   688   // non floating stack BsdThreads needs extra check, see above
   689   if (!_thread_safety_check(thread)) {
   690     // notify parent thread
   691     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   692     osthread->set_state(ZOMBIE);
   693     sync->notify_all();
   694     return NULL;
   695   }
   697 #ifdef __APPLE__
   698   // thread_id is mach thread on macos
   699   osthread->set_thread_id(::mach_thread_self());
   700   osthread->set_unique_thread_id(locate_unique_thread_id());
   701 #else
   702   // thread_id is pthread_id on BSD
   703   osthread->set_thread_id(::pthread_self());
   704 #endif
   705   // initialize signal mask for this thread
   706   os::Bsd::hotspot_sigmask(thread);
   708   // initialize floating point control register
   709   os::Bsd::init_thread_fpu_state();
   711 #ifdef __APPLE__
   712   // register thread with objc gc
   713   if (objc_registerThreadWithCollectorFunction != NULL) {
   714     objc_registerThreadWithCollectorFunction();
   715   }
   716 #endif
   718   // handshaking with parent thread
   719   {
   720     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   722     // notify parent thread
   723     osthread->set_state(INITIALIZED);
   724     sync->notify_all();
   726     // wait until os::start_thread()
   727     while (osthread->get_state() == INITIALIZED) {
   728       sync->wait(Mutex::_no_safepoint_check_flag);
   729     }
   730   }
   732   // call one more level start routine
   733   thread->run();
   735   return 0;
   736 }
   738 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
   739   assert(thread->osthread() == NULL, "caller responsible");
   741   // Allocate the OSThread object
   742   OSThread* osthread = new OSThread(NULL, NULL);
   743   if (osthread == NULL) {
   744     return false;
   745   }
   747   // set the correct thread state
   748   osthread->set_thread_type(thr_type);
   750   // Initial state is ALLOCATED but not INITIALIZED
   751   osthread->set_state(ALLOCATED);
   753   thread->set_osthread(osthread);
   755   // init thread attributes
   756   pthread_attr_t attr;
   757   pthread_attr_init(&attr);
   758   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   760   // stack size
   761   if (os::Bsd::supports_variable_stack_size()) {
   762     // calculate stack size if it's not specified by caller
   763     if (stack_size == 0) {
   764       stack_size = os::Bsd::default_stack_size(thr_type);
   766       switch (thr_type) {
   767       case os::java_thread:
   768         // Java threads use ThreadStackSize which default value can be
   769         // changed with the flag -Xss
   770         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
   771         stack_size = JavaThread::stack_size_at_create();
   772         break;
   773       case os::compiler_thread:
   774         if (CompilerThreadStackSize > 0) {
   775           stack_size = (size_t)(CompilerThreadStackSize * K);
   776           break;
   777         } // else fall through:
   778           // use VMThreadStackSize if CompilerThreadStackSize is not defined
   779       case os::vm_thread:
   780       case os::pgc_thread:
   781       case os::cgc_thread:
   782       case os::watcher_thread:
   783         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
   784         break;
   785       }
   786     }
   788     stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
   789     pthread_attr_setstacksize(&attr, stack_size);
   790   } else {
   791     // let pthread_create() pick the default value.
   792   }
   794   ThreadState state;
   796   {
   797     pthread_t tid;
   798     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
   800     pthread_attr_destroy(&attr);
   802     if (ret != 0) {
   803       if (PrintMiscellaneous && (Verbose || WizardMode)) {
   804         perror("pthread_create()");
   805       }
   806       // Need to clean up stuff we've allocated so far
   807       thread->set_osthread(NULL);
   808       delete osthread;
   809       return false;
   810     }
   812     // Store pthread info into the OSThread
   813     osthread->set_pthread_id(tid);
   815     // Wait until child thread is either initialized or aborted
   816     {
   817       Monitor* sync_with_child = osthread->startThread_lock();
   818       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   819       while ((state = osthread->get_state()) == ALLOCATED) {
   820         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
   821       }
   822     }
   824   }
   826   // Aborted due to thread limit being reached
   827   if (state == ZOMBIE) {
   828       thread->set_osthread(NULL);
   829       delete osthread;
   830       return false;
   831   }
   833   // The thread is returned suspended (in state INITIALIZED),
   834   // and is started higher up in the call chain
   835   assert(state == INITIALIZED, "race condition");
   836   return true;
   837 }
   839 /////////////////////////////////////////////////////////////////////////////
   840 // attach existing thread
   842 // bootstrap the main thread
   843 bool os::create_main_thread(JavaThread* thread) {
   844   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
   845   return create_attached_thread(thread);
   846 }
   848 bool os::create_attached_thread(JavaThread* thread) {
   849 #ifdef ASSERT
   850     thread->verify_not_published();
   851 #endif
   853   // Allocate the OSThread object
   854   OSThread* osthread = new OSThread(NULL, NULL);
   856   if (osthread == NULL) {
   857     return false;
   858   }
   860   // Store pthread info into the OSThread
   861 #ifdef __APPLE__
   862   osthread->set_thread_id(::mach_thread_self());
   863   osthread->set_unique_thread_id(locate_unique_thread_id());
   864 #else
   865   osthread->set_thread_id(::pthread_self());
   866 #endif
   867   osthread->set_pthread_id(::pthread_self());
   869   // initialize floating point control register
   870   os::Bsd::init_thread_fpu_state();
   872   // Initial thread state is RUNNABLE
   873   osthread->set_state(RUNNABLE);
   875   thread->set_osthread(osthread);
   877   // initialize signal mask for this thread
   878   // and save the caller's signal mask
   879   os::Bsd::hotspot_sigmask(thread);
   881   return true;
   882 }
   884 void os::pd_start_thread(Thread* thread) {
   885   OSThread * osthread = thread->osthread();
   886   assert(osthread->get_state() != INITIALIZED, "just checking");
   887   Monitor* sync_with_child = osthread->startThread_lock();
   888   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   889   sync_with_child->notify();
   890 }
   892 // Free Bsd resources related to the OSThread
   893 void os::free_thread(OSThread* osthread) {
   894   assert(osthread != NULL, "osthread not set");
   896   if (Thread::current()->osthread() == osthread) {
   897     // Restore caller's signal mask
   898     sigset_t sigmask = osthread->caller_sigmask();
   899     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   900    }
   902   delete osthread;
   903 }
   905 //////////////////////////////////////////////////////////////////////////////
   906 // thread local storage
   908 int os::allocate_thread_local_storage() {
   909   pthread_key_t key;
   910   int rslt = pthread_key_create(&key, NULL);
   911   assert(rslt == 0, "cannot allocate thread local storage");
   912   return (int)key;
   913 }
   915 // Note: This is currently not used by VM, as we don't destroy TLS key
   916 // on VM exit.
   917 void os::free_thread_local_storage(int index) {
   918   int rslt = pthread_key_delete((pthread_key_t)index);
   919   assert(rslt == 0, "invalid index");
   920 }
   922 void os::thread_local_storage_at_put(int index, void* value) {
   923   int rslt = pthread_setspecific((pthread_key_t)index, value);
   924   assert(rslt == 0, "pthread_setspecific failed");
   925 }
   927 extern "C" Thread* get_thread() {
   928   return ThreadLocalStorage::thread();
   929 }
   932 ////////////////////////////////////////////////////////////////////////////////
   933 // time support
   935 // Time since start-up in seconds to a fine granularity.
   936 // Used by VMSelfDestructTimer and the MemProfiler.
   937 double os::elapsedTime() {
   939   return (double)(os::elapsed_counter()) * 0.000001;
   940 }
   942 jlong os::elapsed_counter() {
   943   timeval time;
   944   int status = gettimeofday(&time, NULL);
   945   return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
   946 }
   948 jlong os::elapsed_frequency() {
   949   return (1000 * 1000);
   950 }
   952 // XXX: For now, code this as if BSD does not support vtime.
   953 bool os::supports_vtime() { return false; }
   954 bool os::enable_vtime()   { return false; }
   955 bool os::vtime_enabled()  { return false; }
   956 double os::elapsedVTime() {
   957   // better than nothing, but not much
   958   return elapsedTime();
   959 }
   961 jlong os::javaTimeMillis() {
   962   timeval time;
   963   int status = gettimeofday(&time, NULL);
   964   assert(status != -1, "bsd error");
   965   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   966 }
   968 #ifndef CLOCK_MONOTONIC
   969 #define CLOCK_MONOTONIC (1)
   970 #endif
   972 #ifdef __APPLE__
   973 void os::Bsd::clock_init() {
   974         // XXXDARWIN: Investigate replacement monotonic clock
   975 }
   976 #else
   977 void os::Bsd::clock_init() {
   978   struct timespec res;
   979   struct timespec tp;
   980   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
   981       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
   982     // yes, monotonic clock is supported
   983     _clock_gettime = ::clock_gettime;
   984   }
   985 }
   986 #endif
   989 jlong os::javaTimeNanos() {
   990   if (Bsd::supports_monotonic_clock()) {
   991     struct timespec tp;
   992     int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
   993     assert(status == 0, "gettime error");
   994     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
   995     return result;
   996   } else {
   997     timeval time;
   998     int status = gettimeofday(&time, NULL);
   999     assert(status != -1, "bsd error");
  1000     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
  1001     return 1000 * usecs;
  1005 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
  1006   if (Bsd::supports_monotonic_clock()) {
  1007     info_ptr->max_value = ALL_64_BITS;
  1009     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
  1010     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
  1011     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
  1012   } else {
  1013     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
  1014     info_ptr->max_value = ALL_64_BITS;
  1016     // gettimeofday is a real time clock so it skips
  1017     info_ptr->may_skip_backward = true;
  1018     info_ptr->may_skip_forward = true;
  1021   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
  1024 // Return the real, user, and system times in seconds from an
  1025 // arbitrary fixed point in the past.
  1026 bool os::getTimesSecs(double* process_real_time,
  1027                       double* process_user_time,
  1028                       double* process_system_time) {
  1029   struct tms ticks;
  1030   clock_t real_ticks = times(&ticks);
  1032   if (real_ticks == (clock_t) (-1)) {
  1033     return false;
  1034   } else {
  1035     double ticks_per_second = (double) clock_tics_per_sec;
  1036     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
  1037     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
  1038     *process_real_time = ((double) real_ticks) / ticks_per_second;
  1040     return true;
  1045 char * os::local_time_string(char *buf, size_t buflen) {
  1046   struct tm t;
  1047   time_t long_time;
  1048   time(&long_time);
  1049   localtime_r(&long_time, &t);
  1050   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  1051                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
  1052                t.tm_hour, t.tm_min, t.tm_sec);
  1053   return buf;
  1056 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
  1057   return localtime_r(clock, res);
  1060 ////////////////////////////////////////////////////////////////////////////////
  1061 // runtime exit support
  1063 // Note: os::shutdown() might be called very early during initialization, or
  1064 // called from signal handler. Before adding something to os::shutdown(), make
  1065 // sure it is async-safe and can handle partially initialized VM.
  1066 void os::shutdown() {
  1068   // allow PerfMemory to attempt cleanup of any persistent resources
  1069   perfMemory_exit();
  1071   // needs to remove object in file system
  1072   AttachListener::abort();
  1074   // flush buffered output, finish log files
  1075   ostream_abort();
  1077   // Check for abort hook
  1078   abort_hook_t abort_hook = Arguments::abort_hook();
  1079   if (abort_hook != NULL) {
  1080     abort_hook();
  1085 // Note: os::abort() might be called very early during initialization, or
  1086 // called from signal handler. Before adding something to os::abort(), make
  1087 // sure it is async-safe and can handle partially initialized VM.
  1088 void os::abort(bool dump_core) {
  1089   os::shutdown();
  1090   if (dump_core) {
  1091 #ifndef PRODUCT
  1092     fdStream out(defaultStream::output_fd());
  1093     out.print_raw("Current thread is ");
  1094     char buf[16];
  1095     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
  1096     out.print_raw_cr(buf);
  1097     out.print_raw_cr("Dumping core ...");
  1098 #endif
  1099     ::abort(); // dump core
  1102   ::exit(1);
  1105 // Die immediately, no exit hook, no abort hook, no cleanup.
  1106 void os::die() {
  1107   // _exit() on BsdThreads only kills current thread
  1108   ::abort();
  1111 // unused on bsd for now.
  1112 void os::set_error_file(const char *logfile) {}
  1115 // This method is a copy of JDK's sysGetLastErrorString
  1116 // from src/solaris/hpi/src/system_md.c
  1118 size_t os::lasterror(char *buf, size_t len) {
  1120   if (errno == 0)  return 0;
  1122   const char *s = ::strerror(errno);
  1123   size_t n = ::strlen(s);
  1124   if (n >= len) {
  1125     n = len - 1;
  1127   ::strncpy(buf, s, n);
  1128   buf[n] = '\0';
  1129   return n;
  1132 intx os::current_thread_id() {
  1133 #ifdef __APPLE__
  1134   return (intx)::mach_thread_self();
  1135 #else
  1136   return (intx)::pthread_self();
  1137 #endif
  1139 int os::current_process_id() {
  1141   // Under the old bsd thread library, bsd gives each thread
  1142   // its own process id. Because of this each thread will return
  1143   // a different pid if this method were to return the result
  1144   // of getpid(2). Bsd provides no api that returns the pid
  1145   // of the launcher thread for the vm. This implementation
  1146   // returns a unique pid, the pid of the launcher thread
  1147   // that starts the vm 'process'.
  1149   // Under the NPTL, getpid() returns the same pid as the
  1150   // launcher thread rather than a unique pid per thread.
  1151   // Use gettid() if you want the old pre NPTL behaviour.
  1153   // if you are looking for the result of a call to getpid() that
  1154   // returns a unique pid for the calling thread, then look at the
  1155   // OSThread::thread_id() method in osThread_bsd.hpp file
  1157   return (int)(_initial_pid ? _initial_pid : getpid());
  1160 // DLL functions
  1162 #define JNI_LIB_PREFIX "lib"
  1163 #ifdef __APPLE__
  1164 #define JNI_LIB_SUFFIX ".dylib"
  1165 #else
  1166 #define JNI_LIB_SUFFIX ".so"
  1167 #endif
  1169 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1171 // This must be hard coded because it's the system's temporary
  1172 // directory not the java application's temp directory, ala java.io.tmpdir.
  1173 #ifdef __APPLE__
  1174 // macosx has a secure per-user temporary directory
  1175 char temp_path_storage[PATH_MAX];
  1176 const char* os::get_temp_directory() {
  1177   static char *temp_path = NULL;
  1178   if (temp_path == NULL) {
  1179     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
  1180     if (pathSize == 0 || pathSize > PATH_MAX) {
  1181       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
  1183     temp_path = temp_path_storage;
  1185   return temp_path;
  1187 #else /* __APPLE__ */
  1188 const char* os::get_temp_directory() { return "/tmp"; }
  1189 #endif /* __APPLE__ */
  1191 static bool file_exists(const char* filename) {
  1192   struct stat statbuf;
  1193   if (filename == NULL || strlen(filename) == 0) {
  1194     return false;
  1196   return os::stat(filename, &statbuf) == 0;
  1199 bool os::dll_build_name(char* buffer, size_t buflen,
  1200                         const char* pname, const char* fname) {
  1201   bool retval = false;
  1202   // Copied from libhpi
  1203   const size_t pnamelen = pname ? strlen(pname) : 0;
  1205   // Return error on buffer overflow.
  1206   if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
  1207     return retval;
  1210   if (pnamelen == 0) {
  1211     snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
  1212     retval = true;
  1213   } else if (strchr(pname, *os::path_separator()) != NULL) {
  1214     int n;
  1215     char** pelements = split_path(pname, &n);
  1216     for (int i = 0 ; i < n ; i++) {
  1217       // Really shouldn't be NULL, but check can't hurt
  1218       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1219         continue; // skip the empty path values
  1221       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1222           pelements[i], fname);
  1223       if (file_exists(buffer)) {
  1224         retval = true;
  1225         break;
  1228     // release the storage
  1229     for (int i = 0 ; i < n ; i++) {
  1230       if (pelements[i] != NULL) {
  1231         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
  1234     if (pelements != NULL) {
  1235       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
  1237   } else {
  1238     snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
  1239     retval = true;
  1241   return retval;
  1244 const char* os::get_current_directory(char *buf, int buflen) {
  1245   return getcwd(buf, buflen);
  1248 // check if addr is inside libjvm.so
  1249 bool os::address_is_in_vm(address addr) {
  1250   static address libjvm_base_addr;
  1251   Dl_info dlinfo;
  1253   if (libjvm_base_addr == NULL) {
  1254     dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
  1255     libjvm_base_addr = (address)dlinfo.dli_fbase;
  1256     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
  1259   if (dladdr((void *)addr, &dlinfo)) {
  1260     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
  1263   return false;
  1267 #define MACH_MAXSYMLEN 256
  1269 bool os::dll_address_to_function_name(address addr, char *buf,
  1270                                       int buflen, int *offset) {
  1271   Dl_info dlinfo;
  1272   char localbuf[MACH_MAXSYMLEN];
  1274   // dladdr will find names of dynamic functions only, but does
  1275   // it set dli_fbase with mach_header address when it "fails" ?
  1276   if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
  1277     if (buf != NULL) {
  1278       if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1279         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
  1282     if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1283     return true;
  1284   } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
  1285     if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1286        buf, buflen, offset, dlinfo.dli_fname)) {
  1287        return true;
  1291   // Handle non-dymanic manually:
  1292   if (dlinfo.dli_fbase != NULL &&
  1293       Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) {
  1294     if(!Decoder::demangle(localbuf, buf, buflen)) {
  1295       jio_snprintf(buf, buflen, "%s", localbuf);
  1297     return true;
  1299   if (buf != NULL) buf[0] = '\0';
  1300   if (offset != NULL) *offset = -1;
  1301   return false;
  1304 // ported from solaris version
  1305 bool os::dll_address_to_library_name(address addr, char* buf,
  1306                                      int buflen, int* offset) {
  1307   Dl_info dlinfo;
  1309   if (dladdr((void*)addr, &dlinfo)){
  1310      if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
  1311      if (offset) *offset = addr - (address)dlinfo.dli_fbase;
  1312      return true;
  1313   } else {
  1314      if (buf) buf[0] = '\0';
  1315      if (offset) *offset = -1;
  1316      return false;
  1320 // Loads .dll/.so and
  1321 // in case of error it checks if .dll/.so was built for the
  1322 // same architecture as Hotspot is running on
  1324 #ifdef __APPLE__
  1325 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
  1326   void * result= ::dlopen(filename, RTLD_LAZY);
  1327   if (result != NULL) {
  1328     // Successful loading
  1329     return result;
  1332   // Read system error message into ebuf
  1333   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1334   ebuf[ebuflen-1]='\0';
  1336   return NULL;
  1338 #else
  1339 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1341   void * result= ::dlopen(filename, RTLD_LAZY);
  1342   if (result != NULL) {
  1343     // Successful loading
  1344     return result;
  1347   Elf32_Ehdr elf_head;
  1349   // Read system error message into ebuf
  1350   // It may or may not be overwritten below
  1351   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1352   ebuf[ebuflen-1]='\0';
  1353   int diag_msg_max_length=ebuflen-strlen(ebuf);
  1354   char* diag_msg_buf=ebuf+strlen(ebuf);
  1356   if (diag_msg_max_length==0) {
  1357     // No more space in ebuf for additional diagnostics message
  1358     return NULL;
  1362   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
  1364   if (file_descriptor < 0) {
  1365     // Can't open library, report dlerror() message
  1366     return NULL;
  1369   bool failed_to_read_elf_head=
  1370     (sizeof(elf_head)!=
  1371         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
  1373   ::close(file_descriptor);
  1374   if (failed_to_read_elf_head) {
  1375     // file i/o error - report dlerror() msg
  1376     return NULL;
  1379   typedef struct {
  1380     Elf32_Half  code;         // Actual value as defined in elf.h
  1381     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
  1382     char        elf_class;    // 32 or 64 bit
  1383     char        endianess;    // MSB or LSB
  1384     char*       name;         // String representation
  1385   } arch_t;
  1387   #ifndef EM_486
  1388   #define EM_486          6               /* Intel 80486 */
  1389   #endif
  1391   #ifndef EM_MIPS_RS3_LE
  1392   #define EM_MIPS_RS3_LE  10              /* MIPS */
  1393   #endif
  1395   #ifndef EM_PPC64
  1396   #define EM_PPC64        21              /* PowerPC64 */
  1397   #endif
  1399   #ifndef EM_S390
  1400   #define EM_S390         22              /* IBM System/390 */
  1401   #endif
  1403   #ifndef EM_IA_64
  1404   #define EM_IA_64        50              /* HP/Intel IA-64 */
  1405   #endif
  1407   #ifndef EM_X86_64
  1408   #define EM_X86_64       62              /* AMD x86-64 */
  1409   #endif
  1411   static const arch_t arch_array[]={
  1412     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1413     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1414     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
  1415     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
  1416     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1417     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1418     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
  1419     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
  1420     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
  1421     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
  1422     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
  1423     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
  1424     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
  1425     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
  1426     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1427     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1428   };
  1430   #if  (defined IA32)
  1431     static  Elf32_Half running_arch_code=EM_386;
  1432   #elif   (defined AMD64)
  1433     static  Elf32_Half running_arch_code=EM_X86_64;
  1434   #elif  (defined IA64)
  1435     static  Elf32_Half running_arch_code=EM_IA_64;
  1436   #elif  (defined __sparc) && (defined _LP64)
  1437     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1438   #elif  (defined __sparc) && (!defined _LP64)
  1439     static  Elf32_Half running_arch_code=EM_SPARC;
  1440   #elif  (defined __powerpc64__)
  1441     static  Elf32_Half running_arch_code=EM_PPC64;
  1442   #elif  (defined __powerpc__)
  1443     static  Elf32_Half running_arch_code=EM_PPC;
  1444   #elif  (defined ARM)
  1445     static  Elf32_Half running_arch_code=EM_ARM;
  1446   #elif  (defined S390)
  1447     static  Elf32_Half running_arch_code=EM_S390;
  1448   #elif  (defined ALPHA)
  1449     static  Elf32_Half running_arch_code=EM_ALPHA;
  1450   #elif  (defined MIPSEL)
  1451     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1452   #elif  (defined PARISC)
  1453     static  Elf32_Half running_arch_code=EM_PARISC;
  1454   #elif  (defined MIPS)
  1455     static  Elf32_Half running_arch_code=EM_MIPS;
  1456   #elif  (defined M68K)
  1457     static  Elf32_Half running_arch_code=EM_68K;
  1458   #else
  1459     #error Method os::dll_load requires that one of following is defined:\
  1460          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1461   #endif
  1463   // Identify compatability class for VM's architecture and library's architecture
  1464   // Obtain string descriptions for architectures
  1466   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
  1467   int running_arch_index=-1;
  1469   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
  1470     if (running_arch_code == arch_array[i].code) {
  1471       running_arch_index    = i;
  1473     if (lib_arch.code == arch_array[i].code) {
  1474       lib_arch.compat_class = arch_array[i].compat_class;
  1475       lib_arch.name         = arch_array[i].name;
  1479   assert(running_arch_index != -1,
  1480     "Didn't find running architecture code (running_arch_code) in arch_array");
  1481   if (running_arch_index == -1) {
  1482     // Even though running architecture detection failed
  1483     // we may still continue with reporting dlerror() message
  1484     return NULL;
  1487   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
  1488     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
  1489     return NULL;
  1492 #ifndef S390
  1493   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
  1494     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
  1495     return NULL;
  1497 #endif // !S390
  1499   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1500     if ( lib_arch.name!=NULL ) {
  1501       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1502         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1503         lib_arch.name, arch_array[running_arch_index].name);
  1504     } else {
  1505       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1506       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1507         lib_arch.code,
  1508         arch_array[running_arch_index].name);
  1512   return NULL;
  1514 #endif /* !__APPLE__ */
  1516 // XXX: Do we need a lock around this as per Linux?
  1517 void* os::dll_lookup(void* handle, const char* name) {
  1518   return dlsym(handle, name);
  1522 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1523   int fd = ::open(filename, O_RDONLY);
  1524   if (fd == -1) {
  1525      return false;
  1528   char buf[32];
  1529   int bytes;
  1530   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1531     st->print_raw(buf, bytes);
  1534   ::close(fd);
  1536   return true;
  1539 void os::print_dll_info(outputStream *st) {
  1540    st->print_cr("Dynamic libraries:");
  1541 #ifdef RTLD_DI_LINKMAP
  1542     Dl_info dli;
  1543     void *handle;
  1544     Link_map *map;
  1545     Link_map *p;
  1547     if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) {
  1548         st->print_cr("Error: Cannot print dynamic libraries.");
  1549         return;
  1551     handle = dlopen(dli.dli_fname, RTLD_LAZY);
  1552     if (handle == NULL) {
  1553         st->print_cr("Error: Cannot print dynamic libraries.");
  1554         return;
  1556     dlinfo(handle, RTLD_DI_LINKMAP, &map);
  1557     if (map == NULL) {
  1558         st->print_cr("Error: Cannot print dynamic libraries.");
  1559         return;
  1562     while (map->l_prev != NULL)
  1563         map = map->l_prev;
  1565     while (map != NULL) {
  1566         st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
  1567         map = map->l_next;
  1570     dlclose(handle);
  1571 #elif defined(__APPLE__)
  1572     uint32_t count;
  1573     uint32_t i;
  1575     count = _dyld_image_count();
  1576     for (i = 1; i < count; i++) {
  1577         const char *name = _dyld_get_image_name(i);
  1578         intptr_t slide = _dyld_get_image_vmaddr_slide(i);
  1579         st->print_cr(PTR_FORMAT " \t%s", slide, name);
  1581 #else
  1582    st->print_cr("Error: Cannot print dynamic libraries.");
  1583 #endif
  1586 void os::print_os_info_brief(outputStream* st) {
  1587   st->print("Bsd");
  1589   os::Posix::print_uname_info(st);
  1592 void os::print_os_info(outputStream* st) {
  1593   st->print("OS:");
  1594   st->print("Bsd");
  1596   os::Posix::print_uname_info(st);
  1598   os::Posix::print_rlimit_info(st);
  1600   os::Posix::print_load_average(st);
  1603 void os::pd_print_cpu_info(outputStream* st) {
  1604   // Nothing to do for now.
  1607 void os::print_memory_info(outputStream* st) {
  1609   st->print("Memory:");
  1610   st->print(" %dk page", os::vm_page_size()>>10);
  1612   st->print(", physical " UINT64_FORMAT "k",
  1613             os::physical_memory() >> 10);
  1614   st->print("(" UINT64_FORMAT "k free)",
  1615             os::available_memory() >> 10);
  1616   st->cr();
  1618   // meminfo
  1619   st->print("\n/proc/meminfo:\n");
  1620   _print_ascii_file("/proc/meminfo", st);
  1621   st->cr();
  1624 // Taken from /usr/include/bits/siginfo.h  Supposed to be architecture specific
  1625 // but they're the same for all the bsd arch that we support
  1626 // and they're the same for solaris but there's no common place to put this.
  1627 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
  1628                           "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
  1629                           "ILL_COPROC", "ILL_BADSTK" };
  1631 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
  1632                           "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
  1633                           "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
  1635 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
  1637 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
  1639 void os::print_siginfo(outputStream* st, void* siginfo) {
  1640   st->print("siginfo:");
  1642   const int buflen = 100;
  1643   char buf[buflen];
  1644   siginfo_t *si = (siginfo_t*)siginfo;
  1645   st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
  1646   if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
  1647     st->print("si_errno=%s", buf);
  1648   } else {
  1649     st->print("si_errno=%d", si->si_errno);
  1651   const int c = si->si_code;
  1652   assert(c > 0, "unexpected si_code");
  1653   switch (si->si_signo) {
  1654   case SIGILL:
  1655     st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
  1656     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1657     break;
  1658   case SIGFPE:
  1659     st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
  1660     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1661     break;
  1662   case SIGSEGV:
  1663     st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
  1664     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1665     break;
  1666   case SIGBUS:
  1667     st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
  1668     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1669     break;
  1670   default:
  1671     st->print(", si_code=%d", si->si_code);
  1672     // no si_addr
  1675   if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
  1676       UseSharedSpaces) {
  1677     FileMapInfo* mapinfo = FileMapInfo::current_info();
  1678     if (mapinfo->is_in_shared_space(si->si_addr)) {
  1679       st->print("\n\nError accessing class data sharing archive."   \
  1680                 " Mapped file inaccessible during execution, "      \
  1681                 " possible disk/network problem.");
  1684   st->cr();
  1688 static void print_signal_handler(outputStream* st, int sig,
  1689                                  char* buf, size_t buflen);
  1691 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  1692   st->print_cr("Signal Handlers:");
  1693   print_signal_handler(st, SIGSEGV, buf, buflen);
  1694   print_signal_handler(st, SIGBUS , buf, buflen);
  1695   print_signal_handler(st, SIGFPE , buf, buflen);
  1696   print_signal_handler(st, SIGPIPE, buf, buflen);
  1697   print_signal_handler(st, SIGXFSZ, buf, buflen);
  1698   print_signal_handler(st, SIGILL , buf, buflen);
  1699   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
  1700   print_signal_handler(st, SR_signum, buf, buflen);
  1701   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
  1702   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
  1703   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
  1704   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
  1707 static char saved_jvm_path[MAXPATHLEN] = {0};
  1709 // Find the full path to the current module, libjvm
  1710 void os::jvm_path(char *buf, jint buflen) {
  1711   // Error checking.
  1712   if (buflen < MAXPATHLEN) {
  1713     assert(false, "must use a large-enough buffer");
  1714     buf[0] = '\0';
  1715     return;
  1717   // Lazy resolve the path to current module.
  1718   if (saved_jvm_path[0] != 0) {
  1719     strcpy(buf, saved_jvm_path);
  1720     return;
  1723   char dli_fname[MAXPATHLEN];
  1724   bool ret = dll_address_to_library_name(
  1725                 CAST_FROM_FN_PTR(address, os::jvm_path),
  1726                 dli_fname, sizeof(dli_fname), NULL);
  1727   assert(ret != 0, "cannot locate libjvm");
  1728   char *rp = realpath(dli_fname, buf);
  1729   if (rp == NULL)
  1730     return;
  1732   if (Arguments::created_by_gamma_launcher()) {
  1733     // Support for the gamma launcher.  Typical value for buf is
  1734     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm".  If "/jre/lib/" appears at
  1735     // the right place in the string, then assume we are installed in a JDK and
  1736     // we're done.  Otherwise, check for a JAVA_HOME environment variable and
  1737     // construct a path to the JVM being overridden.
  1739     const char *p = buf + strlen(buf) - 1;
  1740     for (int count = 0; p > buf && count < 5; ++count) {
  1741       for (--p; p > buf && *p != '/'; --p)
  1742         /* empty */ ;
  1745     if (strncmp(p, "/jre/lib/", 9) != 0) {
  1746       // Look for JAVA_HOME in the environment.
  1747       char* java_home_var = ::getenv("JAVA_HOME");
  1748       if (java_home_var != NULL && java_home_var[0] != 0) {
  1749         char* jrelib_p;
  1750         int len;
  1752         // Check the current module name "libjvm"
  1753         p = strrchr(buf, '/');
  1754         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1756         rp = realpath(java_home_var, buf);
  1757         if (rp == NULL)
  1758           return;
  1760         // determine if this is a legacy image or modules image
  1761         // modules image doesn't have "jre" subdirectory
  1762         len = strlen(buf);
  1763         jrelib_p = buf + len;
  1765         // Add the appropriate library subdir
  1766         snprintf(jrelib_p, buflen-len, "/jre/lib");
  1767         if (0 != access(buf, F_OK)) {
  1768           snprintf(jrelib_p, buflen-len, "/lib");
  1771         // Add the appropriate client or server subdir
  1772         len = strlen(buf);
  1773         jrelib_p = buf + len;
  1774         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
  1775         if (0 != access(buf, F_OK)) {
  1776           snprintf(jrelib_p, buflen-len, "");
  1779         // If the path exists within JAVA_HOME, add the JVM library name
  1780         // to complete the path to JVM being overridden.  Otherwise fallback
  1781         // to the path to the current library.
  1782         if (0 == access(buf, F_OK)) {
  1783           // Use current module name "libjvm"
  1784           len = strlen(buf);
  1785           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1786         } else {
  1787           // Fall back to path of current library
  1788           rp = realpath(dli_fname, buf);
  1789           if (rp == NULL)
  1790             return;
  1796   strcpy(saved_jvm_path, buf);
  1799 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  1800   // no prefix required, not even "_"
  1803 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  1804   // no suffix required
  1807 ////////////////////////////////////////////////////////////////////////////////
  1808 // sun.misc.Signal support
  1810 static volatile jint sigint_count = 0;
  1812 static void
  1813 UserHandler(int sig, void *siginfo, void *context) {
  1814   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1815   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1816   // don't want to flood the manager thread with sem_post requests.
  1817   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1818       return;
  1820   // Ctrl-C is pressed during error reporting, likely because the error
  1821   // handler fails to abort. Let VM die immediately.
  1822   if (sig == SIGINT && is_error_reported()) {
  1823      os::die();
  1826   os::signal_notify(sig);
  1829 void* os::user_handler() {
  1830   return CAST_FROM_FN_PTR(void*, UserHandler);
  1833 extern "C" {
  1834   typedef void (*sa_handler_t)(int);
  1835   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  1838 void* os::signal(int signal_number, void* handler) {
  1839   struct sigaction sigAct, oldSigAct;
  1841   sigfillset(&(sigAct.sa_mask));
  1842   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
  1843   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
  1845   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
  1846     // -1 means registration failed
  1847     return (void *)-1;
  1850   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
  1853 void os::signal_raise(int signal_number) {
  1854   ::raise(signal_number);
  1857 /*
  1858  * The following code is moved from os.cpp for making this
  1859  * code platform specific, which it is by its very nature.
  1860  */
  1862 // Will be modified when max signal is changed to be dynamic
  1863 int os::sigexitnum_pd() {
  1864   return NSIG;
  1867 // a counter for each possible signal value
  1868 static volatile jint pending_signals[NSIG+1] = { 0 };
  1870 // Bsd(POSIX) specific hand shaking semaphore.
  1871 #ifdef __APPLE__
  1872 static semaphore_t sig_sem;
  1873 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1874 #define SEM_WAIT(sem)           semaphore_wait(sem);
  1875 #define SEM_POST(sem)           semaphore_signal(sem);
  1876 #else
  1877 static sem_t sig_sem;
  1878 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1879 #define SEM_WAIT(sem)           sem_wait(&sem);
  1880 #define SEM_POST(sem)           sem_post(&sem);
  1881 #endif
  1883 void os::signal_init_pd() {
  1884   // Initialize signal structures
  1885   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
  1887   // Initialize signal semaphore
  1888   ::SEM_INIT(sig_sem, 0);
  1891 void os::signal_notify(int sig) {
  1892   Atomic::inc(&pending_signals[sig]);
  1893   ::SEM_POST(sig_sem);
  1896 static int check_pending_signals(bool wait) {
  1897   Atomic::store(0, &sigint_count);
  1898   for (;;) {
  1899     for (int i = 0; i < NSIG + 1; i++) {
  1900       jint n = pending_signals[i];
  1901       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  1902         return i;
  1905     if (!wait) {
  1906       return -1;
  1908     JavaThread *thread = JavaThread::current();
  1909     ThreadBlockInVM tbivm(thread);
  1911     bool threadIsSuspended;
  1912     do {
  1913       thread->set_suspend_equivalent();
  1914       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  1915       ::SEM_WAIT(sig_sem);
  1917       // were we externally suspended while we were waiting?
  1918       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  1919       if (threadIsSuspended) {
  1920         //
  1921         // The semaphore has been incremented, but while we were waiting
  1922         // another thread suspended us. We don't want to continue running
  1923         // while suspended because that would surprise the thread that
  1924         // suspended us.
  1925         //
  1926         ::SEM_POST(sig_sem);
  1928         thread->java_suspend_self();
  1930     } while (threadIsSuspended);
  1934 int os::signal_lookup() {
  1935   return check_pending_signals(false);
  1938 int os::signal_wait() {
  1939   return check_pending_signals(true);
  1942 ////////////////////////////////////////////////////////////////////////////////
  1943 // Virtual Memory
  1945 int os::vm_page_size() {
  1946   // Seems redundant as all get out
  1947   assert(os::Bsd::page_size() != -1, "must call os::init");
  1948   return os::Bsd::page_size();
  1951 // Solaris allocates memory by pages.
  1952 int os::vm_allocation_granularity() {
  1953   assert(os::Bsd::page_size() != -1, "must call os::init");
  1954   return os::Bsd::page_size();
  1957 // Rationale behind this function:
  1958 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
  1959 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
  1960 //  samples for JITted code. Here we create private executable mapping over the code cache
  1961 //  and then we can use standard (well, almost, as mapping can change) way to provide
  1962 //  info for the reporting script by storing timestamp and location of symbol
  1963 void bsd_wrap_code(char* base, size_t size) {
  1964   static volatile jint cnt = 0;
  1966   if (!UseOprofile) {
  1967     return;
  1970   char buf[PATH_MAX + 1];
  1971   int num = Atomic::add(1, &cnt);
  1973   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
  1974            os::get_temp_directory(), os::current_process_id(), num);
  1975   unlink(buf);
  1977   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
  1979   if (fd != -1) {
  1980     off_t rv = ::lseek(fd, size-2, SEEK_SET);
  1981     if (rv != (off_t)-1) {
  1982       if (::write(fd, "", 1) == 1) {
  1983         mmap(base, size,
  1984              PROT_READ|PROT_WRITE|PROT_EXEC,
  1985              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
  1988     ::close(fd);
  1989     unlink(buf);
  1993 // NOTE: Bsd kernel does not really reserve the pages for us.
  1994 //       All it does is to check if there are enough free pages
  1995 //       left at the time of mmap(). This could be a potential
  1996 //       problem.
  1997 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
  1998   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
  1999 #ifdef __OpenBSD__
  2000   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2001   return ::mprotect(addr, size, prot) == 0;
  2002 #else
  2003   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2004                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2005   return res != (uintptr_t) MAP_FAILED;
  2006 #endif
  2010 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2011                        bool exec) {
  2012   return commit_memory(addr, size, exec);
  2015 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2018 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2019   ::madvise(addr, bytes, MADV_DONTNEED);
  2022 void os::numa_make_global(char *addr, size_t bytes) {
  2025 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
  2028 bool os::numa_topology_changed()   { return false; }
  2030 size_t os::numa_get_groups_num() {
  2031   return 1;
  2034 int os::numa_get_group_id() {
  2035   return 0;
  2038 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2039   if (size > 0) {
  2040     ids[0] = 0;
  2041     return 1;
  2043   return 0;
  2046 bool os::get_page_info(char *start, page_info* info) {
  2047   return false;
  2050 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2051   return end;
  2055 bool os::pd_uncommit_memory(char* addr, size_t size) {
  2056 #ifdef __OpenBSD__
  2057   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2058   return ::mprotect(addr, size, PROT_NONE) == 0;
  2059 #else
  2060   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2061                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2062   return res  != (uintptr_t) MAP_FAILED;
  2063 #endif
  2066 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2067   return os::commit_memory(addr, size);
  2070 // If this is a growable mapping, remove the guard pages entirely by
  2071 // munmap()ping them.  If not, just call uncommit_memory().
  2072 bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2073   return os::uncommit_memory(addr, size);
  2076 static address _highest_vm_reserved_address = NULL;
  2078 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
  2079 // at 'requested_addr'. If there are existing memory mappings at the same
  2080 // location, however, they will be overwritten. If 'fixed' is false,
  2081 // 'requested_addr' is only treated as a hint, the return value may or
  2082 // may not start from the requested address. Unlike Bsd mmap(), this
  2083 // function returns NULL to indicate failure.
  2084 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
  2085   char * addr;
  2086   int flags;
  2088   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
  2089   if (fixed) {
  2090     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
  2091     flags |= MAP_FIXED;
  2094   // Map uncommitted pages PROT_READ and PROT_WRITE, change access
  2095   // to PROT_EXEC if executable when we commit the page.
  2096   addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
  2097                        flags, -1, 0);
  2099   if (addr != MAP_FAILED) {
  2100     // anon_mmap() should only get called during VM initialization,
  2101     // don't need lock (actually we can skip locking even it can be called
  2102     // from multiple threads, because _highest_vm_reserved_address is just a
  2103     // hint about the upper limit of non-stack memory regions.)
  2104     if ((address)addr + bytes > _highest_vm_reserved_address) {
  2105       _highest_vm_reserved_address = (address)addr + bytes;
  2109   return addr == MAP_FAILED ? NULL : addr;
  2112 // Don't update _highest_vm_reserved_address, because there might be memory
  2113 // regions above addr + size. If so, releasing a memory region only creates
  2114 // a hole in the address space, it doesn't help prevent heap-stack collision.
  2115 //
  2116 static int anon_munmap(char * addr, size_t size) {
  2117   return ::munmap(addr, size) == 0;
  2120 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2121                          size_t alignment_hint) {
  2122   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2125 bool os::pd_release_memory(char* addr, size_t size) {
  2126   return anon_munmap(addr, size);
  2129 static address highest_vm_reserved_address() {
  2130   return _highest_vm_reserved_address;
  2133 static bool bsd_mprotect(char* addr, size_t size, int prot) {
  2134   // Bsd wants the mprotect address argument to be page aligned.
  2135   char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
  2137   // According to SUSv3, mprotect() should only be used with mappings
  2138   // established by mmap(), and mmap() always maps whole pages. Unaligned
  2139   // 'addr' likely indicates problem in the VM (e.g. trying to change
  2140   // protection of malloc'ed or statically allocated memory). Check the
  2141   // caller if you hit this assert.
  2142   assert(addr == bottom, "sanity check");
  2144   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
  2145   return ::mprotect(bottom, size, prot) == 0;
  2148 // Set protections specified
  2149 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  2150                         bool is_committed) {
  2151   unsigned int p = 0;
  2152   switch (prot) {
  2153   case MEM_PROT_NONE: p = PROT_NONE; break;
  2154   case MEM_PROT_READ: p = PROT_READ; break;
  2155   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
  2156   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
  2157   default:
  2158     ShouldNotReachHere();
  2160   // is_committed is unused.
  2161   return bsd_mprotect(addr, bytes, p);
  2164 bool os::guard_memory(char* addr, size_t size) {
  2165   return bsd_mprotect(addr, size, PROT_NONE);
  2168 bool os::unguard_memory(char* addr, size_t size) {
  2169   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
  2172 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
  2173   return false;
  2176 /*
  2177 * Set the coredump_filter bits to include largepages in core dump (bit 6)
  2179 * From the coredump_filter documentation:
  2181 * - (bit 0) anonymous private memory
  2182 * - (bit 1) anonymous shared memory
  2183 * - (bit 2) file-backed private memory
  2184 * - (bit 3) file-backed shared memory
  2185 * - (bit 4) ELF header pages in file-backed private memory areas (it is
  2186 *           effective only if the bit 2 is cleared)
  2187 * - (bit 5) hugetlb private memory
  2188 * - (bit 6) hugetlb shared memory
  2189 */
  2190 static void set_coredump_filter(void) {
  2191   FILE *f;
  2192   long cdm;
  2194   if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
  2195     return;
  2198   if (fscanf(f, "%lx", &cdm) != 1) {
  2199     fclose(f);
  2200     return;
  2203   rewind(f);
  2205   if ((cdm & LARGEPAGES_BIT) == 0) {
  2206     cdm |= LARGEPAGES_BIT;
  2207     fprintf(f, "%#lx", cdm);
  2210   fclose(f);
  2213 // Large page support
  2215 static size_t _large_page_size = 0;
  2217 void os::large_page_init() {
  2221 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
  2222   // "exec" is passed in but not used.  Creating the shared image for
  2223   // the code cache doesn't have an SHM_X executable permission to check.
  2224   assert(UseLargePages && UseSHM, "only for SHM large pages");
  2226   key_t key = IPC_PRIVATE;
  2227   char *addr;
  2229   bool warn_on_failure = UseLargePages &&
  2230                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2231                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2232                         );
  2233   char msg[128];
  2235   // Create a large shared memory region to attach to based on size.
  2236   // Currently, size is the total size of the heap
  2237   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2238   if (shmid == -1) {
  2239      // Possible reasons for shmget failure:
  2240      // 1. shmmax is too small for Java heap.
  2241      //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2242      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2243      // 2. not enough large page memory.
  2244      //    > check available large pages: cat /proc/meminfo
  2245      //    > increase amount of large pages:
  2246      //          echo new_value > /proc/sys/vm/nr_hugepages
  2247      //      Note 1: different Bsd may use different name for this property,
  2248      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2249      //      Note 2: it's possible there's enough physical memory available but
  2250      //            they are so fragmented after a long run that they can't
  2251      //            coalesce into large pages. Try to reserve large pages when
  2252      //            the system is still "fresh".
  2253      if (warn_on_failure) {
  2254        jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
  2255        warning(msg);
  2257      return NULL;
  2260   // attach to the region
  2261   addr = (char*)shmat(shmid, req_addr, 0);
  2262   int err = errno;
  2264   // Remove shmid. If shmat() is successful, the actual shared memory segment
  2265   // will be deleted when it's detached by shmdt() or when the process
  2266   // terminates. If shmat() is not successful this will remove the shared
  2267   // segment immediately.
  2268   shmctl(shmid, IPC_RMID, NULL);
  2270   if ((intptr_t)addr == -1) {
  2271      if (warn_on_failure) {
  2272        jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
  2273        warning(msg);
  2275      return NULL;
  2278   return addr;
  2281 bool os::release_memory_special(char* base, size_t bytes) {
  2282   // detaching the SHM segment will also delete it, see reserve_memory_special()
  2283   int rslt = shmdt(base);
  2284   return rslt == 0;
  2287 size_t os::large_page_size() {
  2288   return _large_page_size;
  2291 // HugeTLBFS allows application to commit large page memory on demand;
  2292 // with SysV SHM the entire memory region must be allocated as shared
  2293 // memory.
  2294 bool os::can_commit_large_page_memory() {
  2295   return UseHugeTLBFS;
  2298 bool os::can_execute_large_page_memory() {
  2299   return UseHugeTLBFS;
  2302 // Reserve memory at an arbitrary address, only if that area is
  2303 // available (and not reserved for something else).
  2305 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2306   const int max_tries = 10;
  2307   char* base[max_tries];
  2308   size_t size[max_tries];
  2309   const size_t gap = 0x000000;
  2311   // Assert only that the size is a multiple of the page size, since
  2312   // that's all that mmap requires, and since that's all we really know
  2313   // about at this low abstraction level.  If we need higher alignment,
  2314   // we can either pass an alignment to this method or verify alignment
  2315   // in one of the methods further up the call chain.  See bug 5044738.
  2316   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
  2318   // Repeatedly allocate blocks until the block is allocated at the
  2319   // right spot. Give up after max_tries. Note that reserve_memory() will
  2320   // automatically update _highest_vm_reserved_address if the call is
  2321   // successful. The variable tracks the highest memory address every reserved
  2322   // by JVM. It is used to detect heap-stack collision if running with
  2323   // fixed-stack BsdThreads. Because here we may attempt to reserve more
  2324   // space than needed, it could confuse the collision detecting code. To
  2325   // solve the problem, save current _highest_vm_reserved_address and
  2326   // calculate the correct value before return.
  2327   address old_highest = _highest_vm_reserved_address;
  2329   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2330   // if kernel honors the hint then we can return immediately.
  2331   char * addr = anon_mmap(requested_addr, bytes, false);
  2332   if (addr == requested_addr) {
  2333      return requested_addr;
  2336   if (addr != NULL) {
  2337      // mmap() is successful but it fails to reserve at the requested address
  2338      anon_munmap(addr, bytes);
  2341   int i;
  2342   for (i = 0; i < max_tries; ++i) {
  2343     base[i] = reserve_memory(bytes);
  2345     if (base[i] != NULL) {
  2346       // Is this the block we wanted?
  2347       if (base[i] == requested_addr) {
  2348         size[i] = bytes;
  2349         break;
  2352       // Does this overlap the block we wanted? Give back the overlapped
  2353       // parts and try again.
  2355       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
  2356       if (top_overlap >= 0 && top_overlap < bytes) {
  2357         unmap_memory(base[i], top_overlap);
  2358         base[i] += top_overlap;
  2359         size[i] = bytes - top_overlap;
  2360       } else {
  2361         size_t bottom_overlap = base[i] + bytes - requested_addr;
  2362         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
  2363           unmap_memory(requested_addr, bottom_overlap);
  2364           size[i] = bytes - bottom_overlap;
  2365         } else {
  2366           size[i] = bytes;
  2372   // Give back the unused reserved pieces.
  2374   for (int j = 0; j < i; ++j) {
  2375     if (base[j] != NULL) {
  2376       unmap_memory(base[j], size[j]);
  2380   if (i < max_tries) {
  2381     _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
  2382     return requested_addr;
  2383   } else {
  2384     _highest_vm_reserved_address = old_highest;
  2385     return NULL;
  2389 size_t os::read(int fd, void *buf, unsigned int nBytes) {
  2390   RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
  2393 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
  2394 // Solaris uses poll(), bsd uses park().
  2395 // Poll() is likely a better choice, assuming that Thread.interrupt()
  2396 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
  2397 // SIGSEGV, see 4355769.
  2399 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  2400   assert(thread == Thread::current(),  "thread consistency check");
  2402   ParkEvent * const slp = thread->_SleepEvent ;
  2403   slp->reset() ;
  2404   OrderAccess::fence() ;
  2406   if (interruptible) {
  2407     jlong prevtime = javaTimeNanos();
  2409     for (;;) {
  2410       if (os::is_interrupted(thread, true)) {
  2411         return OS_INTRPT;
  2414       jlong newtime = javaTimeNanos();
  2416       if (newtime - prevtime < 0) {
  2417         // time moving backwards, should only happen if no monotonic clock
  2418         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2419         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2420       } else {
  2421         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2424       if(millis <= 0) {
  2425         return OS_OK;
  2428       prevtime = newtime;
  2431         assert(thread->is_Java_thread(), "sanity check");
  2432         JavaThread *jt = (JavaThread *) thread;
  2433         ThreadBlockInVM tbivm(jt);
  2434         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
  2436         jt->set_suspend_equivalent();
  2437         // cleared by handle_special_suspend_equivalent_condition() or
  2438         // java_suspend_self() via check_and_wait_while_suspended()
  2440         slp->park(millis);
  2442         // were we externally suspended while we were waiting?
  2443         jt->check_and_wait_while_suspended();
  2446   } else {
  2447     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  2448     jlong prevtime = javaTimeNanos();
  2450     for (;;) {
  2451       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
  2452       // the 1st iteration ...
  2453       jlong newtime = javaTimeNanos();
  2455       if (newtime - prevtime < 0) {
  2456         // time moving backwards, should only happen if no monotonic clock
  2457         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2458         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2459       } else {
  2460         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2463       if(millis <= 0) break ;
  2465       prevtime = newtime;
  2466       slp->park(millis);
  2468     return OS_OK ;
  2472 int os::naked_sleep() {
  2473   // %% make the sleep time an integer flag. for now use 1 millisec.
  2474   return os::sleep(Thread::current(), 1, false);
  2477 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  2478 void os::infinite_sleep() {
  2479   while (true) {    // sleep forever ...
  2480     ::sleep(100);   // ... 100 seconds at a time
  2484 // Used to convert frequent JVM_Yield() to nops
  2485 bool os::dont_yield() {
  2486   return DontYieldALot;
  2489 void os::yield() {
  2490   sched_yield();
  2493 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
  2495 void os::yield_all(int attempts) {
  2496   // Yields to all threads, including threads with lower priorities
  2497   // Threads on Bsd are all with same priority. The Solaris style
  2498   // os::yield_all() with nanosleep(1ms) is not necessary.
  2499   sched_yield();
  2502 // Called from the tight loops to possibly influence time-sharing heuristics
  2503 void os::loop_breaker(int attempts) {
  2504   os::yield_all(attempts);
  2507 ////////////////////////////////////////////////////////////////////////////////
  2508 // thread priority support
  2510 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
  2511 // only supports dynamic priority, static priority must be zero. For real-time
  2512 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
  2513 // However, for large multi-threaded applications, SCHED_RR is not only slower
  2514 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
  2515 // of 5 runs - Sep 2005).
  2516 //
  2517 // The following code actually changes the niceness of kernel-thread/LWP. It
  2518 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
  2519 // not the entire user process, and user level threads are 1:1 mapped to kernel
  2520 // threads. It has always been the case, but could change in the future. For
  2521 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
  2522 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
  2524 #if !defined(__APPLE__)
  2525 int os::java_to_os_priority[CriticalPriority + 1] = {
  2526   19,              // 0 Entry should never be used
  2528    0,              // 1 MinPriority
  2529    3,              // 2
  2530    6,              // 3
  2532   10,              // 4
  2533   15,              // 5 NormPriority
  2534   18,              // 6
  2536   21,              // 7
  2537   25,              // 8
  2538   28,              // 9 NearMaxPriority
  2540   31,              // 10 MaxPriority
  2542   31               // 11 CriticalPriority
  2543 };
  2544 #else
  2545 /* Using Mach high-level priority assignments */
  2546 int os::java_to_os_priority[CriticalPriority + 1] = {
  2547    0,              // 0 Entry should never be used (MINPRI_USER)
  2549   27,              // 1 MinPriority
  2550   28,              // 2
  2551   29,              // 3
  2553   30,              // 4
  2554   31,              // 5 NormPriority (BASEPRI_DEFAULT)
  2555   32,              // 6
  2557   33,              // 7
  2558   34,              // 8
  2559   35,              // 9 NearMaxPriority
  2561   36,              // 10 MaxPriority
  2563   36               // 11 CriticalPriority
  2564 };
  2565 #endif
  2567 static int prio_init() {
  2568   if (ThreadPriorityPolicy == 1) {
  2569     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
  2570     // if effective uid is not root. Perhaps, a more elegant way of doing
  2571     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
  2572     if (geteuid() != 0) {
  2573       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
  2574         warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
  2576       ThreadPriorityPolicy = 0;
  2579   if (UseCriticalJavaThreadPriority) {
  2580     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
  2582   return 0;
  2585 OSReturn os::set_native_priority(Thread* thread, int newpri) {
  2586   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
  2588 #ifdef __OpenBSD__
  2589   // OpenBSD pthread_setprio starves low priority threads
  2590   return OS_OK;
  2591 #elif defined(__FreeBSD__)
  2592   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
  2593 #elif defined(__APPLE__) || defined(__NetBSD__)
  2594   struct sched_param sp;
  2595   int policy;
  2596   pthread_t self = pthread_self();
  2598   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2599     return OS_ERR;
  2601   sp.sched_priority = newpri;
  2602   if (pthread_setschedparam(self, policy, &sp) != 0)
  2603     return OS_ERR;
  2605   return OS_OK;
  2606 #else
  2607   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2608   return (ret == 0) ? OS_OK : OS_ERR;
  2609 #endif
  2612 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
  2613   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
  2614     *priority_ptr = java_to_os_priority[NormPriority];
  2615     return OS_OK;
  2618   errno = 0;
  2619 #if defined(__OpenBSD__) || defined(__FreeBSD__)
  2620   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
  2621 #elif defined(__APPLE__) || defined(__NetBSD__)
  2622   int policy;
  2623   struct sched_param sp;
  2625   pthread_getschedparam(pthread_self(), &policy, &sp);
  2626   *priority_ptr = sp.sched_priority;
  2627 #else
  2628   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
  2629 #endif
  2630   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
  2633 // Hint to the underlying OS that a task switch would not be good.
  2634 // Void return because it's a hint and can fail.
  2635 void os::hint_no_preempt() {}
  2637 ////////////////////////////////////////////////////////////////////////////////
  2638 // suspend/resume support
  2640 //  the low-level signal-based suspend/resume support is a remnant from the
  2641 //  old VM-suspension that used to be for java-suspension, safepoints etc,
  2642 //  within hotspot. Now there is a single use-case for this:
  2643 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
  2644 //      that runs in the watcher thread.
  2645 //  The remaining code is greatly simplified from the more general suspension
  2646 //  code that used to be used.
  2647 //
  2648 //  The protocol is quite simple:
  2649 //  - suspend:
  2650 //      - sends a signal to the target thread
  2651 //      - polls the suspend state of the osthread using a yield loop
  2652 //      - target thread signal handler (SR_handler) sets suspend state
  2653 //        and blocks in sigsuspend until continued
  2654 //  - resume:
  2655 //      - sets target osthread state to continue
  2656 //      - sends signal to end the sigsuspend loop in the SR_handler
  2657 //
  2658 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2659 //
  2661 static void resume_clear_context(OSThread *osthread) {
  2662   osthread->set_ucontext(NULL);
  2663   osthread->set_siginfo(NULL);
  2665   // notify the suspend action is completed, we have now resumed
  2666   osthread->sr.clear_suspended();
  2669 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2670   osthread->set_ucontext(context);
  2671   osthread->set_siginfo(siginfo);
  2674 //
  2675 // Handler function invoked when a thread's execution is suspended or
  2676 // resumed. We have to be careful that only async-safe functions are
  2677 // called here (Note: most pthread functions are not async safe and
  2678 // should be avoided.)
  2679 //
  2680 // Note: sigwait() is a more natural fit than sigsuspend() from an
  2681 // interface point of view, but sigwait() prevents the signal hander
  2682 // from being run. libpthread would get very confused by not having
  2683 // its signal handlers run and prevents sigwait()'s use with the
  2684 // mutex granting granting signal.
  2685 //
  2686 // Currently only ever called on the VMThread
  2687 //
  2688 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
  2689   // Save and restore errno to avoid confusing native code with EINTR
  2690   // after sigsuspend.
  2691   int old_errno = errno;
  2693   Thread* thread = Thread::current();
  2694   OSThread* osthread = thread->osthread();
  2695   assert(thread->is_VM_thread(), "Must be VMThread");
  2696   // read current suspend action
  2697   int action = osthread->sr.suspend_action();
  2698   if (action == os::Bsd::SuspendResume::SR_SUSPEND) {
  2699     suspend_save_context(osthread, siginfo, context);
  2701     // Notify the suspend action is about to be completed. do_suspend()
  2702     // waits until SR_SUSPENDED is set and then returns. We will wait
  2703     // here for a resume signal and that completes the suspend-other
  2704     // action. do_suspend/do_resume is always called as a pair from
  2705     // the same thread - so there are no races
  2707     // notify the caller
  2708     osthread->sr.set_suspended();
  2710     sigset_t suspend_set;  // signals for sigsuspend()
  2712     // get current set of blocked signals and unblock resume signal
  2713     pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
  2714     sigdelset(&suspend_set, SR_signum);
  2716     // wait here until we are resumed
  2717     do {
  2718       sigsuspend(&suspend_set);
  2719       // ignore all returns until we get a resume signal
  2720     } while (osthread->sr.suspend_action() != os::Bsd::SuspendResume::SR_CONTINUE);
  2722     resume_clear_context(osthread);
  2724   } else {
  2725     assert(action == os::Bsd::SuspendResume::SR_CONTINUE, "unexpected sr action");
  2726     // nothing special to do - just leave the handler
  2729   errno = old_errno;
  2733 static int SR_initialize() {
  2734   struct sigaction act;
  2735   char *s;
  2736   /* Get signal number to use for suspend/resume */
  2737   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2738     int sig = ::strtol(s, 0, 10);
  2739     if (sig > 0 || sig < NSIG) {
  2740         SR_signum = sig;
  2744   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2745         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2747   sigemptyset(&SR_sigset);
  2748   sigaddset(&SR_sigset, SR_signum);
  2750   /* Set up signal handler for suspend/resume */
  2751   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2752   act.sa_handler = (void (*)(int)) SR_handler;
  2754   // SR_signum is blocked by default.
  2755   // 4528190 - We also need to block pthread restart signal (32 on all
  2756   // supported Bsd platforms). Note that BsdThreads need to block
  2757   // this signal for all threads to work properly. So we don't have
  2758   // to use hard-coded signal number when setting up the mask.
  2759   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
  2761   if (sigaction(SR_signum, &act, 0) == -1) {
  2762     return -1;
  2765   // Save signal flag
  2766   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
  2767   return 0;
  2770 static int SR_finalize() {
  2771   return 0;
  2775 // returns true on success and false on error - really an error is fatal
  2776 // but this seems the normal response to library errors
  2777 static bool do_suspend(OSThread* osthread) {
  2778   // mark as suspended and send signal
  2779   osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_SUSPEND);
  2780   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2781   assert_status(status == 0, status, "pthread_kill");
  2783   // check status and wait until notified of suspension
  2784   if (status == 0) {
  2785     for (int i = 0; !osthread->sr.is_suspended(); i++) {
  2786       os::yield_all(i);
  2788     osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
  2789     return true;
  2791   else {
  2792     osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
  2793     return false;
  2797 static void do_resume(OSThread* osthread) {
  2798   assert(osthread->sr.is_suspended(), "thread should be suspended");
  2799   osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_CONTINUE);
  2801   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2802   assert_status(status == 0, status, "pthread_kill");
  2803   // check status and wait unit notified of resumption
  2804   if (status == 0) {
  2805     for (int i = 0; osthread->sr.is_suspended(); i++) {
  2806       os::yield_all(i);
  2809   osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
  2812 ////////////////////////////////////////////////////////////////////////////////
  2813 // interrupt support
  2815 void os::interrupt(Thread* thread) {
  2816   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2817     "possibility of dangling Thread pointer");
  2819   OSThread* osthread = thread->osthread();
  2821   if (!osthread->interrupted()) {
  2822     osthread->set_interrupted(true);
  2823     // More than one thread can get here with the same value of osthread,
  2824     // resulting in multiple notifications.  We do, however, want the store
  2825     // to interrupted() to be visible to other threads before we execute unpark().
  2826     OrderAccess::fence();
  2827     ParkEvent * const slp = thread->_SleepEvent ;
  2828     if (slp != NULL) slp->unpark() ;
  2831   // For JSR166. Unpark even if interrupt status already was set
  2832   if (thread->is_Java_thread())
  2833     ((JavaThread*)thread)->parker()->unpark();
  2835   ParkEvent * ev = thread->_ParkEvent ;
  2836   if (ev != NULL) ev->unpark() ;
  2840 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  2841   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2842     "possibility of dangling Thread pointer");
  2844   OSThread* osthread = thread->osthread();
  2846   bool interrupted = osthread->interrupted();
  2848   if (interrupted && clear_interrupted) {
  2849     osthread->set_interrupted(false);
  2850     // consider thread->_SleepEvent->reset() ... optional optimization
  2853   return interrupted;
  2856 ///////////////////////////////////////////////////////////////////////////////////
  2857 // signal handling (except suspend/resume)
  2859 // This routine may be used by user applications as a "hook" to catch signals.
  2860 // The user-defined signal handler must pass unrecognized signals to this
  2861 // routine, and if it returns true (non-zero), then the signal handler must
  2862 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
  2863 // routine will never retun false (zero), but instead will execute a VM panic
  2864 // routine kill the process.
  2865 //
  2866 // If this routine returns false, it is OK to call it again.  This allows
  2867 // the user-defined signal handler to perform checks either before or after
  2868 // the VM performs its own checks.  Naturally, the user code would be making
  2869 // a serious error if it tried to handle an exception (such as a null check
  2870 // or breakpoint) that the VM was generating for its own correct operation.
  2871 //
  2872 // This routine may recognize any of the following kinds of signals:
  2873 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
  2874 // It should be consulted by handlers for any of those signals.
  2875 //
  2876 // The caller of this routine must pass in the three arguments supplied
  2877 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
  2878 // field of the structure passed to sigaction().  This routine assumes that
  2879 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2880 //
  2881 // Note that the VM will print warnings if it detects conflicting signal
  2882 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2883 //
  2884 extern "C" JNIEXPORT int
  2885 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2886                         void* ucontext, int abort_if_unrecognized);
  2888 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2889   assert(info != NULL && uc != NULL, "it must be old kernel");
  2890   int orig_errno = errno;  // Preserve errno value over signal handler.
  2891   JVM_handle_bsd_signal(sig, info, uc, true);
  2892   errno = orig_errno;
  2896 // This boolean allows users to forward their own non-matching signals
  2897 // to JVM_handle_bsd_signal, harmlessly.
  2898 bool os::Bsd::signal_handlers_are_installed = false;
  2900 // For signal-chaining
  2901 struct sigaction os::Bsd::sigact[MAXSIGNUM];
  2902 unsigned int os::Bsd::sigs = 0;
  2903 bool os::Bsd::libjsig_is_loaded = false;
  2904 typedef struct sigaction *(*get_signal_t)(int);
  2905 get_signal_t os::Bsd::get_signal_action = NULL;
  2907 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
  2908   struct sigaction *actp = NULL;
  2910   if (libjsig_is_loaded) {
  2911     // Retrieve the old signal handler from libjsig
  2912     actp = (*get_signal_action)(sig);
  2914   if (actp == NULL) {
  2915     // Retrieve the preinstalled signal handler from jvm
  2916     actp = get_preinstalled_handler(sig);
  2919   return actp;
  2922 static bool call_chained_handler(struct sigaction *actp, int sig,
  2923                                  siginfo_t *siginfo, void *context) {
  2924   // Call the old signal handler
  2925   if (actp->sa_handler == SIG_DFL) {
  2926     // It's more reasonable to let jvm treat it as an unexpected exception
  2927     // instead of taking the default action.
  2928     return false;
  2929   } else if (actp->sa_handler != SIG_IGN) {
  2930     if ((actp->sa_flags & SA_NODEFER) == 0) {
  2931       // automaticlly block the signal
  2932       sigaddset(&(actp->sa_mask), sig);
  2935     sa_handler_t hand;
  2936     sa_sigaction_t sa;
  2937     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
  2938     // retrieve the chained handler
  2939     if (siginfo_flag_set) {
  2940       sa = actp->sa_sigaction;
  2941     } else {
  2942       hand = actp->sa_handler;
  2945     if ((actp->sa_flags & SA_RESETHAND) != 0) {
  2946       actp->sa_handler = SIG_DFL;
  2949     // try to honor the signal mask
  2950     sigset_t oset;
  2951     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
  2953     // call into the chained handler
  2954     if (siginfo_flag_set) {
  2955       (*sa)(sig, siginfo, context);
  2956     } else {
  2957       (*hand)(sig);
  2960     // restore the signal mask
  2961     pthread_sigmask(SIG_SETMASK, &oset, 0);
  2963   // Tell jvm's signal handler the signal is taken care of.
  2964   return true;
  2967 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
  2968   bool chained = false;
  2969   // signal-chaining
  2970   if (UseSignalChaining) {
  2971     struct sigaction *actp = get_chained_signal_action(sig);
  2972     if (actp != NULL) {
  2973       chained = call_chained_handler(actp, sig, siginfo, context);
  2976   return chained;
  2979 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
  2980   if ((( (unsigned int)1 << sig ) & sigs) != 0) {
  2981     return &sigact[sig];
  2983   return NULL;
  2986 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
  2987   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  2988   sigact[sig] = oldAct;
  2989   sigs |= (unsigned int)1 << sig;
  2992 // for diagnostic
  2993 int os::Bsd::sigflags[MAXSIGNUM];
  2995 int os::Bsd::get_our_sigflags(int sig) {
  2996   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  2997   return sigflags[sig];
  3000 void os::Bsd::set_our_sigflags(int sig, int flags) {
  3001   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3002   sigflags[sig] = flags;
  3005 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
  3006   // Check for overwrite.
  3007   struct sigaction oldAct;
  3008   sigaction(sig, (struct sigaction*)NULL, &oldAct);
  3010   void* oldhand = oldAct.sa_sigaction
  3011                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
  3012                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
  3013   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
  3014       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
  3015       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
  3016     if (AllowUserSignalHandlers || !set_installed) {
  3017       // Do not overwrite; user takes responsibility to forward to us.
  3018       return;
  3019     } else if (UseSignalChaining) {
  3020       // save the old handler in jvm
  3021       save_preinstalled_handler(sig, oldAct);
  3022       // libjsig also interposes the sigaction() call below and saves the
  3023       // old sigaction on it own.
  3024     } else {
  3025       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
  3026                     "%#lx for signal %d.", (long)oldhand, sig));
  3030   struct sigaction sigAct;
  3031   sigfillset(&(sigAct.sa_mask));
  3032   sigAct.sa_handler = SIG_DFL;
  3033   if (!set_installed) {
  3034     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3035   } else {
  3036     sigAct.sa_sigaction = signalHandler;
  3037     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3039   // Save flags, which are set by ours
  3040   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3041   sigflags[sig] = sigAct.sa_flags;
  3043   int ret = sigaction(sig, &sigAct, &oldAct);
  3044   assert(ret == 0, "check");
  3046   void* oldhand2  = oldAct.sa_sigaction
  3047                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
  3048                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
  3049   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
  3052 // install signal handlers for signals that HotSpot needs to
  3053 // handle in order to support Java-level exception handling.
  3055 void os::Bsd::install_signal_handlers() {
  3056   if (!signal_handlers_are_installed) {
  3057     signal_handlers_are_installed = true;
  3059     // signal-chaining
  3060     typedef void (*signal_setting_t)();
  3061     signal_setting_t begin_signal_setting = NULL;
  3062     signal_setting_t end_signal_setting = NULL;
  3063     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3064                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3065     if (begin_signal_setting != NULL) {
  3066       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3067                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3068       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3069                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3070       libjsig_is_loaded = true;
  3071       assert(UseSignalChaining, "should enable signal-chaining");
  3073     if (libjsig_is_loaded) {
  3074       // Tell libjsig jvm is setting signal handlers
  3075       (*begin_signal_setting)();
  3078     set_signal_handler(SIGSEGV, true);
  3079     set_signal_handler(SIGPIPE, true);
  3080     set_signal_handler(SIGBUS, true);
  3081     set_signal_handler(SIGILL, true);
  3082     set_signal_handler(SIGFPE, true);
  3083     set_signal_handler(SIGXFSZ, true);
  3085 #if defined(__APPLE__)
  3086     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
  3087     // signals caught and handled by the JVM. To work around this, we reset the mach task
  3088     // signal handler that's placed on our process by CrashReporter. This disables
  3089     // CrashReporter-based reporting.
  3090     //
  3091     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
  3092     // on caught fatal signals.
  3093     //
  3094     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3095     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3096     // exception handling, while leaving the standard BSD signal handlers functional.
  3097     kern_return_t kr;
  3098     kr = task_set_exception_ports(mach_task_self(),
  3099         EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3100         MACH_PORT_NULL,
  3101         EXCEPTION_STATE_IDENTITY,
  3102         MACHINE_THREAD_STATE);
  3104     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3105 #endif
  3107     if (libjsig_is_loaded) {
  3108       // Tell libjsig jvm finishes setting signal handlers
  3109       (*end_signal_setting)();
  3112     // We don't activate signal checker if libjsig is in place, we trust ourselves
  3113     // and if UserSignalHandler is installed all bets are off
  3114     if (CheckJNICalls) {
  3115       if (libjsig_is_loaded) {
  3116         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
  3117         check_signals = false;
  3119       if (AllowUserSignalHandlers) {
  3120         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
  3121         check_signals = false;
  3128 /////
  3129 // glibc on Bsd platform uses non-documented flag
  3130 // to indicate, that some special sort of signal
  3131 // trampoline is used.
  3132 // We will never set this flag, and we should
  3133 // ignore this flag in our diagnostic
  3134 #ifdef SIGNIFICANT_SIGNAL_MASK
  3135 #undef SIGNIFICANT_SIGNAL_MASK
  3136 #endif
  3137 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3139 static const char* get_signal_handler_name(address handler,
  3140                                            char* buf, int buflen) {
  3141   int offset;
  3142   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
  3143   if (found) {
  3144     // skip directory names
  3145     const char *p1, *p2;
  3146     p1 = buf;
  3147     size_t len = strlen(os::file_separator());
  3148     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
  3149     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
  3150   } else {
  3151     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
  3153   return buf;
  3156 static void print_signal_handler(outputStream* st, int sig,
  3157                                  char* buf, size_t buflen) {
  3158   struct sigaction sa;
  3160   sigaction(sig, NULL, &sa);
  3162   // See comment for SIGNIFICANT_SIGNAL_MASK define
  3163   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3165   st->print("%s: ", os::exception_name(sig, buf, buflen));
  3167   address handler = (sa.sa_flags & SA_SIGINFO)
  3168     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
  3169     : CAST_FROM_FN_PTR(address, sa.sa_handler);
  3171   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
  3172     st->print("SIG_DFL");
  3173   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
  3174     st->print("SIG_IGN");
  3175   } else {
  3176     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
  3179   st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
  3181   address rh = VMError::get_resetted_sighandler(sig);
  3182   // May be, handler was resetted by VMError?
  3183   if(rh != NULL) {
  3184     handler = rh;
  3185     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
  3188   st->print(", sa_flags="   PTR32_FORMAT, sa.sa_flags);
  3190   // Check: is it our handler?
  3191   if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3192      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3193     // It is our signal handler
  3194     // check for flags, reset system-used one!
  3195     if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3196       st->print(
  3197                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3198                 os::Bsd::get_our_sigflags(sig));
  3201   st->cr();
  3205 #define DO_SIGNAL_CHECK(sig) \
  3206   if (!sigismember(&check_signal_done, sig)) \
  3207     os::Bsd::check_signal_handler(sig)
  3209 // This method is a periodic task to check for misbehaving JNI applications
  3210 // under CheckJNI, we can add any periodic checks here
  3212 void os::run_periodic_checks() {
  3214   if (check_signals == false) return;
  3216   // SEGV and BUS if overridden could potentially prevent
  3217   // generation of hs*.log in the event of a crash, debugging
  3218   // such a case can be very challenging, so we absolutely
  3219   // check the following for a good measure:
  3220   DO_SIGNAL_CHECK(SIGSEGV);
  3221   DO_SIGNAL_CHECK(SIGILL);
  3222   DO_SIGNAL_CHECK(SIGFPE);
  3223   DO_SIGNAL_CHECK(SIGBUS);
  3224   DO_SIGNAL_CHECK(SIGPIPE);
  3225   DO_SIGNAL_CHECK(SIGXFSZ);
  3228   // ReduceSignalUsage allows the user to override these handlers
  3229   // see comments at the very top and jvm_solaris.h
  3230   if (!ReduceSignalUsage) {
  3231     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
  3232     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
  3233     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
  3234     DO_SIGNAL_CHECK(BREAK_SIGNAL);
  3237   DO_SIGNAL_CHECK(SR_signum);
  3238   DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
  3241 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
  3243 static os_sigaction_t os_sigaction = NULL;
  3245 void os::Bsd::check_signal_handler(int sig) {
  3246   char buf[O_BUFLEN];
  3247   address jvmHandler = NULL;
  3250   struct sigaction act;
  3251   if (os_sigaction == NULL) {
  3252     // only trust the default sigaction, in case it has been interposed
  3253     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
  3254     if (os_sigaction == NULL) return;
  3257   os_sigaction(sig, (struct sigaction*)NULL, &act);
  3260   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3262   address thisHandler = (act.sa_flags & SA_SIGINFO)
  3263     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
  3264     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
  3267   switch(sig) {
  3268   case SIGSEGV:
  3269   case SIGBUS:
  3270   case SIGFPE:
  3271   case SIGPIPE:
  3272   case SIGILL:
  3273   case SIGXFSZ:
  3274     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
  3275     break;
  3277   case SHUTDOWN1_SIGNAL:
  3278   case SHUTDOWN2_SIGNAL:
  3279   case SHUTDOWN3_SIGNAL:
  3280   case BREAK_SIGNAL:
  3281     jvmHandler = (address)user_handler();
  3282     break;
  3284   case INTERRUPT_SIGNAL:
  3285     jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
  3286     break;
  3288   default:
  3289     if (sig == SR_signum) {
  3290       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
  3291     } else {
  3292       return;
  3294     break;
  3297   if (thisHandler != jvmHandler) {
  3298     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
  3299     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
  3300     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
  3301     // No need to check this sig any longer
  3302     sigaddset(&check_signal_done, sig);
  3303   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3304     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
  3305     tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
  3306     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
  3307     // No need to check this sig any longer
  3308     sigaddset(&check_signal_done, sig);
  3311   // Dump all the signal
  3312   if (sigismember(&check_signal_done, sig)) {
  3313     print_signal_handlers(tty, buf, O_BUFLEN);
  3317 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3319 extern bool signal_name(int signo, char* buf, size_t len);
  3321 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3322   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3323     // signal
  3324     if (!signal_name(exception_code, buf, size)) {
  3325       jio_snprintf(buf, size, "SIG%d", exception_code);
  3327     return buf;
  3328   } else {
  3329     return NULL;
  3333 // this is called _before_ the most of global arguments have been parsed
  3334 void os::init(void) {
  3335   char dummy;   /* used to get a guess on initial stack address */
  3336 //  first_hrtime = gethrtime();
  3338   // With BsdThreads the JavaMain thread pid (primordial thread)
  3339   // is different than the pid of the java launcher thread.
  3340   // So, on Bsd, the launcher thread pid is passed to the VM
  3341   // via the sun.java.launcher.pid property.
  3342   // Use this property instead of getpid() if it was correctly passed.
  3343   // See bug 6351349.
  3344   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
  3346   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
  3348   clock_tics_per_sec = CLK_TCK;
  3350   init_random(1234567);
  3352   ThreadCritical::initialize();
  3354   Bsd::set_page_size(getpagesize());
  3355   if (Bsd::page_size() == -1) {
  3356     fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
  3357                   strerror(errno)));
  3359   init_page_sizes((size_t) Bsd::page_size());
  3361   Bsd::initialize_system_info();
  3363   // main_thread points to the aboriginal thread
  3364   Bsd::_main_thread = pthread_self();
  3366   Bsd::clock_init();
  3367   initial_time_count = os::elapsed_counter();
  3369 #ifdef __APPLE__
  3370   // XXXDARWIN
  3371   // Work around the unaligned VM callbacks in hotspot's
  3372   // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
  3373   // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
  3374   // alignment when doing symbol lookup. To work around this, we force early
  3375   // binding of all symbols now, thus binding when alignment is known-good.
  3376   _dyld_bind_fully_image_containing_address((const void *) &os::init);
  3377 #endif
  3380 // To install functions for atexit system call
  3381 extern "C" {
  3382   static void perfMemory_exit_helper() {
  3383     perfMemory_exit();
  3387 // this is called _after_ the global arguments have been parsed
  3388 jint os::init_2(void)
  3390   // Allocate a single page and mark it as readable for safepoint polling
  3391   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3392   guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
  3394   os::set_polling_page( polling_page );
  3396 #ifndef PRODUCT
  3397   if(Verbose && PrintMiscellaneous)
  3398     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3399 #endif
  3401   if (!UseMembar) {
  3402     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3403     guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
  3404     os::set_memory_serialize_page( mem_serialize_page );
  3406 #ifndef PRODUCT
  3407     if(Verbose && PrintMiscellaneous)
  3408       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3409 #endif
  3412   os::large_page_init();
  3414   // initialize suspend/resume support - must do this before signal_sets_init()
  3415   if (SR_initialize() != 0) {
  3416     perror("SR_initialize failed");
  3417     return JNI_ERR;
  3420   Bsd::signal_sets_init();
  3421   Bsd::install_signal_handlers();
  3423   // Check minimum allowable stack size for thread creation and to initialize
  3424   // the java system classes, including StackOverflowError - depends on page
  3425   // size.  Add a page for compiler2 recursion in main thread.
  3426   // Add in 2*BytesPerWord times page size to account for VM stack during
  3427   // class initialization depending on 32 or 64 bit VM.
  3428   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3429             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3430                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3432   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3433   if (threadStackSizeInBytes != 0 &&
  3434       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3435         tty->print_cr("\nThe stack size specified is too small, "
  3436                       "Specify at least %dk",
  3437                       os::Bsd::min_stack_allowed/ K);
  3438         return JNI_ERR;
  3441   // Make the stack size a multiple of the page size so that
  3442   // the yellow/red zones can be guarded.
  3443   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3444         vm_page_size()));
  3446   if (MaxFDLimit) {
  3447     // set the number of file descriptors to max. print out error
  3448     // if getrlimit/setrlimit fails but continue regardless.
  3449     struct rlimit nbr_files;
  3450     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3451     if (status != 0) {
  3452       if (PrintMiscellaneous && (Verbose || WizardMode))
  3453         perror("os::init_2 getrlimit failed");
  3454     } else {
  3455       nbr_files.rlim_cur = nbr_files.rlim_max;
  3457 #ifdef __APPLE__
  3458       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3459       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
  3460       // be used instead
  3461       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3462 #endif
  3464       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3465       if (status != 0) {
  3466         if (PrintMiscellaneous && (Verbose || WizardMode))
  3467           perror("os::init_2 setrlimit failed");
  3472   // at-exit methods are called in the reverse order of their registration.
  3473   // atexit functions are called on return from main or as a result of a
  3474   // call to exit(3C). There can be only 32 of these functions registered
  3475   // and atexit() does not set errno.
  3477   if (PerfAllowAtExitRegistration) {
  3478     // only register atexit functions if PerfAllowAtExitRegistration is set.
  3479     // atexit functions can be delayed until process exit time, which
  3480     // can be problematic for embedded VM situations. Embedded VMs should
  3481     // call DestroyJavaVM() to assure that VM resources are released.
  3483     // note: perfMemory_exit_helper atexit function may be removed in
  3484     // the future if the appropriate cleanup code can be added to the
  3485     // VM_Exit VMOperation's doit method.
  3486     if (atexit(perfMemory_exit_helper) != 0) {
  3487       warning("os::init2 atexit(perfMemory_exit_helper) failed");
  3491   // initialize thread priority policy
  3492   prio_init();
  3494 #ifdef __APPLE__
  3495   // dynamically link to objective c gc registration
  3496   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
  3497   if (handleLibObjc != NULL) {
  3498     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
  3500 #endif
  3502   return JNI_OK;
  3505 // this is called at the end of vm_initialization
  3506 void os::init_3(void) { }
  3508 // Mark the polling page as unreadable
  3509 void os::make_polling_page_unreadable(void) {
  3510   if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
  3511     fatal("Could not disable polling page");
  3512 };
  3514 // Mark the polling page as readable
  3515 void os::make_polling_page_readable(void) {
  3516   if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3517     fatal("Could not enable polling page");
  3519 };
  3521 int os::active_processor_count() {
  3522   return _processor_count;
  3525 void os::set_native_thread_name(const char *name) {
  3526 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  3527   // This is only supported in Snow Leopard and beyond
  3528   if (name != NULL) {
  3529     // Add a "Java: " prefix to the name
  3530     char buf[MAXTHREADNAMESIZE];
  3531     snprintf(buf, sizeof(buf), "Java: %s", name);
  3532     pthread_setname_np(buf);
  3534 #endif
  3537 bool os::distribute_processes(uint length, uint* distribution) {
  3538   // Not yet implemented.
  3539   return false;
  3542 bool os::bind_to_processor(uint processor_id) {
  3543   // Not yet implemented.
  3544   return false;
  3547 ///
  3549 // Suspends the target using the signal mechanism and then grabs the PC before
  3550 // resuming the target. Used by the flat-profiler only
  3551 ExtendedPC os::get_thread_pc(Thread* thread) {
  3552   // Make sure that it is called by the watcher for the VMThread
  3553   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
  3554   assert(thread->is_VM_thread(), "Can only be called for VMThread");
  3556   ExtendedPC epc;
  3558   OSThread* osthread = thread->osthread();
  3559   if (do_suspend(osthread)) {
  3560     if (osthread->ucontext() != NULL) {
  3561       epc = os::Bsd::ucontext_get_pc(osthread->ucontext());
  3562     } else {
  3563       // NULL context is unexpected, double-check this is the VMThread
  3564       guarantee(thread->is_VM_thread(), "can only be called for VMThread");
  3566     do_resume(osthread);
  3568   // failure means pthread_kill failed for some reason - arguably this is
  3569   // a fatal problem, but such problems are ignored elsewhere
  3571   return epc;
  3574 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3576   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3579 ////////////////////////////////////////////////////////////////////////////////
  3580 // debug support
  3582 static address same_page(address x, address y) {
  3583   int page_bits = -os::vm_page_size();
  3584   if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
  3585     return x;
  3586   else if (x > y)
  3587     return (address)(intptr_t(y) | ~page_bits) + 1;
  3588   else
  3589     return (address)(intptr_t(y) & page_bits);
  3592 bool os::find(address addr, outputStream* st) {
  3593   Dl_info dlinfo;
  3594   memset(&dlinfo, 0, sizeof(dlinfo));
  3595   if (dladdr(addr, &dlinfo)) {
  3596     st->print(PTR_FORMAT ": ", addr);
  3597     if (dlinfo.dli_sname != NULL) {
  3598       st->print("%s+%#x", dlinfo.dli_sname,
  3599                  addr - (intptr_t)dlinfo.dli_saddr);
  3600     } else if (dlinfo.dli_fname) {
  3601       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3602     } else {
  3603       st->print("<absolute address>");
  3605     if (dlinfo.dli_fname) {
  3606       st->print(" in %s", dlinfo.dli_fname);
  3608     if (dlinfo.dli_fbase) {
  3609       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
  3611     st->cr();
  3613     if (Verbose) {
  3614       // decode some bytes around the PC
  3615       address begin = same_page(addr-40, addr);
  3616       address end   = same_page(addr+40, addr);
  3617       address       lowest = (address) dlinfo.dli_sname;
  3618       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3619       if (begin < lowest)  begin = lowest;
  3620       Dl_info dlinfo2;
  3621       if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3622           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3623         end = (address) dlinfo2.dli_saddr;
  3624       Disassembler::decode(begin, end, st);
  3626     return true;
  3628   return false;
  3631 ////////////////////////////////////////////////////////////////////////////////
  3632 // misc
  3634 // This does not do anything on Bsd. This is basically a hook for being
  3635 // able to use structured exception handling (thread-local exception filters)
  3636 // on, e.g., Win32.
  3637 void
  3638 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3639                          JavaCallArguments* args, Thread* thread) {
  3640   f(value, method, args, thread);
  3643 void os::print_statistics() {
  3646 int os::message_box(const char* title, const char* message) {
  3647   int i;
  3648   fdStream err(defaultStream::error_fd());
  3649   for (i = 0; i < 78; i++) err.print_raw("=");
  3650   err.cr();
  3651   err.print_raw_cr(title);
  3652   for (i = 0; i < 78; i++) err.print_raw("-");
  3653   err.cr();
  3654   err.print_raw_cr(message);
  3655   for (i = 0; i < 78; i++) err.print_raw("=");
  3656   err.cr();
  3658   char buf[16];
  3659   // Prevent process from exiting upon "read error" without consuming all CPU
  3660   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
  3662   return buf[0] == 'y' || buf[0] == 'Y';
  3665 int os::stat(const char *path, struct stat *sbuf) {
  3666   char pathbuf[MAX_PATH];
  3667   if (strlen(path) > MAX_PATH - 1) {
  3668     errno = ENAMETOOLONG;
  3669     return -1;
  3671   os::native_path(strcpy(pathbuf, path));
  3672   return ::stat(pathbuf, sbuf);
  3675 bool os::check_heap(bool force) {
  3676   return true;
  3679 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
  3680   return ::vsnprintf(buf, count, format, args);
  3683 // Is a (classpath) directory empty?
  3684 bool os::dir_is_empty(const char* path) {
  3685   DIR *dir = NULL;
  3686   struct dirent *ptr;
  3688   dir = opendir(path);
  3689   if (dir == NULL) return true;
  3691   /* Scan the directory */
  3692   bool result = true;
  3693   char buf[sizeof(struct dirent) + MAX_PATH];
  3694   while (result && (ptr = ::readdir(dir)) != NULL) {
  3695     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3696       result = false;
  3699   closedir(dir);
  3700   return result;
  3703 // This code originates from JDK's sysOpen and open64_w
  3704 // from src/solaris/hpi/src/system_md.c
  3706 #ifndef O_DELETE
  3707 #define O_DELETE 0x10000
  3708 #endif
  3710 // Open a file. Unlink the file immediately after open returns
  3711 // if the specified oflag has the O_DELETE flag set.
  3712 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3714 int os::open(const char *path, int oflag, int mode) {
  3716   if (strlen(path) > MAX_PATH - 1) {
  3717     errno = ENAMETOOLONG;
  3718     return -1;
  3720   int fd;
  3721   int o_delete = (oflag & O_DELETE);
  3722   oflag = oflag & ~O_DELETE;
  3724   fd = ::open(path, oflag, mode);
  3725   if (fd == -1) return -1;
  3727   //If the open succeeded, the file might still be a directory
  3729     struct stat buf;
  3730     int ret = ::fstat(fd, &buf);
  3731     int st_mode = buf.st_mode;
  3733     if (ret != -1) {
  3734       if ((st_mode & S_IFMT) == S_IFDIR) {
  3735         errno = EISDIR;
  3736         ::close(fd);
  3737         return -1;
  3739     } else {
  3740       ::close(fd);
  3741       return -1;
  3745     /*
  3746      * All file descriptors that are opened in the JVM and not
  3747      * specifically destined for a subprocess should have the
  3748      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3749      * party native code might fork and exec without closing all
  3750      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3751      * UNIXProcess.c), and this in turn might:
  3753      * - cause end-of-file to fail to be detected on some file
  3754      *   descriptors, resulting in mysterious hangs, or
  3756      * - might cause an fopen in the subprocess to fail on a system
  3757      *   suffering from bug 1085341.
  3759      * (Yes, the default setting of the close-on-exec flag is a Unix
  3760      * design flaw)
  3762      * See:
  3763      * 1085341: 32-bit stdio routines should support file descriptors >255
  3764      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3765      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3766      */
  3767 #ifdef FD_CLOEXEC
  3769         int flags = ::fcntl(fd, F_GETFD);
  3770         if (flags != -1)
  3771             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3773 #endif
  3775   if (o_delete != 0) {
  3776     ::unlink(path);
  3778   return fd;
  3782 // create binary file, rewriting existing file if required
  3783 int os::create_binary_file(const char* path, bool rewrite_existing) {
  3784   int oflags = O_WRONLY | O_CREAT;
  3785   if (!rewrite_existing) {
  3786     oflags |= O_EXCL;
  3788   return ::open(path, oflags, S_IREAD | S_IWRITE);
  3791 // return current position of file pointer
  3792 jlong os::current_file_offset(int fd) {
  3793   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
  3796 // move file pointer to the specified offset
  3797 jlong os::seek_to_file_offset(int fd, jlong offset) {
  3798   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
  3801 // This code originates from JDK's sysAvailable
  3802 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
  3804 int os::available(int fd, jlong *bytes) {
  3805   jlong cur, end;
  3806   int mode;
  3807   struct stat buf;
  3809   if (::fstat(fd, &buf) >= 0) {
  3810     mode = buf.st_mode;
  3811     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3812       /*
  3813       * XXX: is the following call interruptible? If so, this might
  3814       * need to go through the INTERRUPT_IO() wrapper as for other
  3815       * blocking, interruptible calls in this file.
  3816       */
  3817       int n;
  3818       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3819         *bytes = n;
  3820         return 1;
  3824   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
  3825     return 0;
  3826   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
  3827     return 0;
  3828   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
  3829     return 0;
  3831   *bytes = end - cur;
  3832   return 1;
  3835 int os::socket_available(int fd, jint *pbytes) {
  3836    if (fd < 0)
  3837      return OS_OK;
  3839    int ret;
  3841    RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3843    //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  3844    // is expected to return 0 on failure and 1 on success to the jdk.
  3846    return (ret == OS_ERR) ? 0 : 1;
  3849 // Map a block of memory.
  3850 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  3851                      char *addr, size_t bytes, bool read_only,
  3852                      bool allow_exec) {
  3853   int prot;
  3854   int flags;
  3856   if (read_only) {
  3857     prot = PROT_READ;
  3858     flags = MAP_SHARED;
  3859   } else {
  3860     prot = PROT_READ | PROT_WRITE;
  3861     flags = MAP_PRIVATE;
  3864   if (allow_exec) {
  3865     prot |= PROT_EXEC;
  3868   if (addr != NULL) {
  3869     flags |= MAP_FIXED;
  3872   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
  3873                                      fd, file_offset);
  3874   if (mapped_address == MAP_FAILED) {
  3875     return NULL;
  3877   return mapped_address;
  3881 // Remap a block of memory.
  3882 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  3883                        char *addr, size_t bytes, bool read_only,
  3884                        bool allow_exec) {
  3885   // same as map_memory() on this OS
  3886   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  3887                         allow_exec);
  3891 // Unmap a block of memory.
  3892 bool os::pd_unmap_memory(char* addr, size_t bytes) {
  3893   return munmap(addr, bytes) == 0;
  3896 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  3897 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  3898 // of a thread.
  3899 //
  3900 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
  3901 // the fast estimate available on the platform.
  3903 jlong os::current_thread_cpu_time() {
  3904 #ifdef __APPLE__
  3905   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
  3906 #else
  3907   Unimplemented();
  3908   return 0;
  3909 #endif
  3912 jlong os::thread_cpu_time(Thread* thread) {
  3913 #ifdef __APPLE__
  3914   return os::thread_cpu_time(thread, true /* user + sys */);
  3915 #else
  3916   Unimplemented();
  3917   return 0;
  3918 #endif
  3921 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  3922 #ifdef __APPLE__
  3923   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  3924 #else
  3925   Unimplemented();
  3926   return 0;
  3927 #endif
  3930 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
  3931 #ifdef __APPLE__
  3932   struct thread_basic_info tinfo;
  3933   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
  3934   kern_return_t kr;
  3935   thread_t mach_thread;
  3937   mach_thread = thread->osthread()->thread_id();
  3938   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  3939   if (kr != KERN_SUCCESS)
  3940     return -1;
  3942   if (user_sys_cpu_time) {
  3943     jlong nanos;
  3944     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  3945     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  3946     return nanos;
  3947   } else {
  3948     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
  3950 #else
  3951   Unimplemented();
  3952   return 0;
  3953 #endif
  3957 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  3958   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  3959   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  3960   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  3961   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  3964 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  3965   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  3966   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  3967   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  3968   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  3971 bool os::is_thread_cpu_time_supported() {
  3972 #ifdef __APPLE__
  3973   return true;
  3974 #else
  3975   return false;
  3976 #endif
  3979 // System loadavg support.  Returns -1 if load average cannot be obtained.
  3980 // Bsd doesn't yet have a (official) notion of processor sets,
  3981 // so just return the system wide load average.
  3982 int os::loadavg(double loadavg[], int nelem) {
  3983   return ::getloadavg(loadavg, nelem);
  3986 void os::pause() {
  3987   char filename[MAX_PATH];
  3988   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  3989     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  3990   } else {
  3991     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  3994   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  3995   if (fd != -1) {
  3996     struct stat buf;
  3997     ::close(fd);
  3998     while (::stat(filename, &buf) == 0) {
  3999       (void)::poll(NULL, 0, 100);
  4001   } else {
  4002     jio_fprintf(stderr,
  4003       "Could not open pause file '%s', continuing immediately.\n", filename);
  4008 // Refer to the comments in os_solaris.cpp park-unpark.
  4009 //
  4010 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
  4011 // hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
  4012 // For specifics regarding the bug see GLIBC BUGID 261237 :
  4013 //    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
  4014 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
  4015 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
  4016 // is used.  (The simple C test-case provided in the GLIBC bug report manifests the
  4017 // hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
  4018 // and monitorenter when we're using 1-0 locking.  All those operations may result in
  4019 // calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
  4020 // of libpthread avoids the problem, but isn't practical.
  4021 //
  4022 // Possible remedies:
  4023 //
  4024 // 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
  4025 //      This is palliative and probabilistic, however.  If the thread is preempted
  4026 //      between the call to compute_abstime() and pthread_cond_timedwait(), more
  4027 //      than the minimum period may have passed, and the abstime may be stale (in the
  4028 //      past) resultin in a hang.   Using this technique reduces the odds of a hang
  4029 //      but the JVM is still vulnerable, particularly on heavily loaded systems.
  4030 //
  4031 // 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
  4032 //      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
  4033 //      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
  4034 //      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
  4035 //      thread.
  4036 //
  4037 // 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
  4038 //      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
  4039 //      a timeout request to the chron thread and then blocking via pthread_cond_wait().
  4040 //      This also works well.  In fact it avoids kernel-level scalability impediments
  4041 //      on certain platforms that don't handle lots of active pthread_cond_timedwait()
  4042 //      timers in a graceful fashion.
  4043 //
  4044 // 4.   When the abstime value is in the past it appears that control returns
  4045 //      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
  4046 //      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
  4047 //      can avoid the problem by reinitializing the condvar -- by cond_destroy()
  4048 //      followed by cond_init() -- after all calls to pthread_cond_timedwait().
  4049 //      It may be possible to avoid reinitialization by checking the return
  4050 //      value from pthread_cond_timedwait().  In addition to reinitializing the
  4051 //      condvar we must establish the invariant that cond_signal() is only called
  4052 //      within critical sections protected by the adjunct mutex.  This prevents
  4053 //      cond_signal() from "seeing" a condvar that's in the midst of being
  4054 //      reinitialized or that is corrupt.  Sadly, this invariant obviates the
  4055 //      desirable signal-after-unlock optimization that avoids futile context switching.
  4056 //
  4057 //      I'm also concerned that some versions of NTPL might allocate an auxilliary
  4058 //      structure when a condvar is used or initialized.  cond_destroy()  would
  4059 //      release the helper structure.  Our reinitialize-after-timedwait fix
  4060 //      put excessive stress on malloc/free and locks protecting the c-heap.
  4061 //
  4062 // We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
  4063 // It may be possible to refine (4) by checking the kernel and NTPL verisons
  4064 // and only enabling the work-around for vulnerable environments.
  4066 // utility to compute the abstime argument to timedwait:
  4067 // millis is the relative timeout time
  4068 // abstime will be the absolute timeout time
  4069 // TODO: replace compute_abstime() with unpackTime()
  4071 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4072   if (millis < 0)  millis = 0;
  4073   struct timeval now;
  4074   int status = gettimeofday(&now, NULL);
  4075   assert(status == 0, "gettimeofday");
  4076   jlong seconds = millis / 1000;
  4077   millis %= 1000;
  4078   if (seconds > 50000000) { // see man cond_timedwait(3T)
  4079     seconds = 50000000;
  4081   abstime->tv_sec = now.tv_sec  + seconds;
  4082   long       usec = now.tv_usec + millis * 1000;
  4083   if (usec >= 1000000) {
  4084     abstime->tv_sec += 1;
  4085     usec -= 1000000;
  4087   abstime->tv_nsec = usec * 1000;
  4088   return abstime;
  4092 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
  4093 // Conceptually TryPark() should be equivalent to park(0).
  4095 int os::PlatformEvent::TryPark() {
  4096   for (;;) {
  4097     const int v = _Event ;
  4098     guarantee ((v == 0) || (v == 1), "invariant") ;
  4099     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
  4103 void os::PlatformEvent::park() {       // AKA "down()"
  4104   // Invariant: Only the thread associated with the Event/PlatformEvent
  4105   // may call park().
  4106   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4107   int v ;
  4108   for (;;) {
  4109       v = _Event ;
  4110       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4112   guarantee (v >= 0, "invariant") ;
  4113   if (v == 0) {
  4114      // Do this the hard way by blocking ...
  4115      int status = pthread_mutex_lock(_mutex);
  4116      assert_status(status == 0, status, "mutex_lock");
  4117      guarantee (_nParked == 0, "invariant") ;
  4118      ++ _nParked ;
  4119      while (_Event < 0) {
  4120         status = pthread_cond_wait(_cond, _mutex);
  4121         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4122         // Treat this the same as if the wait was interrupted
  4123         if (status == ETIMEDOUT) { status = EINTR; }
  4124         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4126      -- _nParked ;
  4128     _Event = 0 ;
  4129      status = pthread_mutex_unlock(_mutex);
  4130      assert_status(status == 0, status, "mutex_unlock");
  4131     // Paranoia to ensure our locked and lock-free paths interact
  4132     // correctly with each other.
  4133     OrderAccess::fence();
  4135   guarantee (_Event >= 0, "invariant") ;
  4138 int os::PlatformEvent::park(jlong millis) {
  4139   guarantee (_nParked == 0, "invariant") ;
  4141   int v ;
  4142   for (;;) {
  4143       v = _Event ;
  4144       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4146   guarantee (v >= 0, "invariant") ;
  4147   if (v != 0) return OS_OK ;
  4149   // We do this the hard way, by blocking the thread.
  4150   // Consider enforcing a minimum timeout value.
  4151   struct timespec abst;
  4152   compute_abstime(&abst, millis);
  4154   int ret = OS_TIMEOUT;
  4155   int status = pthread_mutex_lock(_mutex);
  4156   assert_status(status == 0, status, "mutex_lock");
  4157   guarantee (_nParked == 0, "invariant") ;
  4158   ++_nParked ;
  4160   // Object.wait(timo) will return because of
  4161   // (a) notification
  4162   // (b) timeout
  4163   // (c) thread.interrupt
  4164   //
  4165   // Thread.interrupt and object.notify{All} both call Event::set.
  4166   // That is, we treat thread.interrupt as a special case of notification.
  4167   // The underlying Solaris implementation, cond_timedwait, admits
  4168   // spurious/premature wakeups, but the JLS/JVM spec prevents the
  4169   // JVM from making those visible to Java code.  As such, we must
  4170   // filter out spurious wakeups.  We assume all ETIME returns are valid.
  4171   //
  4172   // TODO: properly differentiate simultaneous notify+interrupt.
  4173   // In that case, we should propagate the notify to another waiter.
  4175   while (_Event < 0) {
  4176     status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
  4177     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4178       pthread_cond_destroy (_cond);
  4179       pthread_cond_init (_cond, NULL) ;
  4181     assert_status(status == 0 || status == EINTR ||
  4182                   status == ETIMEDOUT,
  4183                   status, "cond_timedwait");
  4184     if (!FilterSpuriousWakeups) break ;                 // previous semantics
  4185     if (status == ETIMEDOUT) break ;
  4186     // We consume and ignore EINTR and spurious wakeups.
  4188   --_nParked ;
  4189   if (_Event >= 0) {
  4190      ret = OS_OK;
  4192   _Event = 0 ;
  4193   status = pthread_mutex_unlock(_mutex);
  4194   assert_status(status == 0, status, "mutex_unlock");
  4195   assert (_nParked == 0, "invariant") ;
  4196   // Paranoia to ensure our locked and lock-free paths interact
  4197   // correctly with each other.
  4198   OrderAccess::fence();
  4199   return ret;
  4202 void os::PlatformEvent::unpark() {
  4203   // Transitions for _Event:
  4204   //    0 :=> 1
  4205   //    1 :=> 1
  4206   //   -1 :=> either 0 or 1; must signal target thread
  4207   //          That is, we can safely transition _Event from -1 to either
  4208   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
  4209   //          unpark() calls.
  4210   // See also: "Semaphores in Plan 9" by Mullender & Cox
  4211   //
  4212   // Note: Forcing a transition from "-1" to "1" on an unpark() means
  4213   // that it will take two back-to-back park() calls for the owning
  4214   // thread to block. This has the benefit of forcing a spurious return
  4215   // from the first park() call after an unpark() call which will help
  4216   // shake out uses of park() and unpark() without condition variables.
  4218   if (Atomic::xchg(1, &_Event) >= 0) return;
  4220   // Wait for the thread associated with the event to vacate
  4221   int status = pthread_mutex_lock(_mutex);
  4222   assert_status(status == 0, status, "mutex_lock");
  4223   int AnyWaiters = _nParked;
  4224   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
  4225   if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
  4226     AnyWaiters = 0;
  4227     pthread_cond_signal(_cond);
  4229   status = pthread_mutex_unlock(_mutex);
  4230   assert_status(status == 0, status, "mutex_unlock");
  4231   if (AnyWaiters != 0) {
  4232     status = pthread_cond_signal(_cond);
  4233     assert_status(status == 0, status, "cond_signal");
  4236   // Note that we signal() _after dropping the lock for "immortal" Events.
  4237   // This is safe and avoids a common class of  futile wakeups.  In rare
  4238   // circumstances this can cause a thread to return prematurely from
  4239   // cond_{timed}wait() but the spurious wakeup is benign and the victim will
  4240   // simply re-test the condition and re-park itself.
  4244 // JSR166
  4245 // -------------------------------------------------------
  4247 /*
  4248  * The solaris and bsd implementations of park/unpark are fairly
  4249  * conservative for now, but can be improved. They currently use a
  4250  * mutex/condvar pair, plus a a count.
  4251  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4252  * sets count to 1 and signals condvar.  Only one thread ever waits
  4253  * on the condvar. Contention seen when trying to park implies that someone
  4254  * is unparking you, so don't wait. And spurious returns are fine, so there
  4255  * is no need to track notifications.
  4256  */
  4258 #define MAX_SECS 100000000
  4259 /*
  4260  * This code is common to bsd and solaris and will be moved to a
  4261  * common place in dolphin.
  4263  * The passed in time value is either a relative time in nanoseconds
  4264  * or an absolute time in milliseconds. Either way it has to be unpacked
  4265  * into suitable seconds and nanoseconds components and stored in the
  4266  * given timespec structure.
  4267  * Given time is a 64-bit value and the time_t used in the timespec is only
  4268  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4269  * overflow if times way in the future are given. Further on Solaris versions
  4270  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4271  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4272  * As it will be 28 years before "now + 100000000" will overflow we can
  4273  * ignore overflow and just impose a hard-limit on seconds using the value
  4274  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4275  * years from "now".
  4276  */
  4278 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4279   assert (time > 0, "convertTime");
  4281   struct timeval now;
  4282   int status = gettimeofday(&now, NULL);
  4283   assert(status == 0, "gettimeofday");
  4285   time_t max_secs = now.tv_sec + MAX_SECS;
  4287   if (isAbsolute) {
  4288     jlong secs = time / 1000;
  4289     if (secs > max_secs) {
  4290       absTime->tv_sec = max_secs;
  4292     else {
  4293       absTime->tv_sec = secs;
  4295     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4297   else {
  4298     jlong secs = time / NANOSECS_PER_SEC;
  4299     if (secs >= MAX_SECS) {
  4300       absTime->tv_sec = max_secs;
  4301       absTime->tv_nsec = 0;
  4303     else {
  4304       absTime->tv_sec = now.tv_sec + secs;
  4305       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4306       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4307         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4308         ++absTime->tv_sec; // note: this must be <= max_secs
  4312   assert(absTime->tv_sec >= 0, "tv_sec < 0");
  4313   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
  4314   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
  4315   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
  4318 void Parker::park(bool isAbsolute, jlong time) {
  4319   // Ideally we'd do something useful while spinning, such
  4320   // as calling unpackTime().
  4322   // Optional fast-path check:
  4323   // Return immediately if a permit is available.
  4324   // We depend on Atomic::xchg() having full barrier semantics
  4325   // since we are doing a lock-free update to _counter.
  4326   if (Atomic::xchg(0, &_counter) > 0) return;
  4328   Thread* thread = Thread::current();
  4329   assert(thread->is_Java_thread(), "Must be JavaThread");
  4330   JavaThread *jt = (JavaThread *)thread;
  4332   // Optional optimization -- avoid state transitions if there's an interrupt pending.
  4333   // Check interrupt before trying to wait
  4334   if (Thread::is_interrupted(thread, false)) {
  4335     return;
  4338   // Next, demultiplex/decode time arguments
  4339   struct timespec absTime;
  4340   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
  4341     return;
  4343   if (time > 0) {
  4344     unpackTime(&absTime, isAbsolute, time);
  4348   // Enter safepoint region
  4349   // Beware of deadlocks such as 6317397.
  4350   // The per-thread Parker:: mutex is a classic leaf-lock.
  4351   // In particular a thread must never block on the Threads_lock while
  4352   // holding the Parker:: mutex.  If safepoints are pending both the
  4353   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
  4354   ThreadBlockInVM tbivm(jt);
  4356   // Don't wait if cannot get lock since interference arises from
  4357   // unblocking.  Also. check interrupt before trying wait
  4358   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
  4359     return;
  4362   int status ;
  4363   if (_counter > 0)  { // no wait needed
  4364     _counter = 0;
  4365     status = pthread_mutex_unlock(_mutex);
  4366     assert (status == 0, "invariant") ;
  4367     // Paranoia to ensure our locked and lock-free paths interact
  4368     // correctly with each other and Java-level accesses.
  4369     OrderAccess::fence();
  4370     return;
  4373 #ifdef ASSERT
  4374   // Don't catch signals while blocked; let the running threads have the signals.
  4375   // (This allows a debugger to break into the running thread.)
  4376   sigset_t oldsigs;
  4377   sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
  4378   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
  4379 #endif
  4381   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  4382   jt->set_suspend_equivalent();
  4383   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  4385   if (time == 0) {
  4386     status = pthread_cond_wait (_cond, _mutex) ;
  4387   } else {
  4388     status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
  4389     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4390       pthread_cond_destroy (_cond) ;
  4391       pthread_cond_init    (_cond, NULL);
  4394   assert_status(status == 0 || status == EINTR ||
  4395                 status == ETIMEDOUT,
  4396                 status, "cond_timedwait");
  4398 #ifdef ASSERT
  4399   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
  4400 #endif
  4402   _counter = 0 ;
  4403   status = pthread_mutex_unlock(_mutex) ;
  4404   assert_status(status == 0, status, "invariant") ;
  4405   // Paranoia to ensure our locked and lock-free paths interact
  4406   // correctly with each other and Java-level accesses.
  4407   OrderAccess::fence();
  4409   // If externally suspended while waiting, re-suspend
  4410   if (jt->handle_special_suspend_equivalent_condition()) {
  4411     jt->java_suspend_self();
  4415 void Parker::unpark() {
  4416   int s, status ;
  4417   status = pthread_mutex_lock(_mutex);
  4418   assert (status == 0, "invariant") ;
  4419   s = _counter;
  4420   _counter = 1;
  4421   if (s < 1) {
  4422      if (WorkAroundNPTLTimedWaitHang) {
  4423         status = pthread_cond_signal (_cond) ;
  4424         assert (status == 0, "invariant") ;
  4425         status = pthread_mutex_unlock(_mutex);
  4426         assert (status == 0, "invariant") ;
  4427      } else {
  4428         status = pthread_mutex_unlock(_mutex);
  4429         assert (status == 0, "invariant") ;
  4430         status = pthread_cond_signal (_cond) ;
  4431         assert (status == 0, "invariant") ;
  4433   } else {
  4434     pthread_mutex_unlock(_mutex);
  4435     assert (status == 0, "invariant") ;
  4440 /* Darwin has no "environ" in a dynamic library. */
  4441 #ifdef __APPLE__
  4442 #include <crt_externs.h>
  4443 #define environ (*_NSGetEnviron())
  4444 #else
  4445 extern char** environ;
  4446 #endif
  4448 // Run the specified command in a separate process. Return its exit value,
  4449 // or -1 on failure (e.g. can't fork a new process).
  4450 // Unlike system(), this function can be called from signal handler. It
  4451 // doesn't block SIGINT et al.
  4452 int os::fork_and_exec(char* cmd) {
  4453   const char * argv[4] = {"sh", "-c", cmd, NULL};
  4455   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
  4456   // pthread_atfork handlers and reset pthread library. All we need is a
  4457   // separate process to execve. Make a direct syscall to fork process.
  4458   // On IA64 there's no fork syscall, we have to use fork() and hope for
  4459   // the best...
  4460   pid_t pid = fork();
  4462   if (pid < 0) {
  4463     // fork failed
  4464     return -1;
  4466   } else if (pid == 0) {
  4467     // child process
  4469     // execve() in BsdThreads will call pthread_kill_other_threads_np()
  4470     // first to kill every thread on the thread list. Because this list is
  4471     // not reset by fork() (see notes above), execve() will instead kill
  4472     // every thread in the parent process. We know this is the only thread
  4473     // in the new process, so make a system call directly.
  4474     // IA64 should use normal execve() from glibc to match the glibc fork()
  4475     // above.
  4476     execve("/bin/sh", (char* const*)argv, environ);
  4478     // execve failed
  4479     _exit(-1);
  4481   } else  {
  4482     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
  4483     // care about the actual exit code, for now.
  4485     int status;
  4487     // Wait for the child process to exit.  This returns immediately if
  4488     // the child has already exited. */
  4489     while (waitpid(pid, &status, 0) < 0) {
  4490         switch (errno) {
  4491         case ECHILD: return 0;
  4492         case EINTR: break;
  4493         default: return -1;
  4497     if (WIFEXITED(status)) {
  4498        // The child exited normally; get its exit code.
  4499        return WEXITSTATUS(status);
  4500     } else if (WIFSIGNALED(status)) {
  4501        // The child exited because of a signal
  4502        // The best value to return is 0x80 + signal number,
  4503        // because that is what all Unix shells do, and because
  4504        // it allows callers to distinguish between process exit and
  4505        // process death by signal.
  4506        return 0x80 + WTERMSIG(status);
  4507     } else {
  4508        // Unknown exit code; pass it through
  4509        return status;
  4514 // is_headless_jre()
  4515 //
  4516 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
  4517 // in order to report if we are running in a headless jre
  4518 //
  4519 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4520 // as libawt.so, and renamed libawt_xawt.so
  4521 //
  4522 bool os::is_headless_jre() {
  4523     struct stat statbuf;
  4524     char buf[MAXPATHLEN];
  4525     char libmawtpath[MAXPATHLEN];
  4526     const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
  4527     const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
  4528     char *p;
  4530     // Get path to libjvm.so
  4531     os::jvm_path(buf, sizeof(buf));
  4533     // Get rid of libjvm.so
  4534     p = strrchr(buf, '/');
  4535     if (p == NULL) return false;
  4536     else *p = '\0';
  4538     // Get rid of client or server
  4539     p = strrchr(buf, '/');
  4540     if (p == NULL) return false;
  4541     else *p = '\0';
  4543     // check xawt/libmawt.so
  4544     strcpy(libmawtpath, buf);
  4545     strcat(libmawtpath, xawtstr);
  4546     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4548     // check libawt_xawt.so
  4549     strcpy(libmawtpath, buf);
  4550     strcat(libmawtpath, new_xawtstr);
  4551     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4553     return true;
  4556 // Get the default path to the core file
  4557 // Returns the length of the string
  4558 int os::get_core_path(char* buffer, size_t bufferSize) {
  4559   int n = jio_snprintf(buffer, bufferSize, "/cores");
  4561   // Truncate if theoretical string was longer than bufferSize
  4562   n = MIN2(n, (int)bufferSize);
  4564   return n;

mercurial