src/os/bsd/vm/os_bsd.cpp

Thu, 07 Mar 2013 14:06:44 -0500

author
zgu
date
Thu, 07 Mar 2013 14:06:44 -0500
changeset 4711
6b803ba47588
parent 4675
63e54c37ac64
child 4713
252ad8d5f22b
permissions
-rw-r--r--

8008257: NMT: assert(new_rec->is_allocation_record()) failed when running with shared memory option
Summary: Corrected virtual memory recording and tagging code when large pages are used
Reviewed-by: coleenp, ccheung

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 // no precompiled headers
    26 #include "classfile/classLoader.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "classfile/vmSymbols.hpp"
    29 #include "code/icBuffer.hpp"
    30 #include "code/vtableStubs.hpp"
    31 #include "compiler/compileBroker.hpp"
    32 #include "compiler/disassembler.hpp"
    33 #include "interpreter/interpreter.hpp"
    34 #include "jvm_bsd.h"
    35 #include "memory/allocation.inline.hpp"
    36 #include "memory/filemap.hpp"
    37 #include "mutex_bsd.inline.hpp"
    38 #include "oops/oop.inline.hpp"
    39 #include "os_share_bsd.hpp"
    40 #include "prims/jniFastGetField.hpp"
    41 #include "prims/jvm.h"
    42 #include "prims/jvm_misc.hpp"
    43 #include "runtime/arguments.hpp"
    44 #include "runtime/extendedPC.hpp"
    45 #include "runtime/globals.hpp"
    46 #include "runtime/interfaceSupport.hpp"
    47 #include "runtime/java.hpp"
    48 #include "runtime/javaCalls.hpp"
    49 #include "runtime/mutexLocker.hpp"
    50 #include "runtime/objectMonitor.hpp"
    51 #include "runtime/osThread.hpp"
    52 #include "runtime/perfMemory.hpp"
    53 #include "runtime/sharedRuntime.hpp"
    54 #include "runtime/statSampler.hpp"
    55 #include "runtime/stubRoutines.hpp"
    56 #include "runtime/thread.inline.hpp"
    57 #include "runtime/threadCritical.hpp"
    58 #include "runtime/timer.hpp"
    59 #include "services/attachListener.hpp"
    60 #include "services/memTracker.hpp"
    61 #include "services/runtimeService.hpp"
    62 #include "utilities/decoder.hpp"
    63 #include "utilities/defaultStream.hpp"
    64 #include "utilities/events.hpp"
    65 #include "utilities/growableArray.hpp"
    66 #include "utilities/vmError.hpp"
    68 // put OS-includes here
    69 # include <sys/types.h>
    70 # include <sys/mman.h>
    71 # include <sys/stat.h>
    72 # include <sys/select.h>
    73 # include <pthread.h>
    74 # include <signal.h>
    75 # include <errno.h>
    76 # include <dlfcn.h>
    77 # include <stdio.h>
    78 # include <unistd.h>
    79 # include <sys/resource.h>
    80 # include <pthread.h>
    81 # include <sys/stat.h>
    82 # include <sys/time.h>
    83 # include <sys/times.h>
    84 # include <sys/utsname.h>
    85 # include <sys/socket.h>
    86 # include <sys/wait.h>
    87 # include <time.h>
    88 # include <pwd.h>
    89 # include <poll.h>
    90 # include <semaphore.h>
    91 # include <fcntl.h>
    92 # include <string.h>
    93 # include <sys/param.h>
    94 # include <sys/sysctl.h>
    95 # include <sys/ipc.h>
    96 # include <sys/shm.h>
    97 #ifndef __APPLE__
    98 # include <link.h>
    99 #endif
   100 # include <stdint.h>
   101 # include <inttypes.h>
   102 # include <sys/ioctl.h>
   104 #if defined(__FreeBSD__) || defined(__NetBSD__)
   105 # include <elf.h>
   106 #endif
   108 #ifdef __APPLE__
   109 # include <mach/mach.h> // semaphore_* API
   110 # include <mach-o/dyld.h>
   111 # include <sys/proc_info.h>
   112 # include <objc/objc-auto.h>
   113 #endif
   115 #ifndef MAP_ANONYMOUS
   116 #define MAP_ANONYMOUS MAP_ANON
   117 #endif
   119 #define MAX_PATH    (2 * K)
   121 // for timer info max values which include all bits
   122 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
   124 #define LARGEPAGES_BIT (1 << 6)
   125 ////////////////////////////////////////////////////////////////////////////////
   126 // global variables
   127 julong os::Bsd::_physical_memory = 0;
   130 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
   131 pthread_t os::Bsd::_main_thread;
   132 int os::Bsd::_page_size = -1;
   134 static jlong initial_time_count=0;
   136 static int clock_tics_per_sec = 100;
   138 // For diagnostics to print a message once. see run_periodic_checks
   139 static sigset_t check_signal_done;
   140 static bool check_signals = true;
   142 static pid_t _initial_pid = 0;
   144 /* Signal number used to suspend/resume a thread */
   146 /* do not use any signal number less than SIGSEGV, see 4355769 */
   147 static int SR_signum = SIGUSR2;
   148 sigset_t SR_sigset;
   151 ////////////////////////////////////////////////////////////////////////////////
   152 // utility functions
   154 static int SR_initialize();
   155 static int SR_finalize();
   157 julong os::available_memory() {
   158   return Bsd::available_memory();
   159 }
   161 julong os::Bsd::available_memory() {
   162   // XXXBSD: this is just a stopgap implementation
   163   return physical_memory() >> 2;
   164 }
   166 julong os::physical_memory() {
   167   return Bsd::physical_memory();
   168 }
   170 julong os::allocatable_physical_memory(julong size) {
   171 #ifdef _LP64
   172   return size;
   173 #else
   174   julong result = MIN2(size, (julong)3800*M);
   175    if (!is_allocatable(result)) {
   176      // See comments under solaris for alignment considerations
   177      julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
   178      result =  MIN2(size, reasonable_size);
   179    }
   180    return result;
   181 #endif // _LP64
   182 }
   184 ////////////////////////////////////////////////////////////////////////////////
   185 // environment support
   187 bool os::getenv(const char* name, char* buf, int len) {
   188   const char* val = ::getenv(name);
   189   if (val != NULL && strlen(val) < (size_t)len) {
   190     strcpy(buf, val);
   191     return true;
   192   }
   193   if (len > 0) buf[0] = 0;  // return a null string
   194   return false;
   195 }
   198 // Return true if user is running as root.
   200 bool os::have_special_privileges() {
   201   static bool init = false;
   202   static bool privileges = false;
   203   if (!init) {
   204     privileges = (getuid() != geteuid()) || (getgid() != getegid());
   205     init = true;
   206   }
   207   return privileges;
   208 }
   212 // Cpu architecture string
   213 #if   defined(ZERO)
   214 static char cpu_arch[] = ZERO_LIBARCH;
   215 #elif defined(IA64)
   216 static char cpu_arch[] = "ia64";
   217 #elif defined(IA32)
   218 static char cpu_arch[] = "i386";
   219 #elif defined(AMD64)
   220 static char cpu_arch[] = "amd64";
   221 #elif defined(ARM)
   222 static char cpu_arch[] = "arm";
   223 #elif defined(PPC)
   224 static char cpu_arch[] = "ppc";
   225 #elif defined(SPARC)
   226 #  ifdef _LP64
   227 static char cpu_arch[] = "sparcv9";
   228 #  else
   229 static char cpu_arch[] = "sparc";
   230 #  endif
   231 #else
   232 #error Add appropriate cpu_arch setting
   233 #endif
   235 // Compiler variant
   236 #ifdef COMPILER2
   237 #define COMPILER_VARIANT "server"
   238 #else
   239 #define COMPILER_VARIANT "client"
   240 #endif
   243 void os::Bsd::initialize_system_info() {
   244   int mib[2];
   245   size_t len;
   246   int cpu_val;
   247   julong mem_val;
   249   /* get processors count via hw.ncpus sysctl */
   250   mib[0] = CTL_HW;
   251   mib[1] = HW_NCPU;
   252   len = sizeof(cpu_val);
   253   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
   254        assert(len == sizeof(cpu_val), "unexpected data size");
   255        set_processor_count(cpu_val);
   256   }
   257   else {
   258        set_processor_count(1);   // fallback
   259   }
   261   /* get physical memory via hw.memsize sysctl (hw.memsize is used
   262    * since it returns a 64 bit value)
   263    */
   264   mib[0] = CTL_HW;
   265   mib[1] = HW_MEMSIZE;
   266   len = sizeof(mem_val);
   267   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
   268        assert(len == sizeof(mem_val), "unexpected data size");
   269        _physical_memory = mem_val;
   270   } else {
   271        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
   272   }
   274 #ifdef __OpenBSD__
   275   {
   276        // limit _physical_memory memory view on OpenBSD since
   277        // datasize rlimit restricts us anyway.
   278        struct rlimit limits;
   279        getrlimit(RLIMIT_DATA, &limits);
   280        _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
   281   }
   282 #endif
   283 }
   285 #ifdef __APPLE__
   286 static const char *get_home() {
   287   const char *home_dir = ::getenv("HOME");
   288   if ((home_dir == NULL) || (*home_dir == '\0')) {
   289     struct passwd *passwd_info = getpwuid(geteuid());
   290     if (passwd_info != NULL) {
   291       home_dir = passwd_info->pw_dir;
   292     }
   293   }
   295   return home_dir;
   296 }
   297 #endif
   299 void os::init_system_properties_values() {
   300 //  char arch[12];
   301 //  sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
   303   // The next steps are taken in the product version:
   304   //
   305   // Obtain the JAVA_HOME value from the location of libjvm.so.
   306   // This library should be located at:
   307   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
   308   //
   309   // If "/jre/lib/" appears at the right place in the path, then we
   310   // assume libjvm.so is installed in a JDK and we use this path.
   311   //
   312   // Otherwise exit with message: "Could not create the Java virtual machine."
   313   //
   314   // The following extra steps are taken in the debugging version:
   315   //
   316   // If "/jre/lib/" does NOT appear at the right place in the path
   317   // instead of exit check for $JAVA_HOME environment variable.
   318   //
   319   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
   320   // then we append a fake suffix "hotspot/libjvm.so" to this path so
   321   // it looks like libjvm.so is installed there
   322   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
   323   //
   324   // Otherwise exit.
   325   //
   326   // Important note: if the location of libjvm.so changes this
   327   // code needs to be changed accordingly.
   329   // The next few definitions allow the code to be verbatim:
   330 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
   331 #define getenv(n) ::getenv(n)
   333 /*
   334  * See ld(1):
   335  *      The linker uses the following search paths to locate required
   336  *      shared libraries:
   337  *        1: ...
   338  *        ...
   339  *        7: The default directories, normally /lib and /usr/lib.
   340  */
   341 #ifndef DEFAULT_LIBPATH
   342 #define DEFAULT_LIBPATH "/lib:/usr/lib"
   343 #endif
   345 #define EXTENSIONS_DIR  "/lib/ext"
   346 #define ENDORSED_DIR    "/lib/endorsed"
   347 #define REG_DIR         "/usr/java/packages"
   349 #ifdef __APPLE__
   350 #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
   351 #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
   352         const char *user_home_dir = get_home();
   353         // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir
   354         int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
   355             sizeof(SYS_EXTENSIONS_DIRS);
   356 #endif
   358   {
   359     /* sysclasspath, java_home, dll_dir */
   360     {
   361         char *home_path;
   362         char *dll_path;
   363         char *pslash;
   364         char buf[MAXPATHLEN];
   365         os::jvm_path(buf, sizeof(buf));
   367         // Found the full path to libjvm.so.
   368         // Now cut the path to <java_home>/jre if we can.
   369         *(strrchr(buf, '/')) = '\0';  /* get rid of /libjvm.so */
   370         pslash = strrchr(buf, '/');
   371         if (pslash != NULL)
   372             *pslash = '\0';           /* get rid of /{client|server|hotspot} */
   373         dll_path = malloc(strlen(buf) + 1);
   374         if (dll_path == NULL)
   375             return;
   376         strcpy(dll_path, buf);
   377         Arguments::set_dll_dir(dll_path);
   379         if (pslash != NULL) {
   380             pslash = strrchr(buf, '/');
   381             if (pslash != NULL) {
   382                 *pslash = '\0';       /* get rid of /<arch> (/lib on macosx) */
   383 #ifndef __APPLE__
   384                 pslash = strrchr(buf, '/');
   385                 if (pslash != NULL)
   386                     *pslash = '\0';   /* get rid of /lib */
   387 #endif
   388             }
   389         }
   391         home_path = malloc(strlen(buf) + 1);
   392         if (home_path == NULL)
   393             return;
   394         strcpy(home_path, buf);
   395         Arguments::set_java_home(home_path);
   397         if (!set_boot_path('/', ':'))
   398             return;
   399     }
   401     /*
   402      * Where to look for native libraries
   403      *
   404      * Note: Due to a legacy implementation, most of the library path
   405      * is set in the launcher.  This was to accomodate linking restrictions
   406      * on legacy Bsd implementations (which are no longer supported).
   407      * Eventually, all the library path setting will be done here.
   408      *
   409      * However, to prevent the proliferation of improperly built native
   410      * libraries, the new path component /usr/java/packages is added here.
   411      * Eventually, all the library path setting will be done here.
   412      */
   413     {
   414         char *ld_library_path;
   416         /*
   417          * Construct the invariant part of ld_library_path. Note that the
   418          * space for the colon and the trailing null are provided by the
   419          * nulls included by the sizeof operator (so actually we allocate
   420          * a byte more than necessary).
   421          */
   422 #ifdef __APPLE__
   423         ld_library_path = (char *) malloc(system_ext_size);
   424         sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir);
   425 #else
   426         ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
   427             strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
   428         sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
   429 #endif
   431         /*
   432          * Get the user setting of LD_LIBRARY_PATH, and prepended it.  It
   433          * should always exist (until the legacy problem cited above is
   434          * addressed).
   435          */
   436 #ifdef __APPLE__
   437         // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper
   438         char *l = getenv("JAVA_LIBRARY_PATH");
   439         if (l != NULL) {
   440             char *t = ld_library_path;
   441             /* That's +1 for the colon and +1 for the trailing '\0' */
   442             ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1);
   443             sprintf(ld_library_path, "%s:%s", l, t);
   444             free(t);
   445         }
   447         char *v = getenv("DYLD_LIBRARY_PATH");
   448 #else
   449         char *v = getenv("LD_LIBRARY_PATH");
   450 #endif
   451         if (v != NULL) {
   452             char *t = ld_library_path;
   453             /* That's +1 for the colon and +1 for the trailing '\0' */
   454             ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
   455             sprintf(ld_library_path, "%s:%s", v, t);
   456             free(t);
   457         }
   459 #ifdef __APPLE__
   460         // Apple's Java6 has "." at the beginning of java.library.path.
   461         // OpenJDK on Windows has "." at the end of java.library.path.
   462         // OpenJDK on Linux and Solaris don't have "." in java.library.path
   463         // at all. To ease the transition from Apple's Java6 to OpenJDK7,
   464         // "." is appended to the end of java.library.path. Yes, this
   465         // could cause a change in behavior, but Apple's Java6 behavior
   466         // can be achieved by putting "." at the beginning of the
   467         // JAVA_LIBRARY_PATH environment variable.
   468         {
   469             char *t = ld_library_path;
   470             // that's +3 for appending ":." and the trailing '\0'
   471             ld_library_path = (char *) malloc(strlen(t) + 3);
   472             sprintf(ld_library_path, "%s:%s", t, ".");
   473             free(t);
   474         }
   475 #endif
   477         Arguments::set_library_path(ld_library_path);
   478     }
   480     /*
   481      * Extensions directories.
   482      *
   483      * Note that the space for the colon and the trailing null are provided
   484      * by the nulls included by the sizeof operator (so actually one byte more
   485      * than necessary is allocated).
   486      */
   487     {
   488 #ifdef __APPLE__
   489         char *buf = malloc(strlen(Arguments::get_java_home()) +
   490             sizeof(EXTENSIONS_DIR) + system_ext_size);
   491         sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":"
   492             SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home());
   493 #else
   494         char *buf = malloc(strlen(Arguments::get_java_home()) +
   495             sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
   496         sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
   497             Arguments::get_java_home());
   498 #endif
   500         Arguments::set_ext_dirs(buf);
   501     }
   503     /* Endorsed standards default directory. */
   504     {
   505         char * buf;
   506         buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
   507         sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
   508         Arguments::set_endorsed_dirs(buf);
   509     }
   510   }
   512 #ifdef __APPLE__
   513 #undef SYS_EXTENSIONS_DIR
   514 #endif
   515 #undef malloc
   516 #undef getenv
   517 #undef EXTENSIONS_DIR
   518 #undef ENDORSED_DIR
   520   // Done
   521   return;
   522 }
   524 ////////////////////////////////////////////////////////////////////////////////
   525 // breakpoint support
   527 void os::breakpoint() {
   528   BREAKPOINT;
   529 }
   531 extern "C" void breakpoint() {
   532   // use debugger to set breakpoint here
   533 }
   535 ////////////////////////////////////////////////////////////////////////////////
   536 // signal support
   538 debug_only(static bool signal_sets_initialized = false);
   539 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
   541 bool os::Bsd::is_sig_ignored(int sig) {
   542       struct sigaction oact;
   543       sigaction(sig, (struct sigaction*)NULL, &oact);
   544       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
   545                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
   546       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
   547            return true;
   548       else
   549            return false;
   550 }
   552 void os::Bsd::signal_sets_init() {
   553   // Should also have an assertion stating we are still single-threaded.
   554   assert(!signal_sets_initialized, "Already initialized");
   555   // Fill in signals that are necessarily unblocked for all threads in
   556   // the VM. Currently, we unblock the following signals:
   557   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
   558   //                         by -Xrs (=ReduceSignalUsage));
   559   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
   560   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
   561   // the dispositions or masks wrt these signals.
   562   // Programs embedding the VM that want to use the above signals for their
   563   // own purposes must, at this time, use the "-Xrs" option to prevent
   564   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
   565   // (See bug 4345157, and other related bugs).
   566   // In reality, though, unblocking these signals is really a nop, since
   567   // these signals are not blocked by default.
   568   sigemptyset(&unblocked_sigs);
   569   sigemptyset(&allowdebug_blocked_sigs);
   570   sigaddset(&unblocked_sigs, SIGILL);
   571   sigaddset(&unblocked_sigs, SIGSEGV);
   572   sigaddset(&unblocked_sigs, SIGBUS);
   573   sigaddset(&unblocked_sigs, SIGFPE);
   574   sigaddset(&unblocked_sigs, SR_signum);
   576   if (!ReduceSignalUsage) {
   577    if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
   578       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
   579       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
   580    }
   581    if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
   582       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
   583       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
   584    }
   585    if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
   586       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
   587       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
   588    }
   589   }
   590   // Fill in signals that are blocked by all but the VM thread.
   591   sigemptyset(&vm_sigs);
   592   if (!ReduceSignalUsage)
   593     sigaddset(&vm_sigs, BREAK_SIGNAL);
   594   debug_only(signal_sets_initialized = true);
   596 }
   598 // These are signals that are unblocked while a thread is running Java.
   599 // (For some reason, they get blocked by default.)
   600 sigset_t* os::Bsd::unblocked_signals() {
   601   assert(signal_sets_initialized, "Not initialized");
   602   return &unblocked_sigs;
   603 }
   605 // These are the signals that are blocked while a (non-VM) thread is
   606 // running Java. Only the VM thread handles these signals.
   607 sigset_t* os::Bsd::vm_signals() {
   608   assert(signal_sets_initialized, "Not initialized");
   609   return &vm_sigs;
   610 }
   612 // These are signals that are blocked during cond_wait to allow debugger in
   613 sigset_t* os::Bsd::allowdebug_blocked_signals() {
   614   assert(signal_sets_initialized, "Not initialized");
   615   return &allowdebug_blocked_sigs;
   616 }
   618 void os::Bsd::hotspot_sigmask(Thread* thread) {
   620   //Save caller's signal mask before setting VM signal mask
   621   sigset_t caller_sigmask;
   622   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
   624   OSThread* osthread = thread->osthread();
   625   osthread->set_caller_sigmask(caller_sigmask);
   627   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
   629   if (!ReduceSignalUsage) {
   630     if (thread->is_VM_thread()) {
   631       // Only the VM thread handles BREAK_SIGNAL ...
   632       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
   633     } else {
   634       // ... all other threads block BREAK_SIGNAL
   635       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
   636     }
   637   }
   638 }
   641 //////////////////////////////////////////////////////////////////////////////
   642 // create new thread
   644 static address highest_vm_reserved_address();
   646 // check if it's safe to start a new thread
   647 static bool _thread_safety_check(Thread* thread) {
   648   return true;
   649 }
   651 #ifdef __APPLE__
   652 // library handle for calling objc_registerThreadWithCollector()
   653 // without static linking to the libobjc library
   654 #define OBJC_LIB "/usr/lib/libobjc.dylib"
   655 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
   656 typedef void (*objc_registerThreadWithCollector_t)();
   657 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
   658 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
   659 #endif
   661 #ifdef __APPLE__
   662 static uint64_t locate_unique_thread_id() {
   663   // Additional thread_id used to correlate threads in SA
   664   thread_identifier_info_data_t     m_ident_info;
   665   mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
   667   thread_info(::mach_thread_self(), THREAD_IDENTIFIER_INFO,
   668               (thread_info_t) &m_ident_info, &count);
   669   return m_ident_info.thread_id;
   670 }
   671 #endif
   673 // Thread start routine for all newly created threads
   674 static void *java_start(Thread *thread) {
   675   // Try to randomize the cache line index of hot stack frames.
   676   // This helps when threads of the same stack traces evict each other's
   677   // cache lines. The threads can be either from the same JVM instance, or
   678   // from different JVM instances. The benefit is especially true for
   679   // processors with hyperthreading technology.
   680   static int counter = 0;
   681   int pid = os::current_process_id();
   682   alloca(((pid ^ counter++) & 7) * 128);
   684   ThreadLocalStorage::set_thread(thread);
   686   OSThread* osthread = thread->osthread();
   687   Monitor* sync = osthread->startThread_lock();
   689   // non floating stack BsdThreads needs extra check, see above
   690   if (!_thread_safety_check(thread)) {
   691     // notify parent thread
   692     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   693     osthread->set_state(ZOMBIE);
   694     sync->notify_all();
   695     return NULL;
   696   }
   698 #ifdef __APPLE__
   699   // thread_id is mach thread on macos
   700   osthread->set_thread_id(::mach_thread_self());
   701   osthread->set_unique_thread_id(locate_unique_thread_id());
   702 #else
   703   // thread_id is pthread_id on BSD
   704   osthread->set_thread_id(::pthread_self());
   705 #endif
   706   // initialize signal mask for this thread
   707   os::Bsd::hotspot_sigmask(thread);
   709   // initialize floating point control register
   710   os::Bsd::init_thread_fpu_state();
   712 #ifdef __APPLE__
   713   // register thread with objc gc
   714   if (objc_registerThreadWithCollectorFunction != NULL) {
   715     objc_registerThreadWithCollectorFunction();
   716   }
   717 #endif
   719   // handshaking with parent thread
   720   {
   721     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   723     // notify parent thread
   724     osthread->set_state(INITIALIZED);
   725     sync->notify_all();
   727     // wait until os::start_thread()
   728     while (osthread->get_state() == INITIALIZED) {
   729       sync->wait(Mutex::_no_safepoint_check_flag);
   730     }
   731   }
   733   // call one more level start routine
   734   thread->run();
   736   return 0;
   737 }
   739 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
   740   assert(thread->osthread() == NULL, "caller responsible");
   742   // Allocate the OSThread object
   743   OSThread* osthread = new OSThread(NULL, NULL);
   744   if (osthread == NULL) {
   745     return false;
   746   }
   748   // set the correct thread state
   749   osthread->set_thread_type(thr_type);
   751   // Initial state is ALLOCATED but not INITIALIZED
   752   osthread->set_state(ALLOCATED);
   754   thread->set_osthread(osthread);
   756   // init thread attributes
   757   pthread_attr_t attr;
   758   pthread_attr_init(&attr);
   759   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   761   // stack size
   762   if (os::Bsd::supports_variable_stack_size()) {
   763     // calculate stack size if it's not specified by caller
   764     if (stack_size == 0) {
   765       stack_size = os::Bsd::default_stack_size(thr_type);
   767       switch (thr_type) {
   768       case os::java_thread:
   769         // Java threads use ThreadStackSize which default value can be
   770         // changed with the flag -Xss
   771         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
   772         stack_size = JavaThread::stack_size_at_create();
   773         break;
   774       case os::compiler_thread:
   775         if (CompilerThreadStackSize > 0) {
   776           stack_size = (size_t)(CompilerThreadStackSize * K);
   777           break;
   778         } // else fall through:
   779           // use VMThreadStackSize if CompilerThreadStackSize is not defined
   780       case os::vm_thread:
   781       case os::pgc_thread:
   782       case os::cgc_thread:
   783       case os::watcher_thread:
   784         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
   785         break;
   786       }
   787     }
   789     stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
   790     pthread_attr_setstacksize(&attr, stack_size);
   791   } else {
   792     // let pthread_create() pick the default value.
   793   }
   795   ThreadState state;
   797   {
   798     pthread_t tid;
   799     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
   801     pthread_attr_destroy(&attr);
   803     if (ret != 0) {
   804       if (PrintMiscellaneous && (Verbose || WizardMode)) {
   805         perror("pthread_create()");
   806       }
   807       // Need to clean up stuff we've allocated so far
   808       thread->set_osthread(NULL);
   809       delete osthread;
   810       return false;
   811     }
   813     // Store pthread info into the OSThread
   814     osthread->set_pthread_id(tid);
   816     // Wait until child thread is either initialized or aborted
   817     {
   818       Monitor* sync_with_child = osthread->startThread_lock();
   819       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   820       while ((state = osthread->get_state()) == ALLOCATED) {
   821         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
   822       }
   823     }
   825   }
   827   // Aborted due to thread limit being reached
   828   if (state == ZOMBIE) {
   829       thread->set_osthread(NULL);
   830       delete osthread;
   831       return false;
   832   }
   834   // The thread is returned suspended (in state INITIALIZED),
   835   // and is started higher up in the call chain
   836   assert(state == INITIALIZED, "race condition");
   837   return true;
   838 }
   840 /////////////////////////////////////////////////////////////////////////////
   841 // attach existing thread
   843 // bootstrap the main thread
   844 bool os::create_main_thread(JavaThread* thread) {
   845   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
   846   return create_attached_thread(thread);
   847 }
   849 bool os::create_attached_thread(JavaThread* thread) {
   850 #ifdef ASSERT
   851     thread->verify_not_published();
   852 #endif
   854   // Allocate the OSThread object
   855   OSThread* osthread = new OSThread(NULL, NULL);
   857   if (osthread == NULL) {
   858     return false;
   859   }
   861   // Store pthread info into the OSThread
   862 #ifdef __APPLE__
   863   osthread->set_thread_id(::mach_thread_self());
   864   osthread->set_unique_thread_id(locate_unique_thread_id());
   865 #else
   866   osthread->set_thread_id(::pthread_self());
   867 #endif
   868   osthread->set_pthread_id(::pthread_self());
   870   // initialize floating point control register
   871   os::Bsd::init_thread_fpu_state();
   873   // Initial thread state is RUNNABLE
   874   osthread->set_state(RUNNABLE);
   876   thread->set_osthread(osthread);
   878   // initialize signal mask for this thread
   879   // and save the caller's signal mask
   880   os::Bsd::hotspot_sigmask(thread);
   882   return true;
   883 }
   885 void os::pd_start_thread(Thread* thread) {
   886   OSThread * osthread = thread->osthread();
   887   assert(osthread->get_state() != INITIALIZED, "just checking");
   888   Monitor* sync_with_child = osthread->startThread_lock();
   889   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   890   sync_with_child->notify();
   891 }
   893 // Free Bsd resources related to the OSThread
   894 void os::free_thread(OSThread* osthread) {
   895   assert(osthread != NULL, "osthread not set");
   897   if (Thread::current()->osthread() == osthread) {
   898     // Restore caller's signal mask
   899     sigset_t sigmask = osthread->caller_sigmask();
   900     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   901    }
   903   delete osthread;
   904 }
   906 //////////////////////////////////////////////////////////////////////////////
   907 // thread local storage
   909 int os::allocate_thread_local_storage() {
   910   pthread_key_t key;
   911   int rslt = pthread_key_create(&key, NULL);
   912   assert(rslt == 0, "cannot allocate thread local storage");
   913   return (int)key;
   914 }
   916 // Note: This is currently not used by VM, as we don't destroy TLS key
   917 // on VM exit.
   918 void os::free_thread_local_storage(int index) {
   919   int rslt = pthread_key_delete((pthread_key_t)index);
   920   assert(rslt == 0, "invalid index");
   921 }
   923 void os::thread_local_storage_at_put(int index, void* value) {
   924   int rslt = pthread_setspecific((pthread_key_t)index, value);
   925   assert(rslt == 0, "pthread_setspecific failed");
   926 }
   928 extern "C" Thread* get_thread() {
   929   return ThreadLocalStorage::thread();
   930 }
   933 ////////////////////////////////////////////////////////////////////////////////
   934 // time support
   936 // Time since start-up in seconds to a fine granularity.
   937 // Used by VMSelfDestructTimer and the MemProfiler.
   938 double os::elapsedTime() {
   940   return (double)(os::elapsed_counter()) * 0.000001;
   941 }
   943 jlong os::elapsed_counter() {
   944   timeval time;
   945   int status = gettimeofday(&time, NULL);
   946   return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
   947 }
   949 jlong os::elapsed_frequency() {
   950   return (1000 * 1000);
   951 }
   953 // XXX: For now, code this as if BSD does not support vtime.
   954 bool os::supports_vtime() { return false; }
   955 bool os::enable_vtime()   { return false; }
   956 bool os::vtime_enabled()  { return false; }
   957 double os::elapsedVTime() {
   958   // better than nothing, but not much
   959   return elapsedTime();
   960 }
   962 jlong os::javaTimeMillis() {
   963   timeval time;
   964   int status = gettimeofday(&time, NULL);
   965   assert(status != -1, "bsd error");
   966   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   967 }
   969 #ifndef CLOCK_MONOTONIC
   970 #define CLOCK_MONOTONIC (1)
   971 #endif
   973 #ifdef __APPLE__
   974 void os::Bsd::clock_init() {
   975         // XXXDARWIN: Investigate replacement monotonic clock
   976 }
   977 #else
   978 void os::Bsd::clock_init() {
   979   struct timespec res;
   980   struct timespec tp;
   981   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
   982       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
   983     // yes, monotonic clock is supported
   984     _clock_gettime = ::clock_gettime;
   985   }
   986 }
   987 #endif
   990 jlong os::javaTimeNanos() {
   991   if (Bsd::supports_monotonic_clock()) {
   992     struct timespec tp;
   993     int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
   994     assert(status == 0, "gettime error");
   995     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
   996     return result;
   997   } else {
   998     timeval time;
   999     int status = gettimeofday(&time, NULL);
  1000     assert(status != -1, "bsd error");
  1001     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
  1002     return 1000 * usecs;
  1006 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
  1007   if (Bsd::supports_monotonic_clock()) {
  1008     info_ptr->max_value = ALL_64_BITS;
  1010     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
  1011     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
  1012     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
  1013   } else {
  1014     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
  1015     info_ptr->max_value = ALL_64_BITS;
  1017     // gettimeofday is a real time clock so it skips
  1018     info_ptr->may_skip_backward = true;
  1019     info_ptr->may_skip_forward = true;
  1022   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
  1025 // Return the real, user, and system times in seconds from an
  1026 // arbitrary fixed point in the past.
  1027 bool os::getTimesSecs(double* process_real_time,
  1028                       double* process_user_time,
  1029                       double* process_system_time) {
  1030   struct tms ticks;
  1031   clock_t real_ticks = times(&ticks);
  1033   if (real_ticks == (clock_t) (-1)) {
  1034     return false;
  1035   } else {
  1036     double ticks_per_second = (double) clock_tics_per_sec;
  1037     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
  1038     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
  1039     *process_real_time = ((double) real_ticks) / ticks_per_second;
  1041     return true;
  1046 char * os::local_time_string(char *buf, size_t buflen) {
  1047   struct tm t;
  1048   time_t long_time;
  1049   time(&long_time);
  1050   localtime_r(&long_time, &t);
  1051   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  1052                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
  1053                t.tm_hour, t.tm_min, t.tm_sec);
  1054   return buf;
  1057 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
  1058   return localtime_r(clock, res);
  1061 ////////////////////////////////////////////////////////////////////////////////
  1062 // runtime exit support
  1064 // Note: os::shutdown() might be called very early during initialization, or
  1065 // called from signal handler. Before adding something to os::shutdown(), make
  1066 // sure it is async-safe and can handle partially initialized VM.
  1067 void os::shutdown() {
  1069   // allow PerfMemory to attempt cleanup of any persistent resources
  1070   perfMemory_exit();
  1072   // needs to remove object in file system
  1073   AttachListener::abort();
  1075   // flush buffered output, finish log files
  1076   ostream_abort();
  1078   // Check for abort hook
  1079   abort_hook_t abort_hook = Arguments::abort_hook();
  1080   if (abort_hook != NULL) {
  1081     abort_hook();
  1086 // Note: os::abort() might be called very early during initialization, or
  1087 // called from signal handler. Before adding something to os::abort(), make
  1088 // sure it is async-safe and can handle partially initialized VM.
  1089 void os::abort(bool dump_core) {
  1090   os::shutdown();
  1091   if (dump_core) {
  1092 #ifndef PRODUCT
  1093     fdStream out(defaultStream::output_fd());
  1094     out.print_raw("Current thread is ");
  1095     char buf[16];
  1096     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
  1097     out.print_raw_cr(buf);
  1098     out.print_raw_cr("Dumping core ...");
  1099 #endif
  1100     ::abort(); // dump core
  1103   ::exit(1);
  1106 // Die immediately, no exit hook, no abort hook, no cleanup.
  1107 void os::die() {
  1108   // _exit() on BsdThreads only kills current thread
  1109   ::abort();
  1112 // unused on bsd for now.
  1113 void os::set_error_file(const char *logfile) {}
  1116 // This method is a copy of JDK's sysGetLastErrorString
  1117 // from src/solaris/hpi/src/system_md.c
  1119 size_t os::lasterror(char *buf, size_t len) {
  1121   if (errno == 0)  return 0;
  1123   const char *s = ::strerror(errno);
  1124   size_t n = ::strlen(s);
  1125   if (n >= len) {
  1126     n = len - 1;
  1128   ::strncpy(buf, s, n);
  1129   buf[n] = '\0';
  1130   return n;
  1133 intx os::current_thread_id() {
  1134 #ifdef __APPLE__
  1135   return (intx)::mach_thread_self();
  1136 #else
  1137   return (intx)::pthread_self();
  1138 #endif
  1140 int os::current_process_id() {
  1142   // Under the old bsd thread library, bsd gives each thread
  1143   // its own process id. Because of this each thread will return
  1144   // a different pid if this method were to return the result
  1145   // of getpid(2). Bsd provides no api that returns the pid
  1146   // of the launcher thread for the vm. This implementation
  1147   // returns a unique pid, the pid of the launcher thread
  1148   // that starts the vm 'process'.
  1150   // Under the NPTL, getpid() returns the same pid as the
  1151   // launcher thread rather than a unique pid per thread.
  1152   // Use gettid() if you want the old pre NPTL behaviour.
  1154   // if you are looking for the result of a call to getpid() that
  1155   // returns a unique pid for the calling thread, then look at the
  1156   // OSThread::thread_id() method in osThread_bsd.hpp file
  1158   return (int)(_initial_pid ? _initial_pid : getpid());
  1161 // DLL functions
  1163 #define JNI_LIB_PREFIX "lib"
  1164 #ifdef __APPLE__
  1165 #define JNI_LIB_SUFFIX ".dylib"
  1166 #else
  1167 #define JNI_LIB_SUFFIX ".so"
  1168 #endif
  1170 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1172 // This must be hard coded because it's the system's temporary
  1173 // directory not the java application's temp directory, ala java.io.tmpdir.
  1174 #ifdef __APPLE__
  1175 // macosx has a secure per-user temporary directory
  1176 char temp_path_storage[PATH_MAX];
  1177 const char* os::get_temp_directory() {
  1178   static char *temp_path = NULL;
  1179   if (temp_path == NULL) {
  1180     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
  1181     if (pathSize == 0 || pathSize > PATH_MAX) {
  1182       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
  1184     temp_path = temp_path_storage;
  1186   return temp_path;
  1188 #else /* __APPLE__ */
  1189 const char* os::get_temp_directory() { return "/tmp"; }
  1190 #endif /* __APPLE__ */
  1192 static bool file_exists(const char* filename) {
  1193   struct stat statbuf;
  1194   if (filename == NULL || strlen(filename) == 0) {
  1195     return false;
  1197   return os::stat(filename, &statbuf) == 0;
  1200 bool os::dll_build_name(char* buffer, size_t buflen,
  1201                         const char* pname, const char* fname) {
  1202   bool retval = false;
  1203   // Copied from libhpi
  1204   const size_t pnamelen = pname ? strlen(pname) : 0;
  1206   // Return error on buffer overflow.
  1207   if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
  1208     return retval;
  1211   if (pnamelen == 0) {
  1212     snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
  1213     retval = true;
  1214   } else if (strchr(pname, *os::path_separator()) != NULL) {
  1215     int n;
  1216     char** pelements = split_path(pname, &n);
  1217     for (int i = 0 ; i < n ; i++) {
  1218       // Really shouldn't be NULL, but check can't hurt
  1219       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1220         continue; // skip the empty path values
  1222       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1223           pelements[i], fname);
  1224       if (file_exists(buffer)) {
  1225         retval = true;
  1226         break;
  1229     // release the storage
  1230     for (int i = 0 ; i < n ; i++) {
  1231       if (pelements[i] != NULL) {
  1232         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
  1235     if (pelements != NULL) {
  1236       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
  1238   } else {
  1239     snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
  1240     retval = true;
  1242   return retval;
  1245 const char* os::get_current_directory(char *buf, int buflen) {
  1246   return getcwd(buf, buflen);
  1249 // check if addr is inside libjvm.so
  1250 bool os::address_is_in_vm(address addr) {
  1251   static address libjvm_base_addr;
  1252   Dl_info dlinfo;
  1254   if (libjvm_base_addr == NULL) {
  1255     dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
  1256     libjvm_base_addr = (address)dlinfo.dli_fbase;
  1257     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
  1260   if (dladdr((void *)addr, &dlinfo)) {
  1261     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
  1264   return false;
  1268 #define MACH_MAXSYMLEN 256
  1270 bool os::dll_address_to_function_name(address addr, char *buf,
  1271                                       int buflen, int *offset) {
  1272   Dl_info dlinfo;
  1273   char localbuf[MACH_MAXSYMLEN];
  1275   // dladdr will find names of dynamic functions only, but does
  1276   // it set dli_fbase with mach_header address when it "fails" ?
  1277   if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
  1278     if (buf != NULL) {
  1279       if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1280         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
  1283     if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1284     return true;
  1285   } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
  1286     if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1287        buf, buflen, offset, dlinfo.dli_fname)) {
  1288        return true;
  1292   // Handle non-dymanic manually:
  1293   if (dlinfo.dli_fbase != NULL &&
  1294       Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) {
  1295     if(!Decoder::demangle(localbuf, buf, buflen)) {
  1296       jio_snprintf(buf, buflen, "%s", localbuf);
  1298     return true;
  1300   if (buf != NULL) buf[0] = '\0';
  1301   if (offset != NULL) *offset = -1;
  1302   return false;
  1305 // ported from solaris version
  1306 bool os::dll_address_to_library_name(address addr, char* buf,
  1307                                      int buflen, int* offset) {
  1308   Dl_info dlinfo;
  1310   if (dladdr((void*)addr, &dlinfo)){
  1311      if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
  1312      if (offset) *offset = addr - (address)dlinfo.dli_fbase;
  1313      return true;
  1314   } else {
  1315      if (buf) buf[0] = '\0';
  1316      if (offset) *offset = -1;
  1317      return false;
  1321 // Loads .dll/.so and
  1322 // in case of error it checks if .dll/.so was built for the
  1323 // same architecture as Hotspot is running on
  1325 #ifdef __APPLE__
  1326 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
  1327   void * result= ::dlopen(filename, RTLD_LAZY);
  1328   if (result != NULL) {
  1329     // Successful loading
  1330     return result;
  1333   // Read system error message into ebuf
  1334   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1335   ebuf[ebuflen-1]='\0';
  1337   return NULL;
  1339 #else
  1340 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1342   void * result= ::dlopen(filename, RTLD_LAZY);
  1343   if (result != NULL) {
  1344     // Successful loading
  1345     return result;
  1348   Elf32_Ehdr elf_head;
  1350   // Read system error message into ebuf
  1351   // It may or may not be overwritten below
  1352   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1353   ebuf[ebuflen-1]='\0';
  1354   int diag_msg_max_length=ebuflen-strlen(ebuf);
  1355   char* diag_msg_buf=ebuf+strlen(ebuf);
  1357   if (diag_msg_max_length==0) {
  1358     // No more space in ebuf for additional diagnostics message
  1359     return NULL;
  1363   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
  1365   if (file_descriptor < 0) {
  1366     // Can't open library, report dlerror() message
  1367     return NULL;
  1370   bool failed_to_read_elf_head=
  1371     (sizeof(elf_head)!=
  1372         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
  1374   ::close(file_descriptor);
  1375   if (failed_to_read_elf_head) {
  1376     // file i/o error - report dlerror() msg
  1377     return NULL;
  1380   typedef struct {
  1381     Elf32_Half  code;         // Actual value as defined in elf.h
  1382     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
  1383     char        elf_class;    // 32 or 64 bit
  1384     char        endianess;    // MSB or LSB
  1385     char*       name;         // String representation
  1386   } arch_t;
  1388   #ifndef EM_486
  1389   #define EM_486          6               /* Intel 80486 */
  1390   #endif
  1392   #ifndef EM_MIPS_RS3_LE
  1393   #define EM_MIPS_RS3_LE  10              /* MIPS */
  1394   #endif
  1396   #ifndef EM_PPC64
  1397   #define EM_PPC64        21              /* PowerPC64 */
  1398   #endif
  1400   #ifndef EM_S390
  1401   #define EM_S390         22              /* IBM System/390 */
  1402   #endif
  1404   #ifndef EM_IA_64
  1405   #define EM_IA_64        50              /* HP/Intel IA-64 */
  1406   #endif
  1408   #ifndef EM_X86_64
  1409   #define EM_X86_64       62              /* AMD x86-64 */
  1410   #endif
  1412   static const arch_t arch_array[]={
  1413     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1414     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1415     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
  1416     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
  1417     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1418     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1419     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
  1420     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
  1421     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
  1422     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
  1423     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
  1424     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
  1425     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
  1426     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
  1427     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1428     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1429   };
  1431   #if  (defined IA32)
  1432     static  Elf32_Half running_arch_code=EM_386;
  1433   #elif   (defined AMD64)
  1434     static  Elf32_Half running_arch_code=EM_X86_64;
  1435   #elif  (defined IA64)
  1436     static  Elf32_Half running_arch_code=EM_IA_64;
  1437   #elif  (defined __sparc) && (defined _LP64)
  1438     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1439   #elif  (defined __sparc) && (!defined _LP64)
  1440     static  Elf32_Half running_arch_code=EM_SPARC;
  1441   #elif  (defined __powerpc64__)
  1442     static  Elf32_Half running_arch_code=EM_PPC64;
  1443   #elif  (defined __powerpc__)
  1444     static  Elf32_Half running_arch_code=EM_PPC;
  1445   #elif  (defined ARM)
  1446     static  Elf32_Half running_arch_code=EM_ARM;
  1447   #elif  (defined S390)
  1448     static  Elf32_Half running_arch_code=EM_S390;
  1449   #elif  (defined ALPHA)
  1450     static  Elf32_Half running_arch_code=EM_ALPHA;
  1451   #elif  (defined MIPSEL)
  1452     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1453   #elif  (defined PARISC)
  1454     static  Elf32_Half running_arch_code=EM_PARISC;
  1455   #elif  (defined MIPS)
  1456     static  Elf32_Half running_arch_code=EM_MIPS;
  1457   #elif  (defined M68K)
  1458     static  Elf32_Half running_arch_code=EM_68K;
  1459   #else
  1460     #error Method os::dll_load requires that one of following is defined:\
  1461          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1462   #endif
  1464   // Identify compatability class for VM's architecture and library's architecture
  1465   // Obtain string descriptions for architectures
  1467   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
  1468   int running_arch_index=-1;
  1470   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
  1471     if (running_arch_code == arch_array[i].code) {
  1472       running_arch_index    = i;
  1474     if (lib_arch.code == arch_array[i].code) {
  1475       lib_arch.compat_class = arch_array[i].compat_class;
  1476       lib_arch.name         = arch_array[i].name;
  1480   assert(running_arch_index != -1,
  1481     "Didn't find running architecture code (running_arch_code) in arch_array");
  1482   if (running_arch_index == -1) {
  1483     // Even though running architecture detection failed
  1484     // we may still continue with reporting dlerror() message
  1485     return NULL;
  1488   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
  1489     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
  1490     return NULL;
  1493 #ifndef S390
  1494   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
  1495     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
  1496     return NULL;
  1498 #endif // !S390
  1500   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1501     if ( lib_arch.name!=NULL ) {
  1502       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1503         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1504         lib_arch.name, arch_array[running_arch_index].name);
  1505     } else {
  1506       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1507       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1508         lib_arch.code,
  1509         arch_array[running_arch_index].name);
  1513   return NULL;
  1515 #endif /* !__APPLE__ */
  1517 // XXX: Do we need a lock around this as per Linux?
  1518 void* os::dll_lookup(void* handle, const char* name) {
  1519   return dlsym(handle, name);
  1523 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1524   int fd = ::open(filename, O_RDONLY);
  1525   if (fd == -1) {
  1526      return false;
  1529   char buf[32];
  1530   int bytes;
  1531   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1532     st->print_raw(buf, bytes);
  1535   ::close(fd);
  1537   return true;
  1540 void os::print_dll_info(outputStream *st) {
  1541    st->print_cr("Dynamic libraries:");
  1542 #ifdef RTLD_DI_LINKMAP
  1543     Dl_info dli;
  1544     void *handle;
  1545     Link_map *map;
  1546     Link_map *p;
  1548     if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) {
  1549         st->print_cr("Error: Cannot print dynamic libraries.");
  1550         return;
  1552     handle = dlopen(dli.dli_fname, RTLD_LAZY);
  1553     if (handle == NULL) {
  1554         st->print_cr("Error: Cannot print dynamic libraries.");
  1555         return;
  1557     dlinfo(handle, RTLD_DI_LINKMAP, &map);
  1558     if (map == NULL) {
  1559         st->print_cr("Error: Cannot print dynamic libraries.");
  1560         return;
  1563     while (map->l_prev != NULL)
  1564         map = map->l_prev;
  1566     while (map != NULL) {
  1567         st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
  1568         map = map->l_next;
  1571     dlclose(handle);
  1572 #elif defined(__APPLE__)
  1573     uint32_t count;
  1574     uint32_t i;
  1576     count = _dyld_image_count();
  1577     for (i = 1; i < count; i++) {
  1578         const char *name = _dyld_get_image_name(i);
  1579         intptr_t slide = _dyld_get_image_vmaddr_slide(i);
  1580         st->print_cr(PTR_FORMAT " \t%s", slide, name);
  1582 #else
  1583    st->print_cr("Error: Cannot print dynamic libraries.");
  1584 #endif
  1587 void os::print_os_info_brief(outputStream* st) {
  1588   st->print("Bsd");
  1590   os::Posix::print_uname_info(st);
  1593 void os::print_os_info(outputStream* st) {
  1594   st->print("OS:");
  1595   st->print("Bsd");
  1597   os::Posix::print_uname_info(st);
  1599   os::Posix::print_rlimit_info(st);
  1601   os::Posix::print_load_average(st);
  1604 void os::pd_print_cpu_info(outputStream* st) {
  1605   // Nothing to do for now.
  1608 void os::print_memory_info(outputStream* st) {
  1610   st->print("Memory:");
  1611   st->print(" %dk page", os::vm_page_size()>>10);
  1613   st->print(", physical " UINT64_FORMAT "k",
  1614             os::physical_memory() >> 10);
  1615   st->print("(" UINT64_FORMAT "k free)",
  1616             os::available_memory() >> 10);
  1617   st->cr();
  1619   // meminfo
  1620   st->print("\n/proc/meminfo:\n");
  1621   _print_ascii_file("/proc/meminfo", st);
  1622   st->cr();
  1625 // Taken from /usr/include/bits/siginfo.h  Supposed to be architecture specific
  1626 // but they're the same for all the bsd arch that we support
  1627 // and they're the same for solaris but there's no common place to put this.
  1628 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
  1629                           "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
  1630                           "ILL_COPROC", "ILL_BADSTK" };
  1632 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
  1633                           "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
  1634                           "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
  1636 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
  1638 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
  1640 void os::print_siginfo(outputStream* st, void* siginfo) {
  1641   st->print("siginfo:");
  1643   const int buflen = 100;
  1644   char buf[buflen];
  1645   siginfo_t *si = (siginfo_t*)siginfo;
  1646   st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
  1647   if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
  1648     st->print("si_errno=%s", buf);
  1649   } else {
  1650     st->print("si_errno=%d", si->si_errno);
  1652   const int c = si->si_code;
  1653   assert(c > 0, "unexpected si_code");
  1654   switch (si->si_signo) {
  1655   case SIGILL:
  1656     st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
  1657     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1658     break;
  1659   case SIGFPE:
  1660     st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
  1661     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1662     break;
  1663   case SIGSEGV:
  1664     st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
  1665     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1666     break;
  1667   case SIGBUS:
  1668     st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
  1669     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
  1670     break;
  1671   default:
  1672     st->print(", si_code=%d", si->si_code);
  1673     // no si_addr
  1676   if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
  1677       UseSharedSpaces) {
  1678     FileMapInfo* mapinfo = FileMapInfo::current_info();
  1679     if (mapinfo->is_in_shared_space(si->si_addr)) {
  1680       st->print("\n\nError accessing class data sharing archive."   \
  1681                 " Mapped file inaccessible during execution, "      \
  1682                 " possible disk/network problem.");
  1685   st->cr();
  1689 static void print_signal_handler(outputStream* st, int sig,
  1690                                  char* buf, size_t buflen);
  1692 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  1693   st->print_cr("Signal Handlers:");
  1694   print_signal_handler(st, SIGSEGV, buf, buflen);
  1695   print_signal_handler(st, SIGBUS , buf, buflen);
  1696   print_signal_handler(st, SIGFPE , buf, buflen);
  1697   print_signal_handler(st, SIGPIPE, buf, buflen);
  1698   print_signal_handler(st, SIGXFSZ, buf, buflen);
  1699   print_signal_handler(st, SIGILL , buf, buflen);
  1700   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
  1701   print_signal_handler(st, SR_signum, buf, buflen);
  1702   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
  1703   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
  1704   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
  1705   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
  1708 static char saved_jvm_path[MAXPATHLEN] = {0};
  1710 // Find the full path to the current module, libjvm
  1711 void os::jvm_path(char *buf, jint buflen) {
  1712   // Error checking.
  1713   if (buflen < MAXPATHLEN) {
  1714     assert(false, "must use a large-enough buffer");
  1715     buf[0] = '\0';
  1716     return;
  1718   // Lazy resolve the path to current module.
  1719   if (saved_jvm_path[0] != 0) {
  1720     strcpy(buf, saved_jvm_path);
  1721     return;
  1724   char dli_fname[MAXPATHLEN];
  1725   bool ret = dll_address_to_library_name(
  1726                 CAST_FROM_FN_PTR(address, os::jvm_path),
  1727                 dli_fname, sizeof(dli_fname), NULL);
  1728   assert(ret != 0, "cannot locate libjvm");
  1729   char *rp = realpath(dli_fname, buf);
  1730   if (rp == NULL)
  1731     return;
  1733   if (Arguments::created_by_gamma_launcher()) {
  1734     // Support for the gamma launcher.  Typical value for buf is
  1735     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm".  If "/jre/lib/" appears at
  1736     // the right place in the string, then assume we are installed in a JDK and
  1737     // we're done.  Otherwise, check for a JAVA_HOME environment variable and
  1738     // construct a path to the JVM being overridden.
  1740     const char *p = buf + strlen(buf) - 1;
  1741     for (int count = 0; p > buf && count < 5; ++count) {
  1742       for (--p; p > buf && *p != '/'; --p)
  1743         /* empty */ ;
  1746     if (strncmp(p, "/jre/lib/", 9) != 0) {
  1747       // Look for JAVA_HOME in the environment.
  1748       char* java_home_var = ::getenv("JAVA_HOME");
  1749       if (java_home_var != NULL && java_home_var[0] != 0) {
  1750         char* jrelib_p;
  1751         int len;
  1753         // Check the current module name "libjvm"
  1754         p = strrchr(buf, '/');
  1755         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1757         rp = realpath(java_home_var, buf);
  1758         if (rp == NULL)
  1759           return;
  1761         // determine if this is a legacy image or modules image
  1762         // modules image doesn't have "jre" subdirectory
  1763         len = strlen(buf);
  1764         jrelib_p = buf + len;
  1766         // Add the appropriate library subdir
  1767         snprintf(jrelib_p, buflen-len, "/jre/lib");
  1768         if (0 != access(buf, F_OK)) {
  1769           snprintf(jrelib_p, buflen-len, "/lib");
  1772         // Add the appropriate client or server subdir
  1773         len = strlen(buf);
  1774         jrelib_p = buf + len;
  1775         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
  1776         if (0 != access(buf, F_OK)) {
  1777           snprintf(jrelib_p, buflen-len, "");
  1780         // If the path exists within JAVA_HOME, add the JVM library name
  1781         // to complete the path to JVM being overridden.  Otherwise fallback
  1782         // to the path to the current library.
  1783         if (0 == access(buf, F_OK)) {
  1784           // Use current module name "libjvm"
  1785           len = strlen(buf);
  1786           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1787         } else {
  1788           // Fall back to path of current library
  1789           rp = realpath(dli_fname, buf);
  1790           if (rp == NULL)
  1791             return;
  1797   strcpy(saved_jvm_path, buf);
  1800 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  1801   // no prefix required, not even "_"
  1804 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  1805   // no suffix required
  1808 ////////////////////////////////////////////////////////////////////////////////
  1809 // sun.misc.Signal support
  1811 static volatile jint sigint_count = 0;
  1813 static void
  1814 UserHandler(int sig, void *siginfo, void *context) {
  1815   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1816   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1817   // don't want to flood the manager thread with sem_post requests.
  1818   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1819       return;
  1821   // Ctrl-C is pressed during error reporting, likely because the error
  1822   // handler fails to abort. Let VM die immediately.
  1823   if (sig == SIGINT && is_error_reported()) {
  1824      os::die();
  1827   os::signal_notify(sig);
  1830 void* os::user_handler() {
  1831   return CAST_FROM_FN_PTR(void*, UserHandler);
  1834 extern "C" {
  1835   typedef void (*sa_handler_t)(int);
  1836   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  1839 void* os::signal(int signal_number, void* handler) {
  1840   struct sigaction sigAct, oldSigAct;
  1842   sigfillset(&(sigAct.sa_mask));
  1843   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
  1844   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
  1846   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
  1847     // -1 means registration failed
  1848     return (void *)-1;
  1851   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
  1854 void os::signal_raise(int signal_number) {
  1855   ::raise(signal_number);
  1858 /*
  1859  * The following code is moved from os.cpp for making this
  1860  * code platform specific, which it is by its very nature.
  1861  */
  1863 // Will be modified when max signal is changed to be dynamic
  1864 int os::sigexitnum_pd() {
  1865   return NSIG;
  1868 // a counter for each possible signal value
  1869 static volatile jint pending_signals[NSIG+1] = { 0 };
  1871 // Bsd(POSIX) specific hand shaking semaphore.
  1872 #ifdef __APPLE__
  1873 static semaphore_t sig_sem;
  1874 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1875 #define SEM_WAIT(sem)           semaphore_wait(sem);
  1876 #define SEM_POST(sem)           semaphore_signal(sem);
  1877 #else
  1878 static sem_t sig_sem;
  1879 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1880 #define SEM_WAIT(sem)           sem_wait(&sem);
  1881 #define SEM_POST(sem)           sem_post(&sem);
  1882 #endif
  1884 void os::signal_init_pd() {
  1885   // Initialize signal structures
  1886   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
  1888   // Initialize signal semaphore
  1889   ::SEM_INIT(sig_sem, 0);
  1892 void os::signal_notify(int sig) {
  1893   Atomic::inc(&pending_signals[sig]);
  1894   ::SEM_POST(sig_sem);
  1897 static int check_pending_signals(bool wait) {
  1898   Atomic::store(0, &sigint_count);
  1899   for (;;) {
  1900     for (int i = 0; i < NSIG + 1; i++) {
  1901       jint n = pending_signals[i];
  1902       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  1903         return i;
  1906     if (!wait) {
  1907       return -1;
  1909     JavaThread *thread = JavaThread::current();
  1910     ThreadBlockInVM tbivm(thread);
  1912     bool threadIsSuspended;
  1913     do {
  1914       thread->set_suspend_equivalent();
  1915       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  1916       ::SEM_WAIT(sig_sem);
  1918       // were we externally suspended while we were waiting?
  1919       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  1920       if (threadIsSuspended) {
  1921         //
  1922         // The semaphore has been incremented, but while we were waiting
  1923         // another thread suspended us. We don't want to continue running
  1924         // while suspended because that would surprise the thread that
  1925         // suspended us.
  1926         //
  1927         ::SEM_POST(sig_sem);
  1929         thread->java_suspend_self();
  1931     } while (threadIsSuspended);
  1935 int os::signal_lookup() {
  1936   return check_pending_signals(false);
  1939 int os::signal_wait() {
  1940   return check_pending_signals(true);
  1943 ////////////////////////////////////////////////////////////////////////////////
  1944 // Virtual Memory
  1946 int os::vm_page_size() {
  1947   // Seems redundant as all get out
  1948   assert(os::Bsd::page_size() != -1, "must call os::init");
  1949   return os::Bsd::page_size();
  1952 // Solaris allocates memory by pages.
  1953 int os::vm_allocation_granularity() {
  1954   assert(os::Bsd::page_size() != -1, "must call os::init");
  1955   return os::Bsd::page_size();
  1958 // Rationale behind this function:
  1959 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
  1960 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
  1961 //  samples for JITted code. Here we create private executable mapping over the code cache
  1962 //  and then we can use standard (well, almost, as mapping can change) way to provide
  1963 //  info for the reporting script by storing timestamp and location of symbol
  1964 void bsd_wrap_code(char* base, size_t size) {
  1965   static volatile jint cnt = 0;
  1967   if (!UseOprofile) {
  1968     return;
  1971   char buf[PATH_MAX + 1];
  1972   int num = Atomic::add(1, &cnt);
  1974   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
  1975            os::get_temp_directory(), os::current_process_id(), num);
  1976   unlink(buf);
  1978   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
  1980   if (fd != -1) {
  1981     off_t rv = ::lseek(fd, size-2, SEEK_SET);
  1982     if (rv != (off_t)-1) {
  1983       if (::write(fd, "", 1) == 1) {
  1984         mmap(base, size,
  1985              PROT_READ|PROT_WRITE|PROT_EXEC,
  1986              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
  1989     ::close(fd);
  1990     unlink(buf);
  1994 // NOTE: Bsd kernel does not really reserve the pages for us.
  1995 //       All it does is to check if there are enough free pages
  1996 //       left at the time of mmap(). This could be a potential
  1997 //       problem.
  1998 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
  1999   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
  2000 #ifdef __OpenBSD__
  2001   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2002   return ::mprotect(addr, size, prot) == 0;
  2003 #else
  2004   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2005                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2006   return res != (uintptr_t) MAP_FAILED;
  2007 #endif
  2011 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2012                        bool exec) {
  2013   return commit_memory(addr, size, exec);
  2016 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2019 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2020   ::madvise(addr, bytes, MADV_DONTNEED);
  2023 void os::numa_make_global(char *addr, size_t bytes) {
  2026 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
  2029 bool os::numa_topology_changed()   { return false; }
  2031 size_t os::numa_get_groups_num() {
  2032   return 1;
  2035 int os::numa_get_group_id() {
  2036   return 0;
  2039 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2040   if (size > 0) {
  2041     ids[0] = 0;
  2042     return 1;
  2044   return 0;
  2047 bool os::get_page_info(char *start, page_info* info) {
  2048   return false;
  2051 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2052   return end;
  2056 bool os::pd_uncommit_memory(char* addr, size_t size) {
  2057 #ifdef __OpenBSD__
  2058   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2059   return ::mprotect(addr, size, PROT_NONE) == 0;
  2060 #else
  2061   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2062                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2063   return res  != (uintptr_t) MAP_FAILED;
  2064 #endif
  2067 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2068   return os::commit_memory(addr, size);
  2071 // If this is a growable mapping, remove the guard pages entirely by
  2072 // munmap()ping them.  If not, just call uncommit_memory().
  2073 bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2074   return os::uncommit_memory(addr, size);
  2077 static address _highest_vm_reserved_address = NULL;
  2079 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
  2080 // at 'requested_addr'. If there are existing memory mappings at the same
  2081 // location, however, they will be overwritten. If 'fixed' is false,
  2082 // 'requested_addr' is only treated as a hint, the return value may or
  2083 // may not start from the requested address. Unlike Bsd mmap(), this
  2084 // function returns NULL to indicate failure.
  2085 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
  2086   char * addr;
  2087   int flags;
  2089   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
  2090   if (fixed) {
  2091     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
  2092     flags |= MAP_FIXED;
  2095   // Map uncommitted pages PROT_READ and PROT_WRITE, change access
  2096   // to PROT_EXEC if executable when we commit the page.
  2097   addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
  2098                        flags, -1, 0);
  2100   if (addr != MAP_FAILED) {
  2101     // anon_mmap() should only get called during VM initialization,
  2102     // don't need lock (actually we can skip locking even it can be called
  2103     // from multiple threads, because _highest_vm_reserved_address is just a
  2104     // hint about the upper limit of non-stack memory regions.)
  2105     if ((address)addr + bytes > _highest_vm_reserved_address) {
  2106       _highest_vm_reserved_address = (address)addr + bytes;
  2110   return addr == MAP_FAILED ? NULL : addr;
  2113 // Don't update _highest_vm_reserved_address, because there might be memory
  2114 // regions above addr + size. If so, releasing a memory region only creates
  2115 // a hole in the address space, it doesn't help prevent heap-stack collision.
  2116 //
  2117 static int anon_munmap(char * addr, size_t size) {
  2118   return ::munmap(addr, size) == 0;
  2121 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2122                          size_t alignment_hint) {
  2123   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2126 bool os::pd_release_memory(char* addr, size_t size) {
  2127   return anon_munmap(addr, size);
  2130 static address highest_vm_reserved_address() {
  2131   return _highest_vm_reserved_address;
  2134 static bool bsd_mprotect(char* addr, size_t size, int prot) {
  2135   // Bsd wants the mprotect address argument to be page aligned.
  2136   char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
  2138   // According to SUSv3, mprotect() should only be used with mappings
  2139   // established by mmap(), and mmap() always maps whole pages. Unaligned
  2140   // 'addr' likely indicates problem in the VM (e.g. trying to change
  2141   // protection of malloc'ed or statically allocated memory). Check the
  2142   // caller if you hit this assert.
  2143   assert(addr == bottom, "sanity check");
  2145   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
  2146   return ::mprotect(bottom, size, prot) == 0;
  2149 // Set protections specified
  2150 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  2151                         bool is_committed) {
  2152   unsigned int p = 0;
  2153   switch (prot) {
  2154   case MEM_PROT_NONE: p = PROT_NONE; break;
  2155   case MEM_PROT_READ: p = PROT_READ; break;
  2156   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
  2157   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
  2158   default:
  2159     ShouldNotReachHere();
  2161   // is_committed is unused.
  2162   return bsd_mprotect(addr, bytes, p);
  2165 bool os::guard_memory(char* addr, size_t size) {
  2166   return bsd_mprotect(addr, size, PROT_NONE);
  2169 bool os::unguard_memory(char* addr, size_t size) {
  2170   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
  2173 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
  2174   return false;
  2177 /*
  2178 * Set the coredump_filter bits to include largepages in core dump (bit 6)
  2180 * From the coredump_filter documentation:
  2182 * - (bit 0) anonymous private memory
  2183 * - (bit 1) anonymous shared memory
  2184 * - (bit 2) file-backed private memory
  2185 * - (bit 3) file-backed shared memory
  2186 * - (bit 4) ELF header pages in file-backed private memory areas (it is
  2187 *           effective only if the bit 2 is cleared)
  2188 * - (bit 5) hugetlb private memory
  2189 * - (bit 6) hugetlb shared memory
  2190 */
  2191 static void set_coredump_filter(void) {
  2192   FILE *f;
  2193   long cdm;
  2195   if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
  2196     return;
  2199   if (fscanf(f, "%lx", &cdm) != 1) {
  2200     fclose(f);
  2201     return;
  2204   rewind(f);
  2206   if ((cdm & LARGEPAGES_BIT) == 0) {
  2207     cdm |= LARGEPAGES_BIT;
  2208     fprintf(f, "%#lx", cdm);
  2211   fclose(f);
  2214 // Large page support
  2216 static size_t _large_page_size = 0;
  2218 void os::large_page_init() {
  2222 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
  2223   // "exec" is passed in but not used.  Creating the shared image for
  2224   // the code cache doesn't have an SHM_X executable permission to check.
  2225   assert(UseLargePages && UseSHM, "only for SHM large pages");
  2227   key_t key = IPC_PRIVATE;
  2228   char *addr;
  2230   bool warn_on_failure = UseLargePages &&
  2231                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2232                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2233                         );
  2234   char msg[128];
  2236   // Create a large shared memory region to attach to based on size.
  2237   // Currently, size is the total size of the heap
  2238   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2239   if (shmid == -1) {
  2240      // Possible reasons for shmget failure:
  2241      // 1. shmmax is too small for Java heap.
  2242      //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2243      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2244      // 2. not enough large page memory.
  2245      //    > check available large pages: cat /proc/meminfo
  2246      //    > increase amount of large pages:
  2247      //          echo new_value > /proc/sys/vm/nr_hugepages
  2248      //      Note 1: different Bsd may use different name for this property,
  2249      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2250      //      Note 2: it's possible there's enough physical memory available but
  2251      //            they are so fragmented after a long run that they can't
  2252      //            coalesce into large pages. Try to reserve large pages when
  2253      //            the system is still "fresh".
  2254      if (warn_on_failure) {
  2255        jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
  2256        warning(msg);
  2258      return NULL;
  2261   // attach to the region
  2262   addr = (char*)shmat(shmid, req_addr, 0);
  2263   int err = errno;
  2265   // Remove shmid. If shmat() is successful, the actual shared memory segment
  2266   // will be deleted when it's detached by shmdt() or when the process
  2267   // terminates. If shmat() is not successful this will remove the shared
  2268   // segment immediately.
  2269   shmctl(shmid, IPC_RMID, NULL);
  2271   if ((intptr_t)addr == -1) {
  2272      if (warn_on_failure) {
  2273        jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
  2274        warning(msg);
  2276      return NULL;
  2279   // The memory is committed
  2280   address pc = CALLER_PC;
  2281   MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
  2282   MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
  2284   return addr;
  2287 bool os::release_memory_special(char* base, size_t bytes) {
  2288   // detaching the SHM segment will also delete it, see reserve_memory_special()
  2289   int rslt = shmdt(base);
  2290   if (rslt == 0) {
  2291     MemTracker::record_virtual_memory_uncommit((address)base, bytes);
  2292     MemTracker::record_virtual_memory_release((address)base, bytes);
  2293     return true;
  2294   } else {
  2295     return false;
  2300 size_t os::large_page_size() {
  2301   return _large_page_size;
  2304 // HugeTLBFS allows application to commit large page memory on demand;
  2305 // with SysV SHM the entire memory region must be allocated as shared
  2306 // memory.
  2307 bool os::can_commit_large_page_memory() {
  2308   return UseHugeTLBFS;
  2311 bool os::can_execute_large_page_memory() {
  2312   return UseHugeTLBFS;
  2315 // Reserve memory at an arbitrary address, only if that area is
  2316 // available (and not reserved for something else).
  2318 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2319   const int max_tries = 10;
  2320   char* base[max_tries];
  2321   size_t size[max_tries];
  2322   const size_t gap = 0x000000;
  2324   // Assert only that the size is a multiple of the page size, since
  2325   // that's all that mmap requires, and since that's all we really know
  2326   // about at this low abstraction level.  If we need higher alignment,
  2327   // we can either pass an alignment to this method or verify alignment
  2328   // in one of the methods further up the call chain.  See bug 5044738.
  2329   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
  2331   // Repeatedly allocate blocks until the block is allocated at the
  2332   // right spot. Give up after max_tries. Note that reserve_memory() will
  2333   // automatically update _highest_vm_reserved_address if the call is
  2334   // successful. The variable tracks the highest memory address every reserved
  2335   // by JVM. It is used to detect heap-stack collision if running with
  2336   // fixed-stack BsdThreads. Because here we may attempt to reserve more
  2337   // space than needed, it could confuse the collision detecting code. To
  2338   // solve the problem, save current _highest_vm_reserved_address and
  2339   // calculate the correct value before return.
  2340   address old_highest = _highest_vm_reserved_address;
  2342   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2343   // if kernel honors the hint then we can return immediately.
  2344   char * addr = anon_mmap(requested_addr, bytes, false);
  2345   if (addr == requested_addr) {
  2346      return requested_addr;
  2349   if (addr != NULL) {
  2350      // mmap() is successful but it fails to reserve at the requested address
  2351      anon_munmap(addr, bytes);
  2354   int i;
  2355   for (i = 0; i < max_tries; ++i) {
  2356     base[i] = reserve_memory(bytes);
  2358     if (base[i] != NULL) {
  2359       // Is this the block we wanted?
  2360       if (base[i] == requested_addr) {
  2361         size[i] = bytes;
  2362         break;
  2365       // Does this overlap the block we wanted? Give back the overlapped
  2366       // parts and try again.
  2368       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
  2369       if (top_overlap >= 0 && top_overlap < bytes) {
  2370         unmap_memory(base[i], top_overlap);
  2371         base[i] += top_overlap;
  2372         size[i] = bytes - top_overlap;
  2373       } else {
  2374         size_t bottom_overlap = base[i] + bytes - requested_addr;
  2375         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
  2376           unmap_memory(requested_addr, bottom_overlap);
  2377           size[i] = bytes - bottom_overlap;
  2378         } else {
  2379           size[i] = bytes;
  2385   // Give back the unused reserved pieces.
  2387   for (int j = 0; j < i; ++j) {
  2388     if (base[j] != NULL) {
  2389       unmap_memory(base[j], size[j]);
  2393   if (i < max_tries) {
  2394     _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
  2395     return requested_addr;
  2396   } else {
  2397     _highest_vm_reserved_address = old_highest;
  2398     return NULL;
  2402 size_t os::read(int fd, void *buf, unsigned int nBytes) {
  2403   RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
  2406 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
  2407 // Solaris uses poll(), bsd uses park().
  2408 // Poll() is likely a better choice, assuming that Thread.interrupt()
  2409 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
  2410 // SIGSEGV, see 4355769.
  2412 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  2413   assert(thread == Thread::current(),  "thread consistency check");
  2415   ParkEvent * const slp = thread->_SleepEvent ;
  2416   slp->reset() ;
  2417   OrderAccess::fence() ;
  2419   if (interruptible) {
  2420     jlong prevtime = javaTimeNanos();
  2422     for (;;) {
  2423       if (os::is_interrupted(thread, true)) {
  2424         return OS_INTRPT;
  2427       jlong newtime = javaTimeNanos();
  2429       if (newtime - prevtime < 0) {
  2430         // time moving backwards, should only happen if no monotonic clock
  2431         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2432         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2433       } else {
  2434         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2437       if(millis <= 0) {
  2438         return OS_OK;
  2441       prevtime = newtime;
  2444         assert(thread->is_Java_thread(), "sanity check");
  2445         JavaThread *jt = (JavaThread *) thread;
  2446         ThreadBlockInVM tbivm(jt);
  2447         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
  2449         jt->set_suspend_equivalent();
  2450         // cleared by handle_special_suspend_equivalent_condition() or
  2451         // java_suspend_self() via check_and_wait_while_suspended()
  2453         slp->park(millis);
  2455         // were we externally suspended while we were waiting?
  2456         jt->check_and_wait_while_suspended();
  2459   } else {
  2460     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  2461     jlong prevtime = javaTimeNanos();
  2463     for (;;) {
  2464       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
  2465       // the 1st iteration ...
  2466       jlong newtime = javaTimeNanos();
  2468       if (newtime - prevtime < 0) {
  2469         // time moving backwards, should only happen if no monotonic clock
  2470         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2471         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2472       } else {
  2473         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2476       if(millis <= 0) break ;
  2478       prevtime = newtime;
  2479       slp->park(millis);
  2481     return OS_OK ;
  2485 int os::naked_sleep() {
  2486   // %% make the sleep time an integer flag. for now use 1 millisec.
  2487   return os::sleep(Thread::current(), 1, false);
  2490 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  2491 void os::infinite_sleep() {
  2492   while (true) {    // sleep forever ...
  2493     ::sleep(100);   // ... 100 seconds at a time
  2497 // Used to convert frequent JVM_Yield() to nops
  2498 bool os::dont_yield() {
  2499   return DontYieldALot;
  2502 void os::yield() {
  2503   sched_yield();
  2506 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
  2508 void os::yield_all(int attempts) {
  2509   // Yields to all threads, including threads with lower priorities
  2510   // Threads on Bsd are all with same priority. The Solaris style
  2511   // os::yield_all() with nanosleep(1ms) is not necessary.
  2512   sched_yield();
  2515 // Called from the tight loops to possibly influence time-sharing heuristics
  2516 void os::loop_breaker(int attempts) {
  2517   os::yield_all(attempts);
  2520 ////////////////////////////////////////////////////////////////////////////////
  2521 // thread priority support
  2523 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
  2524 // only supports dynamic priority, static priority must be zero. For real-time
  2525 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
  2526 // However, for large multi-threaded applications, SCHED_RR is not only slower
  2527 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
  2528 // of 5 runs - Sep 2005).
  2529 //
  2530 // The following code actually changes the niceness of kernel-thread/LWP. It
  2531 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
  2532 // not the entire user process, and user level threads are 1:1 mapped to kernel
  2533 // threads. It has always been the case, but could change in the future. For
  2534 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
  2535 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
  2537 #if !defined(__APPLE__)
  2538 int os::java_to_os_priority[CriticalPriority + 1] = {
  2539   19,              // 0 Entry should never be used
  2541    0,              // 1 MinPriority
  2542    3,              // 2
  2543    6,              // 3
  2545   10,              // 4
  2546   15,              // 5 NormPriority
  2547   18,              // 6
  2549   21,              // 7
  2550   25,              // 8
  2551   28,              // 9 NearMaxPriority
  2553   31,              // 10 MaxPriority
  2555   31               // 11 CriticalPriority
  2556 };
  2557 #else
  2558 /* Using Mach high-level priority assignments */
  2559 int os::java_to_os_priority[CriticalPriority + 1] = {
  2560    0,              // 0 Entry should never be used (MINPRI_USER)
  2562   27,              // 1 MinPriority
  2563   28,              // 2
  2564   29,              // 3
  2566   30,              // 4
  2567   31,              // 5 NormPriority (BASEPRI_DEFAULT)
  2568   32,              // 6
  2570   33,              // 7
  2571   34,              // 8
  2572   35,              // 9 NearMaxPriority
  2574   36,              // 10 MaxPriority
  2576   36               // 11 CriticalPriority
  2577 };
  2578 #endif
  2580 static int prio_init() {
  2581   if (ThreadPriorityPolicy == 1) {
  2582     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
  2583     // if effective uid is not root. Perhaps, a more elegant way of doing
  2584     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
  2585     if (geteuid() != 0) {
  2586       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
  2587         warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
  2589       ThreadPriorityPolicy = 0;
  2592   if (UseCriticalJavaThreadPriority) {
  2593     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
  2595   return 0;
  2598 OSReturn os::set_native_priority(Thread* thread, int newpri) {
  2599   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
  2601 #ifdef __OpenBSD__
  2602   // OpenBSD pthread_setprio starves low priority threads
  2603   return OS_OK;
  2604 #elif defined(__FreeBSD__)
  2605   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
  2606 #elif defined(__APPLE__) || defined(__NetBSD__)
  2607   struct sched_param sp;
  2608   int policy;
  2609   pthread_t self = pthread_self();
  2611   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2612     return OS_ERR;
  2614   sp.sched_priority = newpri;
  2615   if (pthread_setschedparam(self, policy, &sp) != 0)
  2616     return OS_ERR;
  2618   return OS_OK;
  2619 #else
  2620   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2621   return (ret == 0) ? OS_OK : OS_ERR;
  2622 #endif
  2625 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
  2626   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
  2627     *priority_ptr = java_to_os_priority[NormPriority];
  2628     return OS_OK;
  2631   errno = 0;
  2632 #if defined(__OpenBSD__) || defined(__FreeBSD__)
  2633   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
  2634 #elif defined(__APPLE__) || defined(__NetBSD__)
  2635   int policy;
  2636   struct sched_param sp;
  2638   pthread_getschedparam(pthread_self(), &policy, &sp);
  2639   *priority_ptr = sp.sched_priority;
  2640 #else
  2641   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
  2642 #endif
  2643   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
  2646 // Hint to the underlying OS that a task switch would not be good.
  2647 // Void return because it's a hint and can fail.
  2648 void os::hint_no_preempt() {}
  2650 ////////////////////////////////////////////////////////////////////////////////
  2651 // suspend/resume support
  2653 //  the low-level signal-based suspend/resume support is a remnant from the
  2654 //  old VM-suspension that used to be for java-suspension, safepoints etc,
  2655 //  within hotspot. Now there is a single use-case for this:
  2656 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
  2657 //      that runs in the watcher thread.
  2658 //  The remaining code is greatly simplified from the more general suspension
  2659 //  code that used to be used.
  2660 //
  2661 //  The protocol is quite simple:
  2662 //  - suspend:
  2663 //      - sends a signal to the target thread
  2664 //      - polls the suspend state of the osthread using a yield loop
  2665 //      - target thread signal handler (SR_handler) sets suspend state
  2666 //        and blocks in sigsuspend until continued
  2667 //  - resume:
  2668 //      - sets target osthread state to continue
  2669 //      - sends signal to end the sigsuspend loop in the SR_handler
  2670 //
  2671 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2672 //
  2674 static void resume_clear_context(OSThread *osthread) {
  2675   osthread->set_ucontext(NULL);
  2676   osthread->set_siginfo(NULL);
  2678   // notify the suspend action is completed, we have now resumed
  2679   osthread->sr.clear_suspended();
  2682 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2683   osthread->set_ucontext(context);
  2684   osthread->set_siginfo(siginfo);
  2687 //
  2688 // Handler function invoked when a thread's execution is suspended or
  2689 // resumed. We have to be careful that only async-safe functions are
  2690 // called here (Note: most pthread functions are not async safe and
  2691 // should be avoided.)
  2692 //
  2693 // Note: sigwait() is a more natural fit than sigsuspend() from an
  2694 // interface point of view, but sigwait() prevents the signal hander
  2695 // from being run. libpthread would get very confused by not having
  2696 // its signal handlers run and prevents sigwait()'s use with the
  2697 // mutex granting granting signal.
  2698 //
  2699 // Currently only ever called on the VMThread
  2700 //
  2701 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
  2702   // Save and restore errno to avoid confusing native code with EINTR
  2703   // after sigsuspend.
  2704   int old_errno = errno;
  2706   Thread* thread = Thread::current();
  2707   OSThread* osthread = thread->osthread();
  2708   assert(thread->is_VM_thread(), "Must be VMThread");
  2709   // read current suspend action
  2710   int action = osthread->sr.suspend_action();
  2711   if (action == os::Bsd::SuspendResume::SR_SUSPEND) {
  2712     suspend_save_context(osthread, siginfo, context);
  2714     // Notify the suspend action is about to be completed. do_suspend()
  2715     // waits until SR_SUSPENDED is set and then returns. We will wait
  2716     // here for a resume signal and that completes the suspend-other
  2717     // action. do_suspend/do_resume is always called as a pair from
  2718     // the same thread - so there are no races
  2720     // notify the caller
  2721     osthread->sr.set_suspended();
  2723     sigset_t suspend_set;  // signals for sigsuspend()
  2725     // get current set of blocked signals and unblock resume signal
  2726     pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
  2727     sigdelset(&suspend_set, SR_signum);
  2729     // wait here until we are resumed
  2730     do {
  2731       sigsuspend(&suspend_set);
  2732       // ignore all returns until we get a resume signal
  2733     } while (osthread->sr.suspend_action() != os::Bsd::SuspendResume::SR_CONTINUE);
  2735     resume_clear_context(osthread);
  2737   } else {
  2738     assert(action == os::Bsd::SuspendResume::SR_CONTINUE, "unexpected sr action");
  2739     // nothing special to do - just leave the handler
  2742   errno = old_errno;
  2746 static int SR_initialize() {
  2747   struct sigaction act;
  2748   char *s;
  2749   /* Get signal number to use for suspend/resume */
  2750   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2751     int sig = ::strtol(s, 0, 10);
  2752     if (sig > 0 || sig < NSIG) {
  2753         SR_signum = sig;
  2757   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2758         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2760   sigemptyset(&SR_sigset);
  2761   sigaddset(&SR_sigset, SR_signum);
  2763   /* Set up signal handler for suspend/resume */
  2764   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2765   act.sa_handler = (void (*)(int)) SR_handler;
  2767   // SR_signum is blocked by default.
  2768   // 4528190 - We also need to block pthread restart signal (32 on all
  2769   // supported Bsd platforms). Note that BsdThreads need to block
  2770   // this signal for all threads to work properly. So we don't have
  2771   // to use hard-coded signal number when setting up the mask.
  2772   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
  2774   if (sigaction(SR_signum, &act, 0) == -1) {
  2775     return -1;
  2778   // Save signal flag
  2779   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
  2780   return 0;
  2783 static int SR_finalize() {
  2784   return 0;
  2788 // returns true on success and false on error - really an error is fatal
  2789 // but this seems the normal response to library errors
  2790 static bool do_suspend(OSThread* osthread) {
  2791   // mark as suspended and send signal
  2792   osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_SUSPEND);
  2793   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2794   assert_status(status == 0, status, "pthread_kill");
  2796   // check status and wait until notified of suspension
  2797   if (status == 0) {
  2798     for (int i = 0; !osthread->sr.is_suspended(); i++) {
  2799       os::yield_all(i);
  2801     osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
  2802     return true;
  2804   else {
  2805     osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
  2806     return false;
  2810 static void do_resume(OSThread* osthread) {
  2811   assert(osthread->sr.is_suspended(), "thread should be suspended");
  2812   osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_CONTINUE);
  2814   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2815   assert_status(status == 0, status, "pthread_kill");
  2816   // check status and wait unit notified of resumption
  2817   if (status == 0) {
  2818     for (int i = 0; osthread->sr.is_suspended(); i++) {
  2819       os::yield_all(i);
  2822   osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
  2825 ////////////////////////////////////////////////////////////////////////////////
  2826 // interrupt support
  2828 void os::interrupt(Thread* thread) {
  2829   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2830     "possibility of dangling Thread pointer");
  2832   OSThread* osthread = thread->osthread();
  2834   if (!osthread->interrupted()) {
  2835     osthread->set_interrupted(true);
  2836     // More than one thread can get here with the same value of osthread,
  2837     // resulting in multiple notifications.  We do, however, want the store
  2838     // to interrupted() to be visible to other threads before we execute unpark().
  2839     OrderAccess::fence();
  2840     ParkEvent * const slp = thread->_SleepEvent ;
  2841     if (slp != NULL) slp->unpark() ;
  2844   // For JSR166. Unpark even if interrupt status already was set
  2845   if (thread->is_Java_thread())
  2846     ((JavaThread*)thread)->parker()->unpark();
  2848   ParkEvent * ev = thread->_ParkEvent ;
  2849   if (ev != NULL) ev->unpark() ;
  2853 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  2854   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  2855     "possibility of dangling Thread pointer");
  2857   OSThread* osthread = thread->osthread();
  2859   bool interrupted = osthread->interrupted();
  2861   if (interrupted && clear_interrupted) {
  2862     osthread->set_interrupted(false);
  2863     // consider thread->_SleepEvent->reset() ... optional optimization
  2866   return interrupted;
  2869 ///////////////////////////////////////////////////////////////////////////////////
  2870 // signal handling (except suspend/resume)
  2872 // This routine may be used by user applications as a "hook" to catch signals.
  2873 // The user-defined signal handler must pass unrecognized signals to this
  2874 // routine, and if it returns true (non-zero), then the signal handler must
  2875 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
  2876 // routine will never retun false (zero), but instead will execute a VM panic
  2877 // routine kill the process.
  2878 //
  2879 // If this routine returns false, it is OK to call it again.  This allows
  2880 // the user-defined signal handler to perform checks either before or after
  2881 // the VM performs its own checks.  Naturally, the user code would be making
  2882 // a serious error if it tried to handle an exception (such as a null check
  2883 // or breakpoint) that the VM was generating for its own correct operation.
  2884 //
  2885 // This routine may recognize any of the following kinds of signals:
  2886 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
  2887 // It should be consulted by handlers for any of those signals.
  2888 //
  2889 // The caller of this routine must pass in the three arguments supplied
  2890 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
  2891 // field of the structure passed to sigaction().  This routine assumes that
  2892 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2893 //
  2894 // Note that the VM will print warnings if it detects conflicting signal
  2895 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2896 //
  2897 extern "C" JNIEXPORT int
  2898 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2899                         void* ucontext, int abort_if_unrecognized);
  2901 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2902   assert(info != NULL && uc != NULL, "it must be old kernel");
  2903   int orig_errno = errno;  // Preserve errno value over signal handler.
  2904   JVM_handle_bsd_signal(sig, info, uc, true);
  2905   errno = orig_errno;
  2909 // This boolean allows users to forward their own non-matching signals
  2910 // to JVM_handle_bsd_signal, harmlessly.
  2911 bool os::Bsd::signal_handlers_are_installed = false;
  2913 // For signal-chaining
  2914 struct sigaction os::Bsd::sigact[MAXSIGNUM];
  2915 unsigned int os::Bsd::sigs = 0;
  2916 bool os::Bsd::libjsig_is_loaded = false;
  2917 typedef struct sigaction *(*get_signal_t)(int);
  2918 get_signal_t os::Bsd::get_signal_action = NULL;
  2920 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
  2921   struct sigaction *actp = NULL;
  2923   if (libjsig_is_loaded) {
  2924     // Retrieve the old signal handler from libjsig
  2925     actp = (*get_signal_action)(sig);
  2927   if (actp == NULL) {
  2928     // Retrieve the preinstalled signal handler from jvm
  2929     actp = get_preinstalled_handler(sig);
  2932   return actp;
  2935 static bool call_chained_handler(struct sigaction *actp, int sig,
  2936                                  siginfo_t *siginfo, void *context) {
  2937   // Call the old signal handler
  2938   if (actp->sa_handler == SIG_DFL) {
  2939     // It's more reasonable to let jvm treat it as an unexpected exception
  2940     // instead of taking the default action.
  2941     return false;
  2942   } else if (actp->sa_handler != SIG_IGN) {
  2943     if ((actp->sa_flags & SA_NODEFER) == 0) {
  2944       // automaticlly block the signal
  2945       sigaddset(&(actp->sa_mask), sig);
  2948     sa_handler_t hand;
  2949     sa_sigaction_t sa;
  2950     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
  2951     // retrieve the chained handler
  2952     if (siginfo_flag_set) {
  2953       sa = actp->sa_sigaction;
  2954     } else {
  2955       hand = actp->sa_handler;
  2958     if ((actp->sa_flags & SA_RESETHAND) != 0) {
  2959       actp->sa_handler = SIG_DFL;
  2962     // try to honor the signal mask
  2963     sigset_t oset;
  2964     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
  2966     // call into the chained handler
  2967     if (siginfo_flag_set) {
  2968       (*sa)(sig, siginfo, context);
  2969     } else {
  2970       (*hand)(sig);
  2973     // restore the signal mask
  2974     pthread_sigmask(SIG_SETMASK, &oset, 0);
  2976   // Tell jvm's signal handler the signal is taken care of.
  2977   return true;
  2980 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
  2981   bool chained = false;
  2982   // signal-chaining
  2983   if (UseSignalChaining) {
  2984     struct sigaction *actp = get_chained_signal_action(sig);
  2985     if (actp != NULL) {
  2986       chained = call_chained_handler(actp, sig, siginfo, context);
  2989   return chained;
  2992 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
  2993   if ((( (unsigned int)1 << sig ) & sigs) != 0) {
  2994     return &sigact[sig];
  2996   return NULL;
  2999 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
  3000   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3001   sigact[sig] = oldAct;
  3002   sigs |= (unsigned int)1 << sig;
  3005 // for diagnostic
  3006 int os::Bsd::sigflags[MAXSIGNUM];
  3008 int os::Bsd::get_our_sigflags(int sig) {
  3009   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3010   return sigflags[sig];
  3013 void os::Bsd::set_our_sigflags(int sig, int flags) {
  3014   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3015   sigflags[sig] = flags;
  3018 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
  3019   // Check for overwrite.
  3020   struct sigaction oldAct;
  3021   sigaction(sig, (struct sigaction*)NULL, &oldAct);
  3023   void* oldhand = oldAct.sa_sigaction
  3024                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
  3025                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
  3026   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
  3027       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
  3028       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
  3029     if (AllowUserSignalHandlers || !set_installed) {
  3030       // Do not overwrite; user takes responsibility to forward to us.
  3031       return;
  3032     } else if (UseSignalChaining) {
  3033       // save the old handler in jvm
  3034       save_preinstalled_handler(sig, oldAct);
  3035       // libjsig also interposes the sigaction() call below and saves the
  3036       // old sigaction on it own.
  3037     } else {
  3038       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
  3039                     "%#lx for signal %d.", (long)oldhand, sig));
  3043   struct sigaction sigAct;
  3044   sigfillset(&(sigAct.sa_mask));
  3045   sigAct.sa_handler = SIG_DFL;
  3046   if (!set_installed) {
  3047     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3048   } else {
  3049     sigAct.sa_sigaction = signalHandler;
  3050     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3052   // Save flags, which are set by ours
  3053   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3054   sigflags[sig] = sigAct.sa_flags;
  3056   int ret = sigaction(sig, &sigAct, &oldAct);
  3057   assert(ret == 0, "check");
  3059   void* oldhand2  = oldAct.sa_sigaction
  3060                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
  3061                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
  3062   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
  3065 // install signal handlers for signals that HotSpot needs to
  3066 // handle in order to support Java-level exception handling.
  3068 void os::Bsd::install_signal_handlers() {
  3069   if (!signal_handlers_are_installed) {
  3070     signal_handlers_are_installed = true;
  3072     // signal-chaining
  3073     typedef void (*signal_setting_t)();
  3074     signal_setting_t begin_signal_setting = NULL;
  3075     signal_setting_t end_signal_setting = NULL;
  3076     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3077                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3078     if (begin_signal_setting != NULL) {
  3079       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3080                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3081       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3082                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3083       libjsig_is_loaded = true;
  3084       assert(UseSignalChaining, "should enable signal-chaining");
  3086     if (libjsig_is_loaded) {
  3087       // Tell libjsig jvm is setting signal handlers
  3088       (*begin_signal_setting)();
  3091     set_signal_handler(SIGSEGV, true);
  3092     set_signal_handler(SIGPIPE, true);
  3093     set_signal_handler(SIGBUS, true);
  3094     set_signal_handler(SIGILL, true);
  3095     set_signal_handler(SIGFPE, true);
  3096     set_signal_handler(SIGXFSZ, true);
  3098 #if defined(__APPLE__)
  3099     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
  3100     // signals caught and handled by the JVM. To work around this, we reset the mach task
  3101     // signal handler that's placed on our process by CrashReporter. This disables
  3102     // CrashReporter-based reporting.
  3103     //
  3104     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
  3105     // on caught fatal signals.
  3106     //
  3107     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3108     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3109     // exception handling, while leaving the standard BSD signal handlers functional.
  3110     kern_return_t kr;
  3111     kr = task_set_exception_ports(mach_task_self(),
  3112         EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3113         MACH_PORT_NULL,
  3114         EXCEPTION_STATE_IDENTITY,
  3115         MACHINE_THREAD_STATE);
  3117     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3118 #endif
  3120     if (libjsig_is_loaded) {
  3121       // Tell libjsig jvm finishes setting signal handlers
  3122       (*end_signal_setting)();
  3125     // We don't activate signal checker if libjsig is in place, we trust ourselves
  3126     // and if UserSignalHandler is installed all bets are off
  3127     if (CheckJNICalls) {
  3128       if (libjsig_is_loaded) {
  3129         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
  3130         check_signals = false;
  3132       if (AllowUserSignalHandlers) {
  3133         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
  3134         check_signals = false;
  3141 /////
  3142 // glibc on Bsd platform uses non-documented flag
  3143 // to indicate, that some special sort of signal
  3144 // trampoline is used.
  3145 // We will never set this flag, and we should
  3146 // ignore this flag in our diagnostic
  3147 #ifdef SIGNIFICANT_SIGNAL_MASK
  3148 #undef SIGNIFICANT_SIGNAL_MASK
  3149 #endif
  3150 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3152 static const char* get_signal_handler_name(address handler,
  3153                                            char* buf, int buflen) {
  3154   int offset;
  3155   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
  3156   if (found) {
  3157     // skip directory names
  3158     const char *p1, *p2;
  3159     p1 = buf;
  3160     size_t len = strlen(os::file_separator());
  3161     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
  3162     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
  3163   } else {
  3164     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
  3166   return buf;
  3169 static void print_signal_handler(outputStream* st, int sig,
  3170                                  char* buf, size_t buflen) {
  3171   struct sigaction sa;
  3173   sigaction(sig, NULL, &sa);
  3175   // See comment for SIGNIFICANT_SIGNAL_MASK define
  3176   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3178   st->print("%s: ", os::exception_name(sig, buf, buflen));
  3180   address handler = (sa.sa_flags & SA_SIGINFO)
  3181     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
  3182     : CAST_FROM_FN_PTR(address, sa.sa_handler);
  3184   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
  3185     st->print("SIG_DFL");
  3186   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
  3187     st->print("SIG_IGN");
  3188   } else {
  3189     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
  3192   st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
  3194   address rh = VMError::get_resetted_sighandler(sig);
  3195   // May be, handler was resetted by VMError?
  3196   if(rh != NULL) {
  3197     handler = rh;
  3198     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
  3201   st->print(", sa_flags="   PTR32_FORMAT, sa.sa_flags);
  3203   // Check: is it our handler?
  3204   if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3205      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3206     // It is our signal handler
  3207     // check for flags, reset system-used one!
  3208     if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3209       st->print(
  3210                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3211                 os::Bsd::get_our_sigflags(sig));
  3214   st->cr();
  3218 #define DO_SIGNAL_CHECK(sig) \
  3219   if (!sigismember(&check_signal_done, sig)) \
  3220     os::Bsd::check_signal_handler(sig)
  3222 // This method is a periodic task to check for misbehaving JNI applications
  3223 // under CheckJNI, we can add any periodic checks here
  3225 void os::run_periodic_checks() {
  3227   if (check_signals == false) return;
  3229   // SEGV and BUS if overridden could potentially prevent
  3230   // generation of hs*.log in the event of a crash, debugging
  3231   // such a case can be very challenging, so we absolutely
  3232   // check the following for a good measure:
  3233   DO_SIGNAL_CHECK(SIGSEGV);
  3234   DO_SIGNAL_CHECK(SIGILL);
  3235   DO_SIGNAL_CHECK(SIGFPE);
  3236   DO_SIGNAL_CHECK(SIGBUS);
  3237   DO_SIGNAL_CHECK(SIGPIPE);
  3238   DO_SIGNAL_CHECK(SIGXFSZ);
  3241   // ReduceSignalUsage allows the user to override these handlers
  3242   // see comments at the very top and jvm_solaris.h
  3243   if (!ReduceSignalUsage) {
  3244     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
  3245     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
  3246     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
  3247     DO_SIGNAL_CHECK(BREAK_SIGNAL);
  3250   DO_SIGNAL_CHECK(SR_signum);
  3251   DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
  3254 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
  3256 static os_sigaction_t os_sigaction = NULL;
  3258 void os::Bsd::check_signal_handler(int sig) {
  3259   char buf[O_BUFLEN];
  3260   address jvmHandler = NULL;
  3263   struct sigaction act;
  3264   if (os_sigaction == NULL) {
  3265     // only trust the default sigaction, in case it has been interposed
  3266     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
  3267     if (os_sigaction == NULL) return;
  3270   os_sigaction(sig, (struct sigaction*)NULL, &act);
  3273   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3275   address thisHandler = (act.sa_flags & SA_SIGINFO)
  3276     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
  3277     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
  3280   switch(sig) {
  3281   case SIGSEGV:
  3282   case SIGBUS:
  3283   case SIGFPE:
  3284   case SIGPIPE:
  3285   case SIGILL:
  3286   case SIGXFSZ:
  3287     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
  3288     break;
  3290   case SHUTDOWN1_SIGNAL:
  3291   case SHUTDOWN2_SIGNAL:
  3292   case SHUTDOWN3_SIGNAL:
  3293   case BREAK_SIGNAL:
  3294     jvmHandler = (address)user_handler();
  3295     break;
  3297   case INTERRUPT_SIGNAL:
  3298     jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
  3299     break;
  3301   default:
  3302     if (sig == SR_signum) {
  3303       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
  3304     } else {
  3305       return;
  3307     break;
  3310   if (thisHandler != jvmHandler) {
  3311     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
  3312     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
  3313     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
  3314     // No need to check this sig any longer
  3315     sigaddset(&check_signal_done, sig);
  3316   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3317     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
  3318     tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
  3319     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
  3320     // No need to check this sig any longer
  3321     sigaddset(&check_signal_done, sig);
  3324   // Dump all the signal
  3325   if (sigismember(&check_signal_done, sig)) {
  3326     print_signal_handlers(tty, buf, O_BUFLEN);
  3330 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3332 extern bool signal_name(int signo, char* buf, size_t len);
  3334 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3335   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3336     // signal
  3337     if (!signal_name(exception_code, buf, size)) {
  3338       jio_snprintf(buf, size, "SIG%d", exception_code);
  3340     return buf;
  3341   } else {
  3342     return NULL;
  3346 // this is called _before_ the most of global arguments have been parsed
  3347 void os::init(void) {
  3348   char dummy;   /* used to get a guess on initial stack address */
  3349 //  first_hrtime = gethrtime();
  3351   // With BsdThreads the JavaMain thread pid (primordial thread)
  3352   // is different than the pid of the java launcher thread.
  3353   // So, on Bsd, the launcher thread pid is passed to the VM
  3354   // via the sun.java.launcher.pid property.
  3355   // Use this property instead of getpid() if it was correctly passed.
  3356   // See bug 6351349.
  3357   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
  3359   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
  3361   clock_tics_per_sec = CLK_TCK;
  3363   init_random(1234567);
  3365   ThreadCritical::initialize();
  3367   Bsd::set_page_size(getpagesize());
  3368   if (Bsd::page_size() == -1) {
  3369     fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
  3370                   strerror(errno)));
  3372   init_page_sizes((size_t) Bsd::page_size());
  3374   Bsd::initialize_system_info();
  3376   // main_thread points to the aboriginal thread
  3377   Bsd::_main_thread = pthread_self();
  3379   Bsd::clock_init();
  3380   initial_time_count = os::elapsed_counter();
  3382 #ifdef __APPLE__
  3383   // XXXDARWIN
  3384   // Work around the unaligned VM callbacks in hotspot's
  3385   // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
  3386   // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
  3387   // alignment when doing symbol lookup. To work around this, we force early
  3388   // binding of all symbols now, thus binding when alignment is known-good.
  3389   _dyld_bind_fully_image_containing_address((const void *) &os::init);
  3390 #endif
  3393 // To install functions for atexit system call
  3394 extern "C" {
  3395   static void perfMemory_exit_helper() {
  3396     perfMemory_exit();
  3400 // this is called _after_ the global arguments have been parsed
  3401 jint os::init_2(void)
  3403   // Allocate a single page and mark it as readable for safepoint polling
  3404   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3405   guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
  3407   os::set_polling_page( polling_page );
  3409 #ifndef PRODUCT
  3410   if(Verbose && PrintMiscellaneous)
  3411     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3412 #endif
  3414   if (!UseMembar) {
  3415     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3416     guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
  3417     os::set_memory_serialize_page( mem_serialize_page );
  3419 #ifndef PRODUCT
  3420     if(Verbose && PrintMiscellaneous)
  3421       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3422 #endif
  3425   os::large_page_init();
  3427   // initialize suspend/resume support - must do this before signal_sets_init()
  3428   if (SR_initialize() != 0) {
  3429     perror("SR_initialize failed");
  3430     return JNI_ERR;
  3433   Bsd::signal_sets_init();
  3434   Bsd::install_signal_handlers();
  3436   // Check minimum allowable stack size for thread creation and to initialize
  3437   // the java system classes, including StackOverflowError - depends on page
  3438   // size.  Add a page for compiler2 recursion in main thread.
  3439   // Add in 2*BytesPerWord times page size to account for VM stack during
  3440   // class initialization depending on 32 or 64 bit VM.
  3441   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3442             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3443                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3445   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3446   if (threadStackSizeInBytes != 0 &&
  3447       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3448         tty->print_cr("\nThe stack size specified is too small, "
  3449                       "Specify at least %dk",
  3450                       os::Bsd::min_stack_allowed/ K);
  3451         return JNI_ERR;
  3454   // Make the stack size a multiple of the page size so that
  3455   // the yellow/red zones can be guarded.
  3456   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3457         vm_page_size()));
  3459   if (MaxFDLimit) {
  3460     // set the number of file descriptors to max. print out error
  3461     // if getrlimit/setrlimit fails but continue regardless.
  3462     struct rlimit nbr_files;
  3463     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3464     if (status != 0) {
  3465       if (PrintMiscellaneous && (Verbose || WizardMode))
  3466         perror("os::init_2 getrlimit failed");
  3467     } else {
  3468       nbr_files.rlim_cur = nbr_files.rlim_max;
  3470 #ifdef __APPLE__
  3471       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3472       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
  3473       // be used instead
  3474       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3475 #endif
  3477       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3478       if (status != 0) {
  3479         if (PrintMiscellaneous && (Verbose || WizardMode))
  3480           perror("os::init_2 setrlimit failed");
  3485   // at-exit methods are called in the reverse order of their registration.
  3486   // atexit functions are called on return from main or as a result of a
  3487   // call to exit(3C). There can be only 32 of these functions registered
  3488   // and atexit() does not set errno.
  3490   if (PerfAllowAtExitRegistration) {
  3491     // only register atexit functions if PerfAllowAtExitRegistration is set.
  3492     // atexit functions can be delayed until process exit time, which
  3493     // can be problematic for embedded VM situations. Embedded VMs should
  3494     // call DestroyJavaVM() to assure that VM resources are released.
  3496     // note: perfMemory_exit_helper atexit function may be removed in
  3497     // the future if the appropriate cleanup code can be added to the
  3498     // VM_Exit VMOperation's doit method.
  3499     if (atexit(perfMemory_exit_helper) != 0) {
  3500       warning("os::init2 atexit(perfMemory_exit_helper) failed");
  3504   // initialize thread priority policy
  3505   prio_init();
  3507 #ifdef __APPLE__
  3508   // dynamically link to objective c gc registration
  3509   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
  3510   if (handleLibObjc != NULL) {
  3511     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
  3513 #endif
  3515   return JNI_OK;
  3518 // this is called at the end of vm_initialization
  3519 void os::init_3(void) { }
  3521 // Mark the polling page as unreadable
  3522 void os::make_polling_page_unreadable(void) {
  3523   if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
  3524     fatal("Could not disable polling page");
  3525 };
  3527 // Mark the polling page as readable
  3528 void os::make_polling_page_readable(void) {
  3529   if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3530     fatal("Could not enable polling page");
  3532 };
  3534 int os::active_processor_count() {
  3535   return _processor_count;
  3538 void os::set_native_thread_name(const char *name) {
  3539 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  3540   // This is only supported in Snow Leopard and beyond
  3541   if (name != NULL) {
  3542     // Add a "Java: " prefix to the name
  3543     char buf[MAXTHREADNAMESIZE];
  3544     snprintf(buf, sizeof(buf), "Java: %s", name);
  3545     pthread_setname_np(buf);
  3547 #endif
  3550 bool os::distribute_processes(uint length, uint* distribution) {
  3551   // Not yet implemented.
  3552   return false;
  3555 bool os::bind_to_processor(uint processor_id) {
  3556   // Not yet implemented.
  3557   return false;
  3560 ///
  3562 // Suspends the target using the signal mechanism and then grabs the PC before
  3563 // resuming the target. Used by the flat-profiler only
  3564 ExtendedPC os::get_thread_pc(Thread* thread) {
  3565   // Make sure that it is called by the watcher for the VMThread
  3566   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
  3567   assert(thread->is_VM_thread(), "Can only be called for VMThread");
  3569   ExtendedPC epc;
  3571   OSThread* osthread = thread->osthread();
  3572   if (do_suspend(osthread)) {
  3573     if (osthread->ucontext() != NULL) {
  3574       epc = os::Bsd::ucontext_get_pc(osthread->ucontext());
  3575     } else {
  3576       // NULL context is unexpected, double-check this is the VMThread
  3577       guarantee(thread->is_VM_thread(), "can only be called for VMThread");
  3579     do_resume(osthread);
  3581   // failure means pthread_kill failed for some reason - arguably this is
  3582   // a fatal problem, but such problems are ignored elsewhere
  3584   return epc;
  3587 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3589   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3592 ////////////////////////////////////////////////////////////////////////////////
  3593 // debug support
  3595 static address same_page(address x, address y) {
  3596   int page_bits = -os::vm_page_size();
  3597   if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
  3598     return x;
  3599   else if (x > y)
  3600     return (address)(intptr_t(y) | ~page_bits) + 1;
  3601   else
  3602     return (address)(intptr_t(y) & page_bits);
  3605 bool os::find(address addr, outputStream* st) {
  3606   Dl_info dlinfo;
  3607   memset(&dlinfo, 0, sizeof(dlinfo));
  3608   if (dladdr(addr, &dlinfo)) {
  3609     st->print(PTR_FORMAT ": ", addr);
  3610     if (dlinfo.dli_sname != NULL) {
  3611       st->print("%s+%#x", dlinfo.dli_sname,
  3612                  addr - (intptr_t)dlinfo.dli_saddr);
  3613     } else if (dlinfo.dli_fname) {
  3614       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3615     } else {
  3616       st->print("<absolute address>");
  3618     if (dlinfo.dli_fname) {
  3619       st->print(" in %s", dlinfo.dli_fname);
  3621     if (dlinfo.dli_fbase) {
  3622       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
  3624     st->cr();
  3626     if (Verbose) {
  3627       // decode some bytes around the PC
  3628       address begin = same_page(addr-40, addr);
  3629       address end   = same_page(addr+40, addr);
  3630       address       lowest = (address) dlinfo.dli_sname;
  3631       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3632       if (begin < lowest)  begin = lowest;
  3633       Dl_info dlinfo2;
  3634       if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3635           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3636         end = (address) dlinfo2.dli_saddr;
  3637       Disassembler::decode(begin, end, st);
  3639     return true;
  3641   return false;
  3644 ////////////////////////////////////////////////////////////////////////////////
  3645 // misc
  3647 // This does not do anything on Bsd. This is basically a hook for being
  3648 // able to use structured exception handling (thread-local exception filters)
  3649 // on, e.g., Win32.
  3650 void
  3651 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3652                          JavaCallArguments* args, Thread* thread) {
  3653   f(value, method, args, thread);
  3656 void os::print_statistics() {
  3659 int os::message_box(const char* title, const char* message) {
  3660   int i;
  3661   fdStream err(defaultStream::error_fd());
  3662   for (i = 0; i < 78; i++) err.print_raw("=");
  3663   err.cr();
  3664   err.print_raw_cr(title);
  3665   for (i = 0; i < 78; i++) err.print_raw("-");
  3666   err.cr();
  3667   err.print_raw_cr(message);
  3668   for (i = 0; i < 78; i++) err.print_raw("=");
  3669   err.cr();
  3671   char buf[16];
  3672   // Prevent process from exiting upon "read error" without consuming all CPU
  3673   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
  3675   return buf[0] == 'y' || buf[0] == 'Y';
  3678 int os::stat(const char *path, struct stat *sbuf) {
  3679   char pathbuf[MAX_PATH];
  3680   if (strlen(path) > MAX_PATH - 1) {
  3681     errno = ENAMETOOLONG;
  3682     return -1;
  3684   os::native_path(strcpy(pathbuf, path));
  3685   return ::stat(pathbuf, sbuf);
  3688 bool os::check_heap(bool force) {
  3689   return true;
  3692 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
  3693   return ::vsnprintf(buf, count, format, args);
  3696 // Is a (classpath) directory empty?
  3697 bool os::dir_is_empty(const char* path) {
  3698   DIR *dir = NULL;
  3699   struct dirent *ptr;
  3701   dir = opendir(path);
  3702   if (dir == NULL) return true;
  3704   /* Scan the directory */
  3705   bool result = true;
  3706   char buf[sizeof(struct dirent) + MAX_PATH];
  3707   while (result && (ptr = ::readdir(dir)) != NULL) {
  3708     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3709       result = false;
  3712   closedir(dir);
  3713   return result;
  3716 // This code originates from JDK's sysOpen and open64_w
  3717 // from src/solaris/hpi/src/system_md.c
  3719 #ifndef O_DELETE
  3720 #define O_DELETE 0x10000
  3721 #endif
  3723 // Open a file. Unlink the file immediately after open returns
  3724 // if the specified oflag has the O_DELETE flag set.
  3725 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3727 int os::open(const char *path, int oflag, int mode) {
  3729   if (strlen(path) > MAX_PATH - 1) {
  3730     errno = ENAMETOOLONG;
  3731     return -1;
  3733   int fd;
  3734   int o_delete = (oflag & O_DELETE);
  3735   oflag = oflag & ~O_DELETE;
  3737   fd = ::open(path, oflag, mode);
  3738   if (fd == -1) return -1;
  3740   //If the open succeeded, the file might still be a directory
  3742     struct stat buf;
  3743     int ret = ::fstat(fd, &buf);
  3744     int st_mode = buf.st_mode;
  3746     if (ret != -1) {
  3747       if ((st_mode & S_IFMT) == S_IFDIR) {
  3748         errno = EISDIR;
  3749         ::close(fd);
  3750         return -1;
  3752     } else {
  3753       ::close(fd);
  3754       return -1;
  3758     /*
  3759      * All file descriptors that are opened in the JVM and not
  3760      * specifically destined for a subprocess should have the
  3761      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3762      * party native code might fork and exec without closing all
  3763      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3764      * UNIXProcess.c), and this in turn might:
  3766      * - cause end-of-file to fail to be detected on some file
  3767      *   descriptors, resulting in mysterious hangs, or
  3769      * - might cause an fopen in the subprocess to fail on a system
  3770      *   suffering from bug 1085341.
  3772      * (Yes, the default setting of the close-on-exec flag is a Unix
  3773      * design flaw)
  3775      * See:
  3776      * 1085341: 32-bit stdio routines should support file descriptors >255
  3777      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3778      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3779      */
  3780 #ifdef FD_CLOEXEC
  3782         int flags = ::fcntl(fd, F_GETFD);
  3783         if (flags != -1)
  3784             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3786 #endif
  3788   if (o_delete != 0) {
  3789     ::unlink(path);
  3791   return fd;
  3795 // create binary file, rewriting existing file if required
  3796 int os::create_binary_file(const char* path, bool rewrite_existing) {
  3797   int oflags = O_WRONLY | O_CREAT;
  3798   if (!rewrite_existing) {
  3799     oflags |= O_EXCL;
  3801   return ::open(path, oflags, S_IREAD | S_IWRITE);
  3804 // return current position of file pointer
  3805 jlong os::current_file_offset(int fd) {
  3806   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
  3809 // move file pointer to the specified offset
  3810 jlong os::seek_to_file_offset(int fd, jlong offset) {
  3811   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
  3814 // This code originates from JDK's sysAvailable
  3815 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
  3817 int os::available(int fd, jlong *bytes) {
  3818   jlong cur, end;
  3819   int mode;
  3820   struct stat buf;
  3822   if (::fstat(fd, &buf) >= 0) {
  3823     mode = buf.st_mode;
  3824     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3825       /*
  3826       * XXX: is the following call interruptible? If so, this might
  3827       * need to go through the INTERRUPT_IO() wrapper as for other
  3828       * blocking, interruptible calls in this file.
  3829       */
  3830       int n;
  3831       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3832         *bytes = n;
  3833         return 1;
  3837   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
  3838     return 0;
  3839   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
  3840     return 0;
  3841   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
  3842     return 0;
  3844   *bytes = end - cur;
  3845   return 1;
  3848 int os::socket_available(int fd, jint *pbytes) {
  3849    if (fd < 0)
  3850      return OS_OK;
  3852    int ret;
  3854    RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3856    //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  3857    // is expected to return 0 on failure and 1 on success to the jdk.
  3859    return (ret == OS_ERR) ? 0 : 1;
  3862 // Map a block of memory.
  3863 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  3864                      char *addr, size_t bytes, bool read_only,
  3865                      bool allow_exec) {
  3866   int prot;
  3867   int flags;
  3869   if (read_only) {
  3870     prot = PROT_READ;
  3871     flags = MAP_SHARED;
  3872   } else {
  3873     prot = PROT_READ | PROT_WRITE;
  3874     flags = MAP_PRIVATE;
  3877   if (allow_exec) {
  3878     prot |= PROT_EXEC;
  3881   if (addr != NULL) {
  3882     flags |= MAP_FIXED;
  3885   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
  3886                                      fd, file_offset);
  3887   if (mapped_address == MAP_FAILED) {
  3888     return NULL;
  3890   return mapped_address;
  3894 // Remap a block of memory.
  3895 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  3896                        char *addr, size_t bytes, bool read_only,
  3897                        bool allow_exec) {
  3898   // same as map_memory() on this OS
  3899   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  3900                         allow_exec);
  3904 // Unmap a block of memory.
  3905 bool os::pd_unmap_memory(char* addr, size_t bytes) {
  3906   return munmap(addr, bytes) == 0;
  3909 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  3910 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  3911 // of a thread.
  3912 //
  3913 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
  3914 // the fast estimate available on the platform.
  3916 jlong os::current_thread_cpu_time() {
  3917 #ifdef __APPLE__
  3918   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
  3919 #endif
  3922 jlong os::thread_cpu_time(Thread* thread) {
  3925 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  3926 #ifdef __APPLE__
  3927   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  3928 #endif
  3931 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
  3932 #ifdef __APPLE__
  3933   struct thread_basic_info tinfo;
  3934   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
  3935   kern_return_t kr;
  3936   thread_t mach_thread;
  3938   mach_thread = thread->osthread()->thread_id();
  3939   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  3940   if (kr != KERN_SUCCESS)
  3941     return -1;
  3943   if (user_sys_cpu_time) {
  3944     jlong nanos;
  3945     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  3946     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  3947     return nanos;
  3948   } else {
  3949     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
  3951 #endif
  3955 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  3956   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  3957   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  3958   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  3959   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  3962 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  3963   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  3964   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  3965   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  3966   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  3969 bool os::is_thread_cpu_time_supported() {
  3970 #ifdef __APPLE__
  3971   return true;
  3972 #else
  3973   return false;
  3974 #endif
  3977 // System loadavg support.  Returns -1 if load average cannot be obtained.
  3978 // Bsd doesn't yet have a (official) notion of processor sets,
  3979 // so just return the system wide load average.
  3980 int os::loadavg(double loadavg[], int nelem) {
  3981   return ::getloadavg(loadavg, nelem);
  3984 void os::pause() {
  3985   char filename[MAX_PATH];
  3986   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  3987     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  3988   } else {
  3989     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  3992   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  3993   if (fd != -1) {
  3994     struct stat buf;
  3995     ::close(fd);
  3996     while (::stat(filename, &buf) == 0) {
  3997       (void)::poll(NULL, 0, 100);
  3999   } else {
  4000     jio_fprintf(stderr,
  4001       "Could not open pause file '%s', continuing immediately.\n", filename);
  4006 // Refer to the comments in os_solaris.cpp park-unpark.
  4007 //
  4008 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
  4009 // hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
  4010 // For specifics regarding the bug see GLIBC BUGID 261237 :
  4011 //    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
  4012 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
  4013 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
  4014 // is used.  (The simple C test-case provided in the GLIBC bug report manifests the
  4015 // hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
  4016 // and monitorenter when we're using 1-0 locking.  All those operations may result in
  4017 // calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
  4018 // of libpthread avoids the problem, but isn't practical.
  4019 //
  4020 // Possible remedies:
  4021 //
  4022 // 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
  4023 //      This is palliative and probabilistic, however.  If the thread is preempted
  4024 //      between the call to compute_abstime() and pthread_cond_timedwait(), more
  4025 //      than the minimum period may have passed, and the abstime may be stale (in the
  4026 //      past) resultin in a hang.   Using this technique reduces the odds of a hang
  4027 //      but the JVM is still vulnerable, particularly on heavily loaded systems.
  4028 //
  4029 // 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
  4030 //      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
  4031 //      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
  4032 //      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
  4033 //      thread.
  4034 //
  4035 // 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
  4036 //      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
  4037 //      a timeout request to the chron thread and then blocking via pthread_cond_wait().
  4038 //      This also works well.  In fact it avoids kernel-level scalability impediments
  4039 //      on certain platforms that don't handle lots of active pthread_cond_timedwait()
  4040 //      timers in a graceful fashion.
  4041 //
  4042 // 4.   When the abstime value is in the past it appears that control returns
  4043 //      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
  4044 //      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
  4045 //      can avoid the problem by reinitializing the condvar -- by cond_destroy()
  4046 //      followed by cond_init() -- after all calls to pthread_cond_timedwait().
  4047 //      It may be possible to avoid reinitialization by checking the return
  4048 //      value from pthread_cond_timedwait().  In addition to reinitializing the
  4049 //      condvar we must establish the invariant that cond_signal() is only called
  4050 //      within critical sections protected by the adjunct mutex.  This prevents
  4051 //      cond_signal() from "seeing" a condvar that's in the midst of being
  4052 //      reinitialized or that is corrupt.  Sadly, this invariant obviates the
  4053 //      desirable signal-after-unlock optimization that avoids futile context switching.
  4054 //
  4055 //      I'm also concerned that some versions of NTPL might allocate an auxilliary
  4056 //      structure when a condvar is used or initialized.  cond_destroy()  would
  4057 //      release the helper structure.  Our reinitialize-after-timedwait fix
  4058 //      put excessive stress on malloc/free and locks protecting the c-heap.
  4059 //
  4060 // We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
  4061 // It may be possible to refine (4) by checking the kernel and NTPL verisons
  4062 // and only enabling the work-around for vulnerable environments.
  4064 // utility to compute the abstime argument to timedwait:
  4065 // millis is the relative timeout time
  4066 // abstime will be the absolute timeout time
  4067 // TODO: replace compute_abstime() with unpackTime()
  4069 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4070   if (millis < 0)  millis = 0;
  4071   struct timeval now;
  4072   int status = gettimeofday(&now, NULL);
  4073   assert(status == 0, "gettimeofday");
  4074   jlong seconds = millis / 1000;
  4075   millis %= 1000;
  4076   if (seconds > 50000000) { // see man cond_timedwait(3T)
  4077     seconds = 50000000;
  4079   abstime->tv_sec = now.tv_sec  + seconds;
  4080   long       usec = now.tv_usec + millis * 1000;
  4081   if (usec >= 1000000) {
  4082     abstime->tv_sec += 1;
  4083     usec -= 1000000;
  4085   abstime->tv_nsec = usec * 1000;
  4086   return abstime;
  4090 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
  4091 // Conceptually TryPark() should be equivalent to park(0).
  4093 int os::PlatformEvent::TryPark() {
  4094   for (;;) {
  4095     const int v = _Event ;
  4096     guarantee ((v == 0) || (v == 1), "invariant") ;
  4097     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
  4101 void os::PlatformEvent::park() {       // AKA "down()"
  4102   // Invariant: Only the thread associated with the Event/PlatformEvent
  4103   // may call park().
  4104   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4105   int v ;
  4106   for (;;) {
  4107       v = _Event ;
  4108       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4110   guarantee (v >= 0, "invariant") ;
  4111   if (v == 0) {
  4112      // Do this the hard way by blocking ...
  4113      int status = pthread_mutex_lock(_mutex);
  4114      assert_status(status == 0, status, "mutex_lock");
  4115      guarantee (_nParked == 0, "invariant") ;
  4116      ++ _nParked ;
  4117      while (_Event < 0) {
  4118         status = pthread_cond_wait(_cond, _mutex);
  4119         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4120         // Treat this the same as if the wait was interrupted
  4121         if (status == ETIMEDOUT) { status = EINTR; }
  4122         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4124      -- _nParked ;
  4126     _Event = 0 ;
  4127      status = pthread_mutex_unlock(_mutex);
  4128      assert_status(status == 0, status, "mutex_unlock");
  4129     // Paranoia to ensure our locked and lock-free paths interact
  4130     // correctly with each other.
  4131     OrderAccess::fence();
  4133   guarantee (_Event >= 0, "invariant") ;
  4136 int os::PlatformEvent::park(jlong millis) {
  4137   guarantee (_nParked == 0, "invariant") ;
  4139   int v ;
  4140   for (;;) {
  4141       v = _Event ;
  4142       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4144   guarantee (v >= 0, "invariant") ;
  4145   if (v != 0) return OS_OK ;
  4147   // We do this the hard way, by blocking the thread.
  4148   // Consider enforcing a minimum timeout value.
  4149   struct timespec abst;
  4150   compute_abstime(&abst, millis);
  4152   int ret = OS_TIMEOUT;
  4153   int status = pthread_mutex_lock(_mutex);
  4154   assert_status(status == 0, status, "mutex_lock");
  4155   guarantee (_nParked == 0, "invariant") ;
  4156   ++_nParked ;
  4158   // Object.wait(timo) will return because of
  4159   // (a) notification
  4160   // (b) timeout
  4161   // (c) thread.interrupt
  4162   //
  4163   // Thread.interrupt and object.notify{All} both call Event::set.
  4164   // That is, we treat thread.interrupt as a special case of notification.
  4165   // The underlying Solaris implementation, cond_timedwait, admits
  4166   // spurious/premature wakeups, but the JLS/JVM spec prevents the
  4167   // JVM from making those visible to Java code.  As such, we must
  4168   // filter out spurious wakeups.  We assume all ETIME returns are valid.
  4169   //
  4170   // TODO: properly differentiate simultaneous notify+interrupt.
  4171   // In that case, we should propagate the notify to another waiter.
  4173   while (_Event < 0) {
  4174     status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
  4175     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4176       pthread_cond_destroy (_cond);
  4177       pthread_cond_init (_cond, NULL) ;
  4179     assert_status(status == 0 || status == EINTR ||
  4180                   status == ETIMEDOUT,
  4181                   status, "cond_timedwait");
  4182     if (!FilterSpuriousWakeups) break ;                 // previous semantics
  4183     if (status == ETIMEDOUT) break ;
  4184     // We consume and ignore EINTR and spurious wakeups.
  4186   --_nParked ;
  4187   if (_Event >= 0) {
  4188      ret = OS_OK;
  4190   _Event = 0 ;
  4191   status = pthread_mutex_unlock(_mutex);
  4192   assert_status(status == 0, status, "mutex_unlock");
  4193   assert (_nParked == 0, "invariant") ;
  4194   // Paranoia to ensure our locked and lock-free paths interact
  4195   // correctly with each other.
  4196   OrderAccess::fence();
  4197   return ret;
  4200 void os::PlatformEvent::unpark() {
  4201   // Transitions for _Event:
  4202   //    0 :=> 1
  4203   //    1 :=> 1
  4204   //   -1 :=> either 0 or 1; must signal target thread
  4205   //          That is, we can safely transition _Event from -1 to either
  4206   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
  4207   //          unpark() calls.
  4208   // See also: "Semaphores in Plan 9" by Mullender & Cox
  4209   //
  4210   // Note: Forcing a transition from "-1" to "1" on an unpark() means
  4211   // that it will take two back-to-back park() calls for the owning
  4212   // thread to block. This has the benefit of forcing a spurious return
  4213   // from the first park() call after an unpark() call which will help
  4214   // shake out uses of park() and unpark() without condition variables.
  4216   if (Atomic::xchg(1, &_Event) >= 0) return;
  4218   // Wait for the thread associated with the event to vacate
  4219   int status = pthread_mutex_lock(_mutex);
  4220   assert_status(status == 0, status, "mutex_lock");
  4221   int AnyWaiters = _nParked;
  4222   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
  4223   if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
  4224     AnyWaiters = 0;
  4225     pthread_cond_signal(_cond);
  4227   status = pthread_mutex_unlock(_mutex);
  4228   assert_status(status == 0, status, "mutex_unlock");
  4229   if (AnyWaiters != 0) {
  4230     status = pthread_cond_signal(_cond);
  4231     assert_status(status == 0, status, "cond_signal");
  4234   // Note that we signal() _after dropping the lock for "immortal" Events.
  4235   // This is safe and avoids a common class of  futile wakeups.  In rare
  4236   // circumstances this can cause a thread to return prematurely from
  4237   // cond_{timed}wait() but the spurious wakeup is benign and the victim will
  4238   // simply re-test the condition and re-park itself.
  4242 // JSR166
  4243 // -------------------------------------------------------
  4245 /*
  4246  * The solaris and bsd implementations of park/unpark are fairly
  4247  * conservative for now, but can be improved. They currently use a
  4248  * mutex/condvar pair, plus a a count.
  4249  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4250  * sets count to 1 and signals condvar.  Only one thread ever waits
  4251  * on the condvar. Contention seen when trying to park implies that someone
  4252  * is unparking you, so don't wait. And spurious returns are fine, so there
  4253  * is no need to track notifications.
  4254  */
  4256 #define MAX_SECS 100000000
  4257 /*
  4258  * This code is common to bsd and solaris and will be moved to a
  4259  * common place in dolphin.
  4261  * The passed in time value is either a relative time in nanoseconds
  4262  * or an absolute time in milliseconds. Either way it has to be unpacked
  4263  * into suitable seconds and nanoseconds components and stored in the
  4264  * given timespec structure.
  4265  * Given time is a 64-bit value and the time_t used in the timespec is only
  4266  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4267  * overflow if times way in the future are given. Further on Solaris versions
  4268  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4269  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4270  * As it will be 28 years before "now + 100000000" will overflow we can
  4271  * ignore overflow and just impose a hard-limit on seconds using the value
  4272  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4273  * years from "now".
  4274  */
  4276 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4277   assert (time > 0, "convertTime");
  4279   struct timeval now;
  4280   int status = gettimeofday(&now, NULL);
  4281   assert(status == 0, "gettimeofday");
  4283   time_t max_secs = now.tv_sec + MAX_SECS;
  4285   if (isAbsolute) {
  4286     jlong secs = time / 1000;
  4287     if (secs > max_secs) {
  4288       absTime->tv_sec = max_secs;
  4290     else {
  4291       absTime->tv_sec = secs;
  4293     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4295   else {
  4296     jlong secs = time / NANOSECS_PER_SEC;
  4297     if (secs >= MAX_SECS) {
  4298       absTime->tv_sec = max_secs;
  4299       absTime->tv_nsec = 0;
  4301     else {
  4302       absTime->tv_sec = now.tv_sec + secs;
  4303       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4304       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4305         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4306         ++absTime->tv_sec; // note: this must be <= max_secs
  4310   assert(absTime->tv_sec >= 0, "tv_sec < 0");
  4311   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
  4312   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
  4313   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
  4316 void Parker::park(bool isAbsolute, jlong time) {
  4317   // Ideally we'd do something useful while spinning, such
  4318   // as calling unpackTime().
  4320   // Optional fast-path check:
  4321   // Return immediately if a permit is available.
  4322   // We depend on Atomic::xchg() having full barrier semantics
  4323   // since we are doing a lock-free update to _counter.
  4324   if (Atomic::xchg(0, &_counter) > 0) return;
  4326   Thread* thread = Thread::current();
  4327   assert(thread->is_Java_thread(), "Must be JavaThread");
  4328   JavaThread *jt = (JavaThread *)thread;
  4330   // Optional optimization -- avoid state transitions if there's an interrupt pending.
  4331   // Check interrupt before trying to wait
  4332   if (Thread::is_interrupted(thread, false)) {
  4333     return;
  4336   // Next, demultiplex/decode time arguments
  4337   struct timespec absTime;
  4338   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
  4339     return;
  4341   if (time > 0) {
  4342     unpackTime(&absTime, isAbsolute, time);
  4346   // Enter safepoint region
  4347   // Beware of deadlocks such as 6317397.
  4348   // The per-thread Parker:: mutex is a classic leaf-lock.
  4349   // In particular a thread must never block on the Threads_lock while
  4350   // holding the Parker:: mutex.  If safepoints are pending both the
  4351   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
  4352   ThreadBlockInVM tbivm(jt);
  4354   // Don't wait if cannot get lock since interference arises from
  4355   // unblocking.  Also. check interrupt before trying wait
  4356   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
  4357     return;
  4360   int status ;
  4361   if (_counter > 0)  { // no wait needed
  4362     _counter = 0;
  4363     status = pthread_mutex_unlock(_mutex);
  4364     assert (status == 0, "invariant") ;
  4365     // Paranoia to ensure our locked and lock-free paths interact
  4366     // correctly with each other and Java-level accesses.
  4367     OrderAccess::fence();
  4368     return;
  4371 #ifdef ASSERT
  4372   // Don't catch signals while blocked; let the running threads have the signals.
  4373   // (This allows a debugger to break into the running thread.)
  4374   sigset_t oldsigs;
  4375   sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
  4376   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
  4377 #endif
  4379   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  4380   jt->set_suspend_equivalent();
  4381   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  4383   if (time == 0) {
  4384     status = pthread_cond_wait (_cond, _mutex) ;
  4385   } else {
  4386     status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
  4387     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4388       pthread_cond_destroy (_cond) ;
  4389       pthread_cond_init    (_cond, NULL);
  4392   assert_status(status == 0 || status == EINTR ||
  4393                 status == ETIMEDOUT,
  4394                 status, "cond_timedwait");
  4396 #ifdef ASSERT
  4397   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
  4398 #endif
  4400   _counter = 0 ;
  4401   status = pthread_mutex_unlock(_mutex) ;
  4402   assert_status(status == 0, status, "invariant") ;
  4403   // Paranoia to ensure our locked and lock-free paths interact
  4404   // correctly with each other and Java-level accesses.
  4405   OrderAccess::fence();
  4407   // If externally suspended while waiting, re-suspend
  4408   if (jt->handle_special_suspend_equivalent_condition()) {
  4409     jt->java_suspend_self();
  4413 void Parker::unpark() {
  4414   int s, status ;
  4415   status = pthread_mutex_lock(_mutex);
  4416   assert (status == 0, "invariant") ;
  4417   s = _counter;
  4418   _counter = 1;
  4419   if (s < 1) {
  4420      if (WorkAroundNPTLTimedWaitHang) {
  4421         status = pthread_cond_signal (_cond) ;
  4422         assert (status == 0, "invariant") ;
  4423         status = pthread_mutex_unlock(_mutex);
  4424         assert (status == 0, "invariant") ;
  4425      } else {
  4426         status = pthread_mutex_unlock(_mutex);
  4427         assert (status == 0, "invariant") ;
  4428         status = pthread_cond_signal (_cond) ;
  4429         assert (status == 0, "invariant") ;
  4431   } else {
  4432     pthread_mutex_unlock(_mutex);
  4433     assert (status == 0, "invariant") ;
  4438 /* Darwin has no "environ" in a dynamic library. */
  4439 #ifdef __APPLE__
  4440 #include <crt_externs.h>
  4441 #define environ (*_NSGetEnviron())
  4442 #else
  4443 extern char** environ;
  4444 #endif
  4446 // Run the specified command in a separate process. Return its exit value,
  4447 // or -1 on failure (e.g. can't fork a new process).
  4448 // Unlike system(), this function can be called from signal handler. It
  4449 // doesn't block SIGINT et al.
  4450 int os::fork_and_exec(char* cmd) {
  4451   const char * argv[4] = {"sh", "-c", cmd, NULL};
  4453   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
  4454   // pthread_atfork handlers and reset pthread library. All we need is a
  4455   // separate process to execve. Make a direct syscall to fork process.
  4456   // On IA64 there's no fork syscall, we have to use fork() and hope for
  4457   // the best...
  4458   pid_t pid = fork();
  4460   if (pid < 0) {
  4461     // fork failed
  4462     return -1;
  4464   } else if (pid == 0) {
  4465     // child process
  4467     // execve() in BsdThreads will call pthread_kill_other_threads_np()
  4468     // first to kill every thread on the thread list. Because this list is
  4469     // not reset by fork() (see notes above), execve() will instead kill
  4470     // every thread in the parent process. We know this is the only thread
  4471     // in the new process, so make a system call directly.
  4472     // IA64 should use normal execve() from glibc to match the glibc fork()
  4473     // above.
  4474     execve("/bin/sh", (char* const*)argv, environ);
  4476     // execve failed
  4477     _exit(-1);
  4479   } else  {
  4480     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
  4481     // care about the actual exit code, for now.
  4483     int status;
  4485     // Wait for the child process to exit.  This returns immediately if
  4486     // the child has already exited. */
  4487     while (waitpid(pid, &status, 0) < 0) {
  4488         switch (errno) {
  4489         case ECHILD: return 0;
  4490         case EINTR: break;
  4491         default: return -1;
  4495     if (WIFEXITED(status)) {
  4496        // The child exited normally; get its exit code.
  4497        return WEXITSTATUS(status);
  4498     } else if (WIFSIGNALED(status)) {
  4499        // The child exited because of a signal
  4500        // The best value to return is 0x80 + signal number,
  4501        // because that is what all Unix shells do, and because
  4502        // it allows callers to distinguish between process exit and
  4503        // process death by signal.
  4504        return 0x80 + WTERMSIG(status);
  4505     } else {
  4506        // Unknown exit code; pass it through
  4507        return status;
  4512 // is_headless_jre()
  4513 //
  4514 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
  4515 // in order to report if we are running in a headless jre
  4516 //
  4517 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4518 // as libawt.so, and renamed libawt_xawt.so
  4519 //
  4520 bool os::is_headless_jre() {
  4521     struct stat statbuf;
  4522     char buf[MAXPATHLEN];
  4523     char libmawtpath[MAXPATHLEN];
  4524     const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
  4525     const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
  4526     char *p;
  4528     // Get path to libjvm.so
  4529     os::jvm_path(buf, sizeof(buf));
  4531     // Get rid of libjvm.so
  4532     p = strrchr(buf, '/');
  4533     if (p == NULL) return false;
  4534     else *p = '\0';
  4536     // Get rid of client or server
  4537     p = strrchr(buf, '/');
  4538     if (p == NULL) return false;
  4539     else *p = '\0';
  4541     // check xawt/libmawt.so
  4542     strcpy(libmawtpath, buf);
  4543     strcat(libmawtpath, xawtstr);
  4544     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4546     // check libawt_xawt.so
  4547     strcpy(libmawtpath, buf);
  4548     strcat(libmawtpath, new_xawtstr);
  4549     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4551     return true;
  4554 // Get the default path to the core file
  4555 // Returns the length of the string
  4556 int os::get_core_path(char* buffer, size_t bufferSize) {
  4557   int n = jio_snprintf(buffer, bufferSize, "/cores");
  4559   // Truncate if theoretical string was longer than bufferSize
  4560   n = MIN2(n, (int)bufferSize);
  4562   return n;

mercurial