src/os/bsd/vm/os_bsd.cpp

Thu, 10 Apr 2014 04:07:45 -0700

author
goetz
date
Thu, 10 Apr 2014 04:07:45 -0700
changeset 6556
6048424d3865
parent 6553
21dd1c827123
child 6667
917873d2983d
child 6779
364b73402247
permissions
-rw-r--r--

8038201: Clean up misleading usage of malloc() in init_system_properties_values()
Summary: Remove the misleading malloc macro and cleanup the code
Reviewed-by: dsamersoff, kvn
Contributed-by: goetz.lindenmaier@sap.com

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 // no precompiled headers
    26 #include "classfile/classLoader.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "classfile/vmSymbols.hpp"
    29 #include "code/icBuffer.hpp"
    30 #include "code/vtableStubs.hpp"
    31 #include "compiler/compileBroker.hpp"
    32 #include "compiler/disassembler.hpp"
    33 #include "interpreter/interpreter.hpp"
    34 #include "jvm_bsd.h"
    35 #include "memory/allocation.inline.hpp"
    36 #include "memory/filemap.hpp"
    37 #include "mutex_bsd.inline.hpp"
    38 #include "oops/oop.inline.hpp"
    39 #include "os_share_bsd.hpp"
    40 #include "prims/jniFastGetField.hpp"
    41 #include "prims/jvm.h"
    42 #include "prims/jvm_misc.hpp"
    43 #include "runtime/arguments.hpp"
    44 #include "runtime/extendedPC.hpp"
    45 #include "runtime/globals.hpp"
    46 #include "runtime/interfaceSupport.hpp"
    47 #include "runtime/java.hpp"
    48 #include "runtime/javaCalls.hpp"
    49 #include "runtime/mutexLocker.hpp"
    50 #include "runtime/objectMonitor.hpp"
    51 #include "runtime/osThread.hpp"
    52 #include "runtime/perfMemory.hpp"
    53 #include "runtime/sharedRuntime.hpp"
    54 #include "runtime/statSampler.hpp"
    55 #include "runtime/stubRoutines.hpp"
    56 #include "runtime/thread.inline.hpp"
    57 #include "runtime/threadCritical.hpp"
    58 #include "runtime/timer.hpp"
    59 #include "services/attachListener.hpp"
    60 #include "services/memTracker.hpp"
    61 #include "services/runtimeService.hpp"
    62 #include "utilities/decoder.hpp"
    63 #include "utilities/defaultStream.hpp"
    64 #include "utilities/events.hpp"
    65 #include "utilities/growableArray.hpp"
    66 #include "utilities/vmError.hpp"
    68 // put OS-includes here
    69 # include <sys/types.h>
    70 # include <sys/mman.h>
    71 # include <sys/stat.h>
    72 # include <sys/select.h>
    73 # include <pthread.h>
    74 # include <signal.h>
    75 # include <errno.h>
    76 # include <dlfcn.h>
    77 # include <stdio.h>
    78 # include <unistd.h>
    79 # include <sys/resource.h>
    80 # include <pthread.h>
    81 # include <sys/stat.h>
    82 # include <sys/time.h>
    83 # include <sys/times.h>
    84 # include <sys/utsname.h>
    85 # include <sys/socket.h>
    86 # include <sys/wait.h>
    87 # include <time.h>
    88 # include <pwd.h>
    89 # include <poll.h>
    90 # include <semaphore.h>
    91 # include <fcntl.h>
    92 # include <string.h>
    93 # include <sys/param.h>
    94 # include <sys/sysctl.h>
    95 # include <sys/ipc.h>
    96 # include <sys/shm.h>
    97 #ifndef __APPLE__
    98 # include <link.h>
    99 #endif
   100 # include <stdint.h>
   101 # include <inttypes.h>
   102 # include <sys/ioctl.h>
   103 # include <sys/syscall.h>
   105 #if defined(__FreeBSD__) || defined(__NetBSD__)
   106 # include <elf.h>
   107 #endif
   109 #ifdef __APPLE__
   110 # include <mach/mach.h> // semaphore_* API
   111 # include <mach-o/dyld.h>
   112 # include <sys/proc_info.h>
   113 # include <objc/objc-auto.h>
   114 #endif
   116 #ifndef MAP_ANONYMOUS
   117 #define MAP_ANONYMOUS MAP_ANON
   118 #endif
   120 #define MAX_PATH    (2 * K)
   122 // for timer info max values which include all bits
   123 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
   125 #define LARGEPAGES_BIT (1 << 6)
   126 ////////////////////////////////////////////////////////////////////////////////
   127 // global variables
   128 julong os::Bsd::_physical_memory = 0;
   131 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
   132 pthread_t os::Bsd::_main_thread;
   133 int os::Bsd::_page_size = -1;
   135 static jlong initial_time_count=0;
   137 static int clock_tics_per_sec = 100;
   139 // For diagnostics to print a message once. see run_periodic_checks
   140 static sigset_t check_signal_done;
   141 static bool check_signals = true;
   143 static pid_t _initial_pid = 0;
   145 /* Signal number used to suspend/resume a thread */
   147 /* do not use any signal number less than SIGSEGV, see 4355769 */
   148 static int SR_signum = SIGUSR2;
   149 sigset_t SR_sigset;
   152 ////////////////////////////////////////////////////////////////////////////////
   153 // utility functions
   155 static int SR_initialize();
   156 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
   158 julong os::available_memory() {
   159   return Bsd::available_memory();
   160 }
   162 // available here means free
   163 julong os::Bsd::available_memory() {
   164   uint64_t available = physical_memory() >> 2;
   165 #ifdef __APPLE__
   166   mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
   167   vm_statistics64_data_t vmstat;
   168   kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64,
   169                                          (host_info64_t)&vmstat, &count);
   170   assert(kerr == KERN_SUCCESS,
   171          "host_statistics64 failed - check mach_host_self() and count");
   172   if (kerr == KERN_SUCCESS) {
   173     available = vmstat.free_count * os::vm_page_size();
   174   }
   175 #endif
   176   return available;
   177 }
   179 julong os::physical_memory() {
   180   return Bsd::physical_memory();
   181 }
   183 ////////////////////////////////////////////////////////////////////////////////
   184 // environment support
   186 bool os::getenv(const char* name, char* buf, int len) {
   187   const char* val = ::getenv(name);
   188   if (val != NULL && strlen(val) < (size_t)len) {
   189     strcpy(buf, val);
   190     return true;
   191   }
   192   if (len > 0) buf[0] = 0;  // return a null string
   193   return false;
   194 }
   197 // Return true if user is running as root.
   199 bool os::have_special_privileges() {
   200   static bool init = false;
   201   static bool privileges = false;
   202   if (!init) {
   203     privileges = (getuid() != geteuid()) || (getgid() != getegid());
   204     init = true;
   205   }
   206   return privileges;
   207 }
   211 // Cpu architecture string
   212 #if   defined(ZERO)
   213 static char cpu_arch[] = ZERO_LIBARCH;
   214 #elif defined(IA64)
   215 static char cpu_arch[] = "ia64";
   216 #elif defined(IA32)
   217 static char cpu_arch[] = "i386";
   218 #elif defined(AMD64)
   219 static char cpu_arch[] = "amd64";
   220 #elif defined(ARM)
   221 static char cpu_arch[] = "arm";
   222 #elif defined(PPC32)
   223 static char cpu_arch[] = "ppc";
   224 #elif defined(SPARC)
   225 #  ifdef _LP64
   226 static char cpu_arch[] = "sparcv9";
   227 #  else
   228 static char cpu_arch[] = "sparc";
   229 #  endif
   230 #else
   231 #error Add appropriate cpu_arch setting
   232 #endif
   234 // Compiler variant
   235 #ifdef COMPILER2
   236 #define COMPILER_VARIANT "server"
   237 #else
   238 #define COMPILER_VARIANT "client"
   239 #endif
   242 void os::Bsd::initialize_system_info() {
   243   int mib[2];
   244   size_t len;
   245   int cpu_val;
   246   julong mem_val;
   248   /* get processors count via hw.ncpus sysctl */
   249   mib[0] = CTL_HW;
   250   mib[1] = HW_NCPU;
   251   len = sizeof(cpu_val);
   252   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
   253        assert(len == sizeof(cpu_val), "unexpected data size");
   254        set_processor_count(cpu_val);
   255   }
   256   else {
   257        set_processor_count(1);   // fallback
   258   }
   260   /* get physical memory via hw.memsize sysctl (hw.memsize is used
   261    * since it returns a 64 bit value)
   262    */
   263   mib[0] = CTL_HW;
   265 #if defined (HW_MEMSIZE) // Apple
   266   mib[1] = HW_MEMSIZE;
   267 #elif defined(HW_PHYSMEM) // Most of BSD
   268   mib[1] = HW_PHYSMEM;
   269 #elif defined(HW_REALMEM) // Old FreeBSD
   270   mib[1] = HW_REALMEM;
   271 #else
   272   #error No ways to get physmem
   273 #endif
   275   len = sizeof(mem_val);
   276   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
   277        assert(len == sizeof(mem_val), "unexpected data size");
   278        _physical_memory = mem_val;
   279   } else {
   280        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
   281   }
   283 #ifdef __OpenBSD__
   284   {
   285        // limit _physical_memory memory view on OpenBSD since
   286        // datasize rlimit restricts us anyway.
   287        struct rlimit limits;
   288        getrlimit(RLIMIT_DATA, &limits);
   289        _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
   290   }
   291 #endif
   292 }
   294 #ifdef __APPLE__
   295 static const char *get_home() {
   296   const char *home_dir = ::getenv("HOME");
   297   if ((home_dir == NULL) || (*home_dir == '\0')) {
   298     struct passwd *passwd_info = getpwuid(geteuid());
   299     if (passwd_info != NULL) {
   300       home_dir = passwd_info->pw_dir;
   301     }
   302   }
   304   return home_dir;
   305 }
   306 #endif
   308 void os::init_system_properties_values() {
   309   // The next steps are taken in the product version:
   310   //
   311   // Obtain the JAVA_HOME value from the location of libjvm.so.
   312   // This library should be located at:
   313   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
   314   //
   315   // If "/jre/lib/" appears at the right place in the path, then we
   316   // assume libjvm.so is installed in a JDK and we use this path.
   317   //
   318   // Otherwise exit with message: "Could not create the Java virtual machine."
   319   //
   320   // The following extra steps are taken in the debugging version:
   321   //
   322   // If "/jre/lib/" does NOT appear at the right place in the path
   323   // instead of exit check for $JAVA_HOME environment variable.
   324   //
   325   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
   326   // then we append a fake suffix "hotspot/libjvm.so" to this path so
   327   // it looks like libjvm.so is installed there
   328   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
   329   //
   330   // Otherwise exit.
   331   //
   332   // Important note: if the location of libjvm.so changes this
   333   // code needs to be changed accordingly.
   335 // See ld(1):
   336 //      The linker uses the following search paths to locate required
   337 //      shared libraries:
   338 //        1: ...
   339 //        ...
   340 //        7: The default directories, normally /lib and /usr/lib.
   341 #ifndef DEFAULT_LIBPATH
   342 #define DEFAULT_LIBPATH "/lib:/usr/lib"
   343 #endif
   345 // Base path of extensions installed on the system.
   346 #define SYS_EXT_DIR     "/usr/java/packages"
   347 #define EXTENSIONS_DIR  "/lib/ext"
   348 #define ENDORSED_DIR    "/lib/endorsed"
   350 #ifndef __APPLE__
   352   // Buffer that fits several sprintfs.
   353   // Note that the space for the colon and the trailing null are provided
   354   // by the nulls included by the sizeof operator.
   355   const size_t bufsize =
   356     MAX3((size_t)MAXPATHLEN,  // For dll_dir & friends.
   357          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir
   358          (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir
   359   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
   361   // sysclasspath, java_home, dll_dir
   362   {
   363     char *pslash;
   364     os::jvm_path(buf, bufsize);
   366     // Found the full path to libjvm.so.
   367     // Now cut the path to <java_home>/jre if we can.
   368     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
   369     pslash = strrchr(buf, '/');
   370     if (pslash != NULL) {
   371       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
   372     }
   373     Arguments::set_dll_dir(buf);
   375     if (pslash != NULL) {
   376       pslash = strrchr(buf, '/');
   377       if (pslash != NULL) {
   378         *pslash = '\0';          // Get rid of /<arch>.
   379         pslash = strrchr(buf, '/');
   380         if (pslash != NULL) {
   381           *pslash = '\0';        // Get rid of /lib.
   382         }
   383       }
   384     }
   385     Arguments::set_java_home(buf);
   386     set_boot_path('/', ':');
   387   }
   389   // Where to look for native libraries.
   390   //
   391   // Note: Due to a legacy implementation, most of the library path
   392   // is set in the launcher. This was to accomodate linking restrictions
   393   // on legacy Bsd implementations (which are no longer supported).
   394   // Eventually, all the library path setting will be done here.
   395   //
   396   // However, to prevent the proliferation of improperly built native
   397   // libraries, the new path component /usr/java/packages is added here.
   398   // Eventually, all the library path setting will be done here.
   399   {
   400     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
   401     // should always exist (until the legacy problem cited above is
   402     // addressed).
   403     const char *v = ::getenv("LD_LIBRARY_PATH");
   404     const char *v_colon = ":";
   405     if (v == NULL) { v = ""; v_colon = ""; }
   406     // That's +1 for the colon and +1 for the trailing '\0'.
   407     char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
   408                                                      strlen(v) + 1 +
   409                                                      sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
   410                                                      mtInternal);
   411     sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
   412     Arguments::set_library_path(ld_library_path);
   413     FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);
   414   }
   416   // Extensions directories.
   417   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
   418   Arguments::set_ext_dirs(buf);
   420   // Endorsed standards default directory.
   421   sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
   422   Arguments::set_endorsed_dirs(buf);
   424   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
   426 #else // __APPLE__
   428 #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
   429 #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
   431   const char *user_home_dir = get_home();
   432   // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
   433   size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
   434     sizeof(SYS_EXTENSIONS_DIRS);
   436   // Buffer that fits several sprintfs.
   437   // Note that the space for the colon and the trailing null are provided
   438   // by the nulls included by the sizeof operator.
   439   const size_t bufsize =
   440     MAX3((size_t)MAXPATHLEN,  // for dll_dir & friends.
   441          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size, // extensions dir
   442          (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir
   443   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
   445   // sysclasspath, java_home, dll_dir
   446   {
   447     char *pslash;
   448     os::jvm_path(buf, bufsize);
   450     // Found the full path to libjvm.so.
   451     // Now cut the path to <java_home>/jre if we can.
   452     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
   453     pslash = strrchr(buf, '/');
   454     if (pslash != NULL) {
   455       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
   456     }
   457     Arguments::set_dll_dir(buf);
   459     if (pslash != NULL) {
   460       pslash = strrchr(buf, '/');
   461       if (pslash != NULL) {
   462         *pslash = '\0';          // Get rid of /lib.
   463       }
   464     }
   465     Arguments::set_java_home(buf);
   466     set_boot_path('/', ':');
   467   }
   469   // Where to look for native libraries.
   470   //
   471   // Note: Due to a legacy implementation, most of the library path
   472   // is set in the launcher. This was to accomodate linking restrictions
   473   // on legacy Bsd implementations (which are no longer supported).
   474   // Eventually, all the library path setting will be done here.
   475   //
   476   // However, to prevent the proliferation of improperly built native
   477   // libraries, the new path component /usr/java/packages is added here.
   478   // Eventually, all the library path setting will be done here.
   479   {
   480     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
   481     // should always exist (until the legacy problem cited above is
   482     // addressed).
   483     // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code
   484     // can specify a directory inside an app wrapper
   485     const char *l = ::getenv("JAVA_LIBRARY_PATH");
   486     const char *l_colon = ":";
   487     if (l == NULL) { l = ""; l_colon = ""; }
   489     const char *v = ::getenv("DYLD_LIBRARY_PATH");
   490     const char *v_colon = ":";
   491     if (v == NULL) { v = ""; v_colon = ""; }
   493     // Apple's Java6 has "." at the beginning of java.library.path.
   494     // OpenJDK on Windows has "." at the end of java.library.path.
   495     // OpenJDK on Linux and Solaris don't have "." in java.library.path
   496     // at all. To ease the transition from Apple's Java6 to OpenJDK7,
   497     // "." is appended to the end of java.library.path. Yes, this
   498     // could cause a change in behavior, but Apple's Java6 behavior
   499     // can be achieved by putting "." at the beginning of the
   500     // JAVA_LIBRARY_PATH environment variable.
   501     char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
   502                                                      strlen(v) + 1 + strlen(l) + 1 +
   503                                                      system_ext_size + 3,
   504                                                      mtInternal);
   505     sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",
   506             v, v_colon, l, l_colon, user_home_dir);
   507     Arguments::set_library_path(ld_library_path);
   508     FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);
   509   }
   511   // Extensions directories.
   512   //
   513   // Note that the space for the colon and the trailing null are provided
   514   // by the nulls included by the sizeof operator (so actually one byte more
   515   // than necessary is allocated).
   516   sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,
   517           user_home_dir, Arguments::get_java_home());
   518   Arguments::set_ext_dirs(buf);
   520   // Endorsed standards default directory.
   521   sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
   522   Arguments::set_endorsed_dirs(buf);
   524   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
   526 #undef SYS_EXTENSIONS_DIR
   527 #undef SYS_EXTENSIONS_DIRS
   529 #endif // __APPLE__
   531 #undef SYS_EXT_DIR
   532 #undef EXTENSIONS_DIR
   533 #undef ENDORSED_DIR
   534 }
   536 ////////////////////////////////////////////////////////////////////////////////
   537 // breakpoint support
   539 void os::breakpoint() {
   540   BREAKPOINT;
   541 }
   543 extern "C" void breakpoint() {
   544   // use debugger to set breakpoint here
   545 }
   547 ////////////////////////////////////////////////////////////////////////////////
   548 // signal support
   550 debug_only(static bool signal_sets_initialized = false);
   551 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
   553 bool os::Bsd::is_sig_ignored(int sig) {
   554       struct sigaction oact;
   555       sigaction(sig, (struct sigaction*)NULL, &oact);
   556       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
   557                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
   558       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
   559            return true;
   560       else
   561            return false;
   562 }
   564 void os::Bsd::signal_sets_init() {
   565   // Should also have an assertion stating we are still single-threaded.
   566   assert(!signal_sets_initialized, "Already initialized");
   567   // Fill in signals that are necessarily unblocked for all threads in
   568   // the VM. Currently, we unblock the following signals:
   569   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
   570   //                         by -Xrs (=ReduceSignalUsage));
   571   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
   572   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
   573   // the dispositions or masks wrt these signals.
   574   // Programs embedding the VM that want to use the above signals for their
   575   // own purposes must, at this time, use the "-Xrs" option to prevent
   576   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
   577   // (See bug 4345157, and other related bugs).
   578   // In reality, though, unblocking these signals is really a nop, since
   579   // these signals are not blocked by default.
   580   sigemptyset(&unblocked_sigs);
   581   sigemptyset(&allowdebug_blocked_sigs);
   582   sigaddset(&unblocked_sigs, SIGILL);
   583   sigaddset(&unblocked_sigs, SIGSEGV);
   584   sigaddset(&unblocked_sigs, SIGBUS);
   585   sigaddset(&unblocked_sigs, SIGFPE);
   586   sigaddset(&unblocked_sigs, SR_signum);
   588   if (!ReduceSignalUsage) {
   589    if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
   590       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
   591       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
   592    }
   593    if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
   594       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
   595       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
   596    }
   597    if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
   598       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
   599       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
   600    }
   601   }
   602   // Fill in signals that are blocked by all but the VM thread.
   603   sigemptyset(&vm_sigs);
   604   if (!ReduceSignalUsage)
   605     sigaddset(&vm_sigs, BREAK_SIGNAL);
   606   debug_only(signal_sets_initialized = true);
   608 }
   610 // These are signals that are unblocked while a thread is running Java.
   611 // (For some reason, they get blocked by default.)
   612 sigset_t* os::Bsd::unblocked_signals() {
   613   assert(signal_sets_initialized, "Not initialized");
   614   return &unblocked_sigs;
   615 }
   617 // These are the signals that are blocked while a (non-VM) thread is
   618 // running Java. Only the VM thread handles these signals.
   619 sigset_t* os::Bsd::vm_signals() {
   620   assert(signal_sets_initialized, "Not initialized");
   621   return &vm_sigs;
   622 }
   624 // These are signals that are blocked during cond_wait to allow debugger in
   625 sigset_t* os::Bsd::allowdebug_blocked_signals() {
   626   assert(signal_sets_initialized, "Not initialized");
   627   return &allowdebug_blocked_sigs;
   628 }
   630 void os::Bsd::hotspot_sigmask(Thread* thread) {
   632   //Save caller's signal mask before setting VM signal mask
   633   sigset_t caller_sigmask;
   634   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
   636   OSThread* osthread = thread->osthread();
   637   osthread->set_caller_sigmask(caller_sigmask);
   639   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
   641   if (!ReduceSignalUsage) {
   642     if (thread->is_VM_thread()) {
   643       // Only the VM thread handles BREAK_SIGNAL ...
   644       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
   645     } else {
   646       // ... all other threads block BREAK_SIGNAL
   647       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
   648     }
   649   }
   650 }
   653 //////////////////////////////////////////////////////////////////////////////
   654 // create new thread
   656 // check if it's safe to start a new thread
   657 static bool _thread_safety_check(Thread* thread) {
   658   return true;
   659 }
   661 #ifdef __APPLE__
   662 // library handle for calling objc_registerThreadWithCollector()
   663 // without static linking to the libobjc library
   664 #define OBJC_LIB "/usr/lib/libobjc.dylib"
   665 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
   666 typedef void (*objc_registerThreadWithCollector_t)();
   667 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
   668 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
   669 #endif
   671 #ifdef __APPLE__
   672 static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {
   673   // Additional thread_id used to correlate threads in SA
   674   thread_identifier_info_data_t     m_ident_info;
   675   mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
   677   thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,
   678               (thread_info_t) &m_ident_info, &count);
   680   return m_ident_info.thread_id;
   681 }
   682 #endif
   684 // Thread start routine for all newly created threads
   685 static void *java_start(Thread *thread) {
   686   // Try to randomize the cache line index of hot stack frames.
   687   // This helps when threads of the same stack traces evict each other's
   688   // cache lines. The threads can be either from the same JVM instance, or
   689   // from different JVM instances. The benefit is especially true for
   690   // processors with hyperthreading technology.
   691   static int counter = 0;
   692   int pid = os::current_process_id();
   693   alloca(((pid ^ counter++) & 7) * 128);
   695   ThreadLocalStorage::set_thread(thread);
   697   OSThread* osthread = thread->osthread();
   698   Monitor* sync = osthread->startThread_lock();
   700   // non floating stack BsdThreads needs extra check, see above
   701   if (!_thread_safety_check(thread)) {
   702     // notify parent thread
   703     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   704     osthread->set_state(ZOMBIE);
   705     sync->notify_all();
   706     return NULL;
   707   }
   709   osthread->set_thread_id(os::Bsd::gettid());
   711 #ifdef __APPLE__
   712   uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
   713   guarantee(unique_thread_id != 0, "unique thread id was not found");
   714   osthread->set_unique_thread_id(unique_thread_id);
   715 #endif
   716   // initialize signal mask for this thread
   717   os::Bsd::hotspot_sigmask(thread);
   719   // initialize floating point control register
   720   os::Bsd::init_thread_fpu_state();
   722 #ifdef __APPLE__
   723   // register thread with objc gc
   724   if (objc_registerThreadWithCollectorFunction != NULL) {
   725     objc_registerThreadWithCollectorFunction();
   726   }
   727 #endif
   729   // handshaking with parent thread
   730   {
   731     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
   733     // notify parent thread
   734     osthread->set_state(INITIALIZED);
   735     sync->notify_all();
   737     // wait until os::start_thread()
   738     while (osthread->get_state() == INITIALIZED) {
   739       sync->wait(Mutex::_no_safepoint_check_flag);
   740     }
   741   }
   743   // call one more level start routine
   744   thread->run();
   746   return 0;
   747 }
   749 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
   750   assert(thread->osthread() == NULL, "caller responsible");
   752   // Allocate the OSThread object
   753   OSThread* osthread = new OSThread(NULL, NULL);
   754   if (osthread == NULL) {
   755     return false;
   756   }
   758   // set the correct thread state
   759   osthread->set_thread_type(thr_type);
   761   // Initial state is ALLOCATED but not INITIALIZED
   762   osthread->set_state(ALLOCATED);
   764   thread->set_osthread(osthread);
   766   // init thread attributes
   767   pthread_attr_t attr;
   768   pthread_attr_init(&attr);
   769   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   771   // stack size
   772   if (os::Bsd::supports_variable_stack_size()) {
   773     // calculate stack size if it's not specified by caller
   774     if (stack_size == 0) {
   775       stack_size = os::Bsd::default_stack_size(thr_type);
   777       switch (thr_type) {
   778       case os::java_thread:
   779         // Java threads use ThreadStackSize which default value can be
   780         // changed with the flag -Xss
   781         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
   782         stack_size = JavaThread::stack_size_at_create();
   783         break;
   784       case os::compiler_thread:
   785         if (CompilerThreadStackSize > 0) {
   786           stack_size = (size_t)(CompilerThreadStackSize * K);
   787           break;
   788         } // else fall through:
   789           // use VMThreadStackSize if CompilerThreadStackSize is not defined
   790       case os::vm_thread:
   791       case os::pgc_thread:
   792       case os::cgc_thread:
   793       case os::watcher_thread:
   794         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
   795         break;
   796       }
   797     }
   799     stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
   800     pthread_attr_setstacksize(&attr, stack_size);
   801   } else {
   802     // let pthread_create() pick the default value.
   803   }
   805   ThreadState state;
   807   {
   808     pthread_t tid;
   809     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
   811     pthread_attr_destroy(&attr);
   813     if (ret != 0) {
   814       if (PrintMiscellaneous && (Verbose || WizardMode)) {
   815         perror("pthread_create()");
   816       }
   817       // Need to clean up stuff we've allocated so far
   818       thread->set_osthread(NULL);
   819       delete osthread;
   820       return false;
   821     }
   823     // Store pthread info into the OSThread
   824     osthread->set_pthread_id(tid);
   826     // Wait until child thread is either initialized or aborted
   827     {
   828       Monitor* sync_with_child = osthread->startThread_lock();
   829       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   830       while ((state = osthread->get_state()) == ALLOCATED) {
   831         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
   832       }
   833     }
   835   }
   837   // Aborted due to thread limit being reached
   838   if (state == ZOMBIE) {
   839       thread->set_osthread(NULL);
   840       delete osthread;
   841       return false;
   842   }
   844   // The thread is returned suspended (in state INITIALIZED),
   845   // and is started higher up in the call chain
   846   assert(state == INITIALIZED, "race condition");
   847   return true;
   848 }
   850 /////////////////////////////////////////////////////////////////////////////
   851 // attach existing thread
   853 // bootstrap the main thread
   854 bool os::create_main_thread(JavaThread* thread) {
   855   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
   856   return create_attached_thread(thread);
   857 }
   859 bool os::create_attached_thread(JavaThread* thread) {
   860 #ifdef ASSERT
   861     thread->verify_not_published();
   862 #endif
   864   // Allocate the OSThread object
   865   OSThread* osthread = new OSThread(NULL, NULL);
   867   if (osthread == NULL) {
   868     return false;
   869   }
   871   osthread->set_thread_id(os::Bsd::gettid());
   873   // Store pthread info into the OSThread
   874 #ifdef __APPLE__
   875   uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
   876   guarantee(unique_thread_id != 0, "just checking");
   877   osthread->set_unique_thread_id(unique_thread_id);
   878 #endif
   879   osthread->set_pthread_id(::pthread_self());
   881   // initialize floating point control register
   882   os::Bsd::init_thread_fpu_state();
   884   // Initial thread state is RUNNABLE
   885   osthread->set_state(RUNNABLE);
   887   thread->set_osthread(osthread);
   889   // initialize signal mask for this thread
   890   // and save the caller's signal mask
   891   os::Bsd::hotspot_sigmask(thread);
   893   return true;
   894 }
   896 void os::pd_start_thread(Thread* thread) {
   897   OSThread * osthread = thread->osthread();
   898   assert(osthread->get_state() != INITIALIZED, "just checking");
   899   Monitor* sync_with_child = osthread->startThread_lock();
   900   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
   901   sync_with_child->notify();
   902 }
   904 // Free Bsd resources related to the OSThread
   905 void os::free_thread(OSThread* osthread) {
   906   assert(osthread != NULL, "osthread not set");
   908   if (Thread::current()->osthread() == osthread) {
   909     // Restore caller's signal mask
   910     sigset_t sigmask = osthread->caller_sigmask();
   911     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   912    }
   914   delete osthread;
   915 }
   917 //////////////////////////////////////////////////////////////////////////////
   918 // thread local storage
   920 // Restore the thread pointer if the destructor is called. This is in case
   921 // someone from JNI code sets up a destructor with pthread_key_create to run
   922 // detachCurrentThread on thread death. Unless we restore the thread pointer we
   923 // will hang or crash. When detachCurrentThread is called the key will be set
   924 // to null and we will not be called again. If detachCurrentThread is never
   925 // called we could loop forever depending on the pthread implementation.
   926 static void restore_thread_pointer(void* p) {
   927   Thread* thread = (Thread*) p;
   928   os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread);
   929 }
   931 int os::allocate_thread_local_storage() {
   932   pthread_key_t key;
   933   int rslt = pthread_key_create(&key, restore_thread_pointer);
   934   assert(rslt == 0, "cannot allocate thread local storage");
   935   return (int)key;
   936 }
   938 // Note: This is currently not used by VM, as we don't destroy TLS key
   939 // on VM exit.
   940 void os::free_thread_local_storage(int index) {
   941   int rslt = pthread_key_delete((pthread_key_t)index);
   942   assert(rslt == 0, "invalid index");
   943 }
   945 void os::thread_local_storage_at_put(int index, void* value) {
   946   int rslt = pthread_setspecific((pthread_key_t)index, value);
   947   assert(rslt == 0, "pthread_setspecific failed");
   948 }
   950 extern "C" Thread* get_thread() {
   951   return ThreadLocalStorage::thread();
   952 }
   955 ////////////////////////////////////////////////////////////////////////////////
   956 // time support
   958 // Time since start-up in seconds to a fine granularity.
   959 // Used by VMSelfDestructTimer and the MemProfiler.
   960 double os::elapsedTime() {
   962   return ((double)os::elapsed_counter()) / os::elapsed_frequency();
   963 }
   965 jlong os::elapsed_counter() {
   966   return javaTimeNanos() - initial_time_count;
   967 }
   969 jlong os::elapsed_frequency() {
   970   return NANOSECS_PER_SEC; // nanosecond resolution
   971 }
   973 bool os::supports_vtime() { return true; }
   974 bool os::enable_vtime()   { return false; }
   975 bool os::vtime_enabled()  { return false; }
   977 double os::elapsedVTime() {
   978   // better than nothing, but not much
   979   return elapsedTime();
   980 }
   982 jlong os::javaTimeMillis() {
   983   timeval time;
   984   int status = gettimeofday(&time, NULL);
   985   assert(status != -1, "bsd error");
   986   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   987 }
   989 #ifndef CLOCK_MONOTONIC
   990 #define CLOCK_MONOTONIC (1)
   991 #endif
   993 #ifdef __APPLE__
   994 void os::Bsd::clock_init() {
   995         // XXXDARWIN: Investigate replacement monotonic clock
   996 }
   997 #else
   998 void os::Bsd::clock_init() {
   999   struct timespec res;
  1000   struct timespec tp;
  1001   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
  1002       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
  1003     // yes, monotonic clock is supported
  1004     _clock_gettime = ::clock_gettime;
  1007 #endif
  1010 jlong os::javaTimeNanos() {
  1011   if (Bsd::supports_monotonic_clock()) {
  1012     struct timespec tp;
  1013     int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
  1014     assert(status == 0, "gettime error");
  1015     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
  1016     return result;
  1017   } else {
  1018     timeval time;
  1019     int status = gettimeofday(&time, NULL);
  1020     assert(status != -1, "bsd error");
  1021     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
  1022     return 1000 * usecs;
  1026 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
  1027   if (Bsd::supports_monotonic_clock()) {
  1028     info_ptr->max_value = ALL_64_BITS;
  1030     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
  1031     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
  1032     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
  1033   } else {
  1034     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
  1035     info_ptr->max_value = ALL_64_BITS;
  1037     // gettimeofday is a real time clock so it skips
  1038     info_ptr->may_skip_backward = true;
  1039     info_ptr->may_skip_forward = true;
  1042   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
  1045 // Return the real, user, and system times in seconds from an
  1046 // arbitrary fixed point in the past.
  1047 bool os::getTimesSecs(double* process_real_time,
  1048                       double* process_user_time,
  1049                       double* process_system_time) {
  1050   struct tms ticks;
  1051   clock_t real_ticks = times(&ticks);
  1053   if (real_ticks == (clock_t) (-1)) {
  1054     return false;
  1055   } else {
  1056     double ticks_per_second = (double) clock_tics_per_sec;
  1057     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
  1058     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
  1059     *process_real_time = ((double) real_ticks) / ticks_per_second;
  1061     return true;
  1066 char * os::local_time_string(char *buf, size_t buflen) {
  1067   struct tm t;
  1068   time_t long_time;
  1069   time(&long_time);
  1070   localtime_r(&long_time, &t);
  1071   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  1072                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
  1073                t.tm_hour, t.tm_min, t.tm_sec);
  1074   return buf;
  1077 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
  1078   return localtime_r(clock, res);
  1081 ////////////////////////////////////////////////////////////////////////////////
  1082 // runtime exit support
  1084 // Note: os::shutdown() might be called very early during initialization, or
  1085 // called from signal handler. Before adding something to os::shutdown(), make
  1086 // sure it is async-safe and can handle partially initialized VM.
  1087 void os::shutdown() {
  1089   // allow PerfMemory to attempt cleanup of any persistent resources
  1090   perfMemory_exit();
  1092   // needs to remove object in file system
  1093   AttachListener::abort();
  1095   // flush buffered output, finish log files
  1096   ostream_abort();
  1098   // Check for abort hook
  1099   abort_hook_t abort_hook = Arguments::abort_hook();
  1100   if (abort_hook != NULL) {
  1101     abort_hook();
  1106 // Note: os::abort() might be called very early during initialization, or
  1107 // called from signal handler. Before adding something to os::abort(), make
  1108 // sure it is async-safe and can handle partially initialized VM.
  1109 void os::abort(bool dump_core) {
  1110   os::shutdown();
  1111   if (dump_core) {
  1112 #ifndef PRODUCT
  1113     fdStream out(defaultStream::output_fd());
  1114     out.print_raw("Current thread is ");
  1115     char buf[16];
  1116     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
  1117     out.print_raw_cr(buf);
  1118     out.print_raw_cr("Dumping core ...");
  1119 #endif
  1120     ::abort(); // dump core
  1123   ::exit(1);
  1126 // Die immediately, no exit hook, no abort hook, no cleanup.
  1127 void os::die() {
  1128   // _exit() on BsdThreads only kills current thread
  1129   ::abort();
  1132 // unused on bsd for now.
  1133 void os::set_error_file(const char *logfile) {}
  1136 // This method is a copy of JDK's sysGetLastErrorString
  1137 // from src/solaris/hpi/src/system_md.c
  1139 size_t os::lasterror(char *buf, size_t len) {
  1141   if (errno == 0)  return 0;
  1143   const char *s = ::strerror(errno);
  1144   size_t n = ::strlen(s);
  1145   if (n >= len) {
  1146     n = len - 1;
  1148   ::strncpy(buf, s, n);
  1149   buf[n] = '\0';
  1150   return n;
  1153 // Information of current thread in variety of formats
  1154 pid_t os::Bsd::gettid() {
  1155   int retval = -1;
  1157 #ifdef __APPLE__ //XNU kernel
  1158   // despite the fact mach port is actually not a thread id use it
  1159   // instead of syscall(SYS_thread_selfid) as it certainly fits to u4
  1160   retval = ::pthread_mach_thread_np(::pthread_self());
  1161   guarantee(retval != 0, "just checking");
  1162   return retval;
  1164 #elif __FreeBSD__
  1165   retval = syscall(SYS_thr_self);
  1166 #elif __OpenBSD__
  1167   retval = syscall(SYS_getthrid);
  1168 #elif __NetBSD__
  1169   retval = (pid_t) syscall(SYS__lwp_self);
  1170 #endif
  1172   if (retval == -1) {
  1173     return getpid();
  1177 intx os::current_thread_id() {
  1178 #ifdef __APPLE__
  1179   return (intx)::pthread_mach_thread_np(::pthread_self());
  1180 #else
  1181   return (intx)::pthread_self();
  1182 #endif
  1185 int os::current_process_id() {
  1187   // Under the old bsd thread library, bsd gives each thread
  1188   // its own process id. Because of this each thread will return
  1189   // a different pid if this method were to return the result
  1190   // of getpid(2). Bsd provides no api that returns the pid
  1191   // of the launcher thread for the vm. This implementation
  1192   // returns a unique pid, the pid of the launcher thread
  1193   // that starts the vm 'process'.
  1195   // Under the NPTL, getpid() returns the same pid as the
  1196   // launcher thread rather than a unique pid per thread.
  1197   // Use gettid() if you want the old pre NPTL behaviour.
  1199   // if you are looking for the result of a call to getpid() that
  1200   // returns a unique pid for the calling thread, then look at the
  1201   // OSThread::thread_id() method in osThread_bsd.hpp file
  1203   return (int)(_initial_pid ? _initial_pid : getpid());
  1206 // DLL functions
  1208 #define JNI_LIB_PREFIX "lib"
  1209 #ifdef __APPLE__
  1210 #define JNI_LIB_SUFFIX ".dylib"
  1211 #else
  1212 #define JNI_LIB_SUFFIX ".so"
  1213 #endif
  1215 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1217 // This must be hard coded because it's the system's temporary
  1218 // directory not the java application's temp directory, ala java.io.tmpdir.
  1219 #ifdef __APPLE__
  1220 // macosx has a secure per-user temporary directory
  1221 char temp_path_storage[PATH_MAX];
  1222 const char* os::get_temp_directory() {
  1223   static char *temp_path = NULL;
  1224   if (temp_path == NULL) {
  1225     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
  1226     if (pathSize == 0 || pathSize > PATH_MAX) {
  1227       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
  1229     temp_path = temp_path_storage;
  1231   return temp_path;
  1233 #else /* __APPLE__ */
  1234 const char* os::get_temp_directory() { return "/tmp"; }
  1235 #endif /* __APPLE__ */
  1237 static bool file_exists(const char* filename) {
  1238   struct stat statbuf;
  1239   if (filename == NULL || strlen(filename) == 0) {
  1240     return false;
  1242   return os::stat(filename, &statbuf) == 0;
  1245 bool os::dll_build_name(char* buffer, size_t buflen,
  1246                         const char* pname, const char* fname) {
  1247   bool retval = false;
  1248   // Copied from libhpi
  1249   const size_t pnamelen = pname ? strlen(pname) : 0;
  1251   // Return error on buffer overflow.
  1252   if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
  1253     return retval;
  1256   if (pnamelen == 0) {
  1257     snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
  1258     retval = true;
  1259   } else if (strchr(pname, *os::path_separator()) != NULL) {
  1260     int n;
  1261     char** pelements = split_path(pname, &n);
  1262     if (pelements == NULL) {
  1263       return false;
  1265     for (int i = 0 ; i < n ; i++) {
  1266       // Really shouldn't be NULL, but check can't hurt
  1267       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1268         continue; // skip the empty path values
  1270       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1271           pelements[i], fname);
  1272       if (file_exists(buffer)) {
  1273         retval = true;
  1274         break;
  1277     // release the storage
  1278     for (int i = 0 ; i < n ; i++) {
  1279       if (pelements[i] != NULL) {
  1280         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
  1283     if (pelements != NULL) {
  1284       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
  1286   } else {
  1287     snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
  1288     retval = true;
  1290   return retval;
  1293 // check if addr is inside libjvm.so
  1294 bool os::address_is_in_vm(address addr) {
  1295   static address libjvm_base_addr;
  1296   Dl_info dlinfo;
  1298   if (libjvm_base_addr == NULL) {
  1299     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
  1300       libjvm_base_addr = (address)dlinfo.dli_fbase;
  1302     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
  1305   if (dladdr((void *)addr, &dlinfo) != 0) {
  1306     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
  1309   return false;
  1313 #define MACH_MAXSYMLEN 256
  1315 bool os::dll_address_to_function_name(address addr, char *buf,
  1316                                       int buflen, int *offset) {
  1317   // buf is not optional, but offset is optional
  1318   assert(buf != NULL, "sanity check");
  1320   Dl_info dlinfo;
  1321   char localbuf[MACH_MAXSYMLEN];
  1323   if (dladdr((void*)addr, &dlinfo) != 0) {
  1324     // see if we have a matching symbol
  1325     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
  1326       if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1327         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
  1329       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1330       return true;
  1332     // no matching symbol so try for just file info
  1333     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1334       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1335                           buf, buflen, offset, dlinfo.dli_fname)) {
  1336          return true;
  1340     // Handle non-dynamic manually:
  1341     if (dlinfo.dli_fbase != NULL &&
  1342         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
  1343                         dlinfo.dli_fbase)) {
  1344       if (!Decoder::demangle(localbuf, buf, buflen)) {
  1345         jio_snprintf(buf, buflen, "%s", localbuf);
  1347       return true;
  1350   buf[0] = '\0';
  1351   if (offset != NULL) *offset = -1;
  1352   return false;
  1355 // ported from solaris version
  1356 bool os::dll_address_to_library_name(address addr, char* buf,
  1357                                      int buflen, int* offset) {
  1358   // buf is not optional, but offset is optional
  1359   assert(buf != NULL, "sanity check");
  1361   Dl_info dlinfo;
  1363   if (dladdr((void*)addr, &dlinfo) != 0) {
  1364     if (dlinfo.dli_fname != NULL) {
  1365       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
  1367     if (dlinfo.dli_fbase != NULL && offset != NULL) {
  1368       *offset = addr - (address)dlinfo.dli_fbase;
  1370     return true;
  1373   buf[0] = '\0';
  1374   if (offset) *offset = -1;
  1375   return false;
  1378 // Loads .dll/.so and
  1379 // in case of error it checks if .dll/.so was built for the
  1380 // same architecture as Hotspot is running on
  1382 #ifdef __APPLE__
  1383 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
  1384   void * result= ::dlopen(filename, RTLD_LAZY);
  1385   if (result != NULL) {
  1386     // Successful loading
  1387     return result;
  1390   // Read system error message into ebuf
  1391   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1392   ebuf[ebuflen-1]='\0';
  1394   return NULL;
  1396 #else
  1397 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1399   void * result= ::dlopen(filename, RTLD_LAZY);
  1400   if (result != NULL) {
  1401     // Successful loading
  1402     return result;
  1405   Elf32_Ehdr elf_head;
  1407   // Read system error message into ebuf
  1408   // It may or may not be overwritten below
  1409   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1410   ebuf[ebuflen-1]='\0';
  1411   int diag_msg_max_length=ebuflen-strlen(ebuf);
  1412   char* diag_msg_buf=ebuf+strlen(ebuf);
  1414   if (diag_msg_max_length==0) {
  1415     // No more space in ebuf for additional diagnostics message
  1416     return NULL;
  1420   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
  1422   if (file_descriptor < 0) {
  1423     // Can't open library, report dlerror() message
  1424     return NULL;
  1427   bool failed_to_read_elf_head=
  1428     (sizeof(elf_head)!=
  1429         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
  1431   ::close(file_descriptor);
  1432   if (failed_to_read_elf_head) {
  1433     // file i/o error - report dlerror() msg
  1434     return NULL;
  1437   typedef struct {
  1438     Elf32_Half  code;         // Actual value as defined in elf.h
  1439     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
  1440     char        elf_class;    // 32 or 64 bit
  1441     char        endianess;    // MSB or LSB
  1442     char*       name;         // String representation
  1443   } arch_t;
  1445   #ifndef EM_486
  1446   #define EM_486          6               /* Intel 80486 */
  1447   #endif
  1449   #ifndef EM_MIPS_RS3_LE
  1450   #define EM_MIPS_RS3_LE  10              /* MIPS */
  1451   #endif
  1453   #ifndef EM_PPC64
  1454   #define EM_PPC64        21              /* PowerPC64 */
  1455   #endif
  1457   #ifndef EM_S390
  1458   #define EM_S390         22              /* IBM System/390 */
  1459   #endif
  1461   #ifndef EM_IA_64
  1462   #define EM_IA_64        50              /* HP/Intel IA-64 */
  1463   #endif
  1465   #ifndef EM_X86_64
  1466   #define EM_X86_64       62              /* AMD x86-64 */
  1467   #endif
  1469   static const arch_t arch_array[]={
  1470     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1471     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1472     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
  1473     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
  1474     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1475     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1476     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
  1477     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
  1478     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
  1479     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
  1480     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
  1481     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
  1482     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
  1483     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
  1484     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1485     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1486   };
  1488   #if  (defined IA32)
  1489     static  Elf32_Half running_arch_code=EM_386;
  1490   #elif   (defined AMD64)
  1491     static  Elf32_Half running_arch_code=EM_X86_64;
  1492   #elif  (defined IA64)
  1493     static  Elf32_Half running_arch_code=EM_IA_64;
  1494   #elif  (defined __sparc) && (defined _LP64)
  1495     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1496   #elif  (defined __sparc) && (!defined _LP64)
  1497     static  Elf32_Half running_arch_code=EM_SPARC;
  1498   #elif  (defined __powerpc64__)
  1499     static  Elf32_Half running_arch_code=EM_PPC64;
  1500   #elif  (defined __powerpc__)
  1501     static  Elf32_Half running_arch_code=EM_PPC;
  1502   #elif  (defined ARM)
  1503     static  Elf32_Half running_arch_code=EM_ARM;
  1504   #elif  (defined S390)
  1505     static  Elf32_Half running_arch_code=EM_S390;
  1506   #elif  (defined ALPHA)
  1507     static  Elf32_Half running_arch_code=EM_ALPHA;
  1508   #elif  (defined MIPSEL)
  1509     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1510   #elif  (defined PARISC)
  1511     static  Elf32_Half running_arch_code=EM_PARISC;
  1512   #elif  (defined MIPS)
  1513     static  Elf32_Half running_arch_code=EM_MIPS;
  1514   #elif  (defined M68K)
  1515     static  Elf32_Half running_arch_code=EM_68K;
  1516   #else
  1517     #error Method os::dll_load requires that one of following is defined:\
  1518          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1519   #endif
  1521   // Identify compatability class for VM's architecture and library's architecture
  1522   // Obtain string descriptions for architectures
  1524   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
  1525   int running_arch_index=-1;
  1527   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
  1528     if (running_arch_code == arch_array[i].code) {
  1529       running_arch_index    = i;
  1531     if (lib_arch.code == arch_array[i].code) {
  1532       lib_arch.compat_class = arch_array[i].compat_class;
  1533       lib_arch.name         = arch_array[i].name;
  1537   assert(running_arch_index != -1,
  1538     "Didn't find running architecture code (running_arch_code) in arch_array");
  1539   if (running_arch_index == -1) {
  1540     // Even though running architecture detection failed
  1541     // we may still continue with reporting dlerror() message
  1542     return NULL;
  1545   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
  1546     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
  1547     return NULL;
  1550 #ifndef S390
  1551   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
  1552     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
  1553     return NULL;
  1555 #endif // !S390
  1557   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1558     if ( lib_arch.name!=NULL ) {
  1559       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1560         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1561         lib_arch.name, arch_array[running_arch_index].name);
  1562     } else {
  1563       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1564       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1565         lib_arch.code,
  1566         arch_array[running_arch_index].name);
  1570   return NULL;
  1572 #endif /* !__APPLE__ */
  1574 void* os::get_default_process_handle() {
  1575 #ifdef __APPLE__
  1576   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
  1577   // to avoid finding unexpected symbols on second (or later)
  1578   // loads of a library.
  1579   return (void*)::dlopen(NULL, RTLD_FIRST);
  1580 #else
  1581   return (void*)::dlopen(NULL, RTLD_LAZY);
  1582 #endif
  1585 // XXX: Do we need a lock around this as per Linux?
  1586 void* os::dll_lookup(void* handle, const char* name) {
  1587   return dlsym(handle, name);
  1591 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1592   int fd = ::open(filename, O_RDONLY);
  1593   if (fd == -1) {
  1594      return false;
  1597   char buf[32];
  1598   int bytes;
  1599   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1600     st->print_raw(buf, bytes);
  1603   ::close(fd);
  1605   return true;
  1608 void os::print_dll_info(outputStream *st) {
  1609   st->print_cr("Dynamic libraries:");
  1610 #ifdef RTLD_DI_LINKMAP
  1611   Dl_info dli;
  1612   void *handle;
  1613   Link_map *map;
  1614   Link_map *p;
  1616   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
  1617       dli.dli_fname == NULL) {
  1618     st->print_cr("Error: Cannot print dynamic libraries.");
  1619     return;
  1621   handle = dlopen(dli.dli_fname, RTLD_LAZY);
  1622   if (handle == NULL) {
  1623     st->print_cr("Error: Cannot print dynamic libraries.");
  1624     return;
  1626   dlinfo(handle, RTLD_DI_LINKMAP, &map);
  1627   if (map == NULL) {
  1628     st->print_cr("Error: Cannot print dynamic libraries.");
  1629     return;
  1632   while (map->l_prev != NULL)
  1633     map = map->l_prev;
  1635   while (map != NULL) {
  1636     st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
  1637     map = map->l_next;
  1640   dlclose(handle);
  1641 #elif defined(__APPLE__)
  1642   uint32_t count;
  1643   uint32_t i;
  1645   count = _dyld_image_count();
  1646   for (i = 1; i < count; i++) {
  1647     const char *name = _dyld_get_image_name(i);
  1648     intptr_t slide = _dyld_get_image_vmaddr_slide(i);
  1649     st->print_cr(PTR_FORMAT " \t%s", slide, name);
  1651 #else
  1652   st->print_cr("Error: Cannot print dynamic libraries.");
  1653 #endif
  1656 void os::print_os_info_brief(outputStream* st) {
  1657   st->print("Bsd");
  1659   os::Posix::print_uname_info(st);
  1662 void os::print_os_info(outputStream* st) {
  1663   st->print("OS:");
  1664   st->print("Bsd");
  1666   os::Posix::print_uname_info(st);
  1668   os::Posix::print_rlimit_info(st);
  1670   os::Posix::print_load_average(st);
  1673 void os::pd_print_cpu_info(outputStream* st) {
  1674   // Nothing to do for now.
  1677 void os::print_memory_info(outputStream* st) {
  1679   st->print("Memory:");
  1680   st->print(" %dk page", os::vm_page_size()>>10);
  1682   st->print(", physical " UINT64_FORMAT "k",
  1683             os::physical_memory() >> 10);
  1684   st->print("(" UINT64_FORMAT "k free)",
  1685             os::available_memory() >> 10);
  1686   st->cr();
  1688   // meminfo
  1689   st->print("\n/proc/meminfo:\n");
  1690   _print_ascii_file("/proc/meminfo", st);
  1691   st->cr();
  1694 void os::print_siginfo(outputStream* st, void* siginfo) {
  1695   const siginfo_t* si = (const siginfo_t*)siginfo;
  1697   os::Posix::print_siginfo_brief(st, si);
  1699   if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
  1700       UseSharedSpaces) {
  1701     FileMapInfo* mapinfo = FileMapInfo::current_info();
  1702     if (mapinfo->is_in_shared_space(si->si_addr)) {
  1703       st->print("\n\nError accessing class data sharing archive."   \
  1704                 " Mapped file inaccessible during execution, "      \
  1705                 " possible disk/network problem.");
  1708   st->cr();
  1712 static void print_signal_handler(outputStream* st, int sig,
  1713                                  char* buf, size_t buflen);
  1715 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  1716   st->print_cr("Signal Handlers:");
  1717   print_signal_handler(st, SIGSEGV, buf, buflen);
  1718   print_signal_handler(st, SIGBUS , buf, buflen);
  1719   print_signal_handler(st, SIGFPE , buf, buflen);
  1720   print_signal_handler(st, SIGPIPE, buf, buflen);
  1721   print_signal_handler(st, SIGXFSZ, buf, buflen);
  1722   print_signal_handler(st, SIGILL , buf, buflen);
  1723   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
  1724   print_signal_handler(st, SR_signum, buf, buflen);
  1725   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
  1726   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
  1727   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
  1728   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
  1731 static char saved_jvm_path[MAXPATHLEN] = {0};
  1733 // Find the full path to the current module, libjvm
  1734 void os::jvm_path(char *buf, jint buflen) {
  1735   // Error checking.
  1736   if (buflen < MAXPATHLEN) {
  1737     assert(false, "must use a large-enough buffer");
  1738     buf[0] = '\0';
  1739     return;
  1741   // Lazy resolve the path to current module.
  1742   if (saved_jvm_path[0] != 0) {
  1743     strcpy(buf, saved_jvm_path);
  1744     return;
  1747   char dli_fname[MAXPATHLEN];
  1748   bool ret = dll_address_to_library_name(
  1749                 CAST_FROM_FN_PTR(address, os::jvm_path),
  1750                 dli_fname, sizeof(dli_fname), NULL);
  1751   assert(ret, "cannot locate libjvm");
  1752   char *rp = NULL;
  1753   if (ret && dli_fname[0] != '\0') {
  1754     rp = realpath(dli_fname, buf);
  1756   if (rp == NULL)
  1757     return;
  1759   if (Arguments::created_by_gamma_launcher()) {
  1760     // Support for the gamma launcher.  Typical value for buf is
  1761     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm".  If "/jre/lib/" appears at
  1762     // the right place in the string, then assume we are installed in a JDK and
  1763     // we're done.  Otherwise, check for a JAVA_HOME environment variable and
  1764     // construct a path to the JVM being overridden.
  1766     const char *p = buf + strlen(buf) - 1;
  1767     for (int count = 0; p > buf && count < 5; ++count) {
  1768       for (--p; p > buf && *p != '/'; --p)
  1769         /* empty */ ;
  1772     if (strncmp(p, "/jre/lib/", 9) != 0) {
  1773       // Look for JAVA_HOME in the environment.
  1774       char* java_home_var = ::getenv("JAVA_HOME");
  1775       if (java_home_var != NULL && java_home_var[0] != 0) {
  1776         char* jrelib_p;
  1777         int len;
  1779         // Check the current module name "libjvm"
  1780         p = strrchr(buf, '/');
  1781         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1783         rp = realpath(java_home_var, buf);
  1784         if (rp == NULL)
  1785           return;
  1787         // determine if this is a legacy image or modules image
  1788         // modules image doesn't have "jre" subdirectory
  1789         len = strlen(buf);
  1790         jrelib_p = buf + len;
  1792         // Add the appropriate library subdir
  1793         snprintf(jrelib_p, buflen-len, "/jre/lib");
  1794         if (0 != access(buf, F_OK)) {
  1795           snprintf(jrelib_p, buflen-len, "/lib");
  1798         // Add the appropriate client or server subdir
  1799         len = strlen(buf);
  1800         jrelib_p = buf + len;
  1801         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
  1802         if (0 != access(buf, F_OK)) {
  1803           snprintf(jrelib_p, buflen-len, "");
  1806         // If the path exists within JAVA_HOME, add the JVM library name
  1807         // to complete the path to JVM being overridden.  Otherwise fallback
  1808         // to the path to the current library.
  1809         if (0 == access(buf, F_OK)) {
  1810           // Use current module name "libjvm"
  1811           len = strlen(buf);
  1812           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1813         } else {
  1814           // Fall back to path of current library
  1815           rp = realpath(dli_fname, buf);
  1816           if (rp == NULL)
  1817             return;
  1823   strcpy(saved_jvm_path, buf);
  1826 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  1827   // no prefix required, not even "_"
  1830 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  1831   // no suffix required
  1834 ////////////////////////////////////////////////////////////////////////////////
  1835 // sun.misc.Signal support
  1837 static volatile jint sigint_count = 0;
  1839 static void
  1840 UserHandler(int sig, void *siginfo, void *context) {
  1841   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1842   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1843   // don't want to flood the manager thread with sem_post requests.
  1844   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1845       return;
  1847   // Ctrl-C is pressed during error reporting, likely because the error
  1848   // handler fails to abort. Let VM die immediately.
  1849   if (sig == SIGINT && is_error_reported()) {
  1850      os::die();
  1853   os::signal_notify(sig);
  1856 void* os::user_handler() {
  1857   return CAST_FROM_FN_PTR(void*, UserHandler);
  1860 extern "C" {
  1861   typedef void (*sa_handler_t)(int);
  1862   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  1865 void* os::signal(int signal_number, void* handler) {
  1866   struct sigaction sigAct, oldSigAct;
  1868   sigfillset(&(sigAct.sa_mask));
  1869   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
  1870   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
  1872   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
  1873     // -1 means registration failed
  1874     return (void *)-1;
  1877   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
  1880 void os::signal_raise(int signal_number) {
  1881   ::raise(signal_number);
  1884 /*
  1885  * The following code is moved from os.cpp for making this
  1886  * code platform specific, which it is by its very nature.
  1887  */
  1889 // Will be modified when max signal is changed to be dynamic
  1890 int os::sigexitnum_pd() {
  1891   return NSIG;
  1894 // a counter for each possible signal value
  1895 static volatile jint pending_signals[NSIG+1] = { 0 };
  1897 // Bsd(POSIX) specific hand shaking semaphore.
  1898 #ifdef __APPLE__
  1899 typedef semaphore_t os_semaphore_t;
  1900 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1901 #define SEM_WAIT(sem)           semaphore_wait(sem)
  1902 #define SEM_POST(sem)           semaphore_signal(sem)
  1903 #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1904 #else
  1905 typedef sem_t os_semaphore_t;
  1906 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1907 #define SEM_WAIT(sem)           sem_wait(&sem)
  1908 #define SEM_POST(sem)           sem_post(&sem)
  1909 #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1910 #endif
  1912 class Semaphore : public StackObj {
  1913   public:
  1914     Semaphore();
  1915     ~Semaphore();
  1916     void signal();
  1917     void wait();
  1918     bool trywait();
  1919     bool timedwait(unsigned int sec, int nsec);
  1920   private:
  1921     jlong currenttime() const;
  1922     os_semaphore_t _semaphore;
  1923 };
  1925 Semaphore::Semaphore() : _semaphore(0) {
  1926   SEM_INIT(_semaphore, 0);
  1929 Semaphore::~Semaphore() {
  1930   SEM_DESTROY(_semaphore);
  1933 void Semaphore::signal() {
  1934   SEM_POST(_semaphore);
  1937 void Semaphore::wait() {
  1938   SEM_WAIT(_semaphore);
  1941 jlong Semaphore::currenttime() const {
  1942     struct timeval tv;
  1943     gettimeofday(&tv, NULL);
  1944     return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
  1947 #ifdef __APPLE__
  1948 bool Semaphore::trywait() {
  1949   return timedwait(0, 0);
  1952 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  1953   kern_return_t kr = KERN_ABORTED;
  1954   mach_timespec_t waitspec;
  1955   waitspec.tv_sec = sec;
  1956   waitspec.tv_nsec = nsec;
  1958   jlong starttime = currenttime();
  1960   kr = semaphore_timedwait(_semaphore, waitspec);
  1961   while (kr == KERN_ABORTED) {
  1962     jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
  1964     jlong current = currenttime();
  1965     jlong passedtime = current - starttime;
  1967     if (passedtime >= totalwait) {
  1968       waitspec.tv_sec = 0;
  1969       waitspec.tv_nsec = 0;
  1970     } else {
  1971       jlong waittime = totalwait - (current - starttime);
  1972       waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
  1973       waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
  1976     kr = semaphore_timedwait(_semaphore, waitspec);
  1979   return kr == KERN_SUCCESS;
  1982 #else
  1984 bool Semaphore::trywait() {
  1985   return sem_trywait(&_semaphore) == 0;
  1988 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  1989   struct timespec ts;
  1990   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
  1992   while (1) {
  1993     int result = sem_timedwait(&_semaphore, &ts);
  1994     if (result == 0) {
  1995       return true;
  1996     } else if (errno == EINTR) {
  1997       continue;
  1998     } else if (errno == ETIMEDOUT) {
  1999       return false;
  2000     } else {
  2001       return false;
  2006 #endif // __APPLE__
  2008 static os_semaphore_t sig_sem;
  2009 static Semaphore sr_semaphore;
  2011 void os::signal_init_pd() {
  2012   // Initialize signal structures
  2013   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
  2015   // Initialize signal semaphore
  2016   ::SEM_INIT(sig_sem, 0);
  2019 void os::signal_notify(int sig) {
  2020   Atomic::inc(&pending_signals[sig]);
  2021   ::SEM_POST(sig_sem);
  2024 static int check_pending_signals(bool wait) {
  2025   Atomic::store(0, &sigint_count);
  2026   for (;;) {
  2027     for (int i = 0; i < NSIG + 1; i++) {
  2028       jint n = pending_signals[i];
  2029       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  2030         return i;
  2033     if (!wait) {
  2034       return -1;
  2036     JavaThread *thread = JavaThread::current();
  2037     ThreadBlockInVM tbivm(thread);
  2039     bool threadIsSuspended;
  2040     do {
  2041       thread->set_suspend_equivalent();
  2042       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  2043       ::SEM_WAIT(sig_sem);
  2045       // were we externally suspended while we were waiting?
  2046       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  2047       if (threadIsSuspended) {
  2048         //
  2049         // The semaphore has been incremented, but while we were waiting
  2050         // another thread suspended us. We don't want to continue running
  2051         // while suspended because that would surprise the thread that
  2052         // suspended us.
  2053         //
  2054         ::SEM_POST(sig_sem);
  2056         thread->java_suspend_self();
  2058     } while (threadIsSuspended);
  2062 int os::signal_lookup() {
  2063   return check_pending_signals(false);
  2066 int os::signal_wait() {
  2067   return check_pending_signals(true);
  2070 ////////////////////////////////////////////////////////////////////////////////
  2071 // Virtual Memory
  2073 int os::vm_page_size() {
  2074   // Seems redundant as all get out
  2075   assert(os::Bsd::page_size() != -1, "must call os::init");
  2076   return os::Bsd::page_size();
  2079 // Solaris allocates memory by pages.
  2080 int os::vm_allocation_granularity() {
  2081   assert(os::Bsd::page_size() != -1, "must call os::init");
  2082   return os::Bsd::page_size();
  2085 // Rationale behind this function:
  2086 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
  2087 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
  2088 //  samples for JITted code. Here we create private executable mapping over the code cache
  2089 //  and then we can use standard (well, almost, as mapping can change) way to provide
  2090 //  info for the reporting script by storing timestamp and location of symbol
  2091 void bsd_wrap_code(char* base, size_t size) {
  2092   static volatile jint cnt = 0;
  2094   if (!UseOprofile) {
  2095     return;
  2098   char buf[PATH_MAX + 1];
  2099   int num = Atomic::add(1, &cnt);
  2101   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
  2102            os::get_temp_directory(), os::current_process_id(), num);
  2103   unlink(buf);
  2105   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
  2107   if (fd != -1) {
  2108     off_t rv = ::lseek(fd, size-2, SEEK_SET);
  2109     if (rv != (off_t)-1) {
  2110       if (::write(fd, "", 1) == 1) {
  2111         mmap(base, size,
  2112              PROT_READ|PROT_WRITE|PROT_EXEC,
  2113              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
  2116     ::close(fd);
  2117     unlink(buf);
  2121 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
  2122                                     int err) {
  2123   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
  2124           ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
  2125           strerror(err), err);
  2128 // NOTE: Bsd kernel does not really reserve the pages for us.
  2129 //       All it does is to check if there are enough free pages
  2130 //       left at the time of mmap(). This could be a potential
  2131 //       problem.
  2132 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
  2133   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
  2134 #ifdef __OpenBSD__
  2135   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2136   if (::mprotect(addr, size, prot) == 0) {
  2137     return true;
  2139 #else
  2140   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2141                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2142   if (res != (uintptr_t) MAP_FAILED) {
  2143     return true;
  2145 #endif
  2147   // Warn about any commit errors we see in non-product builds just
  2148   // in case mmap() doesn't work as described on the man page.
  2149   NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
  2151   return false;
  2154 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2155                        bool exec) {
  2156   // alignment_hint is ignored on this OS
  2157   return pd_commit_memory(addr, size, exec);
  2160 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
  2161                                   const char* mesg) {
  2162   assert(mesg != NULL, "mesg must be specified");
  2163   if (!pd_commit_memory(addr, size, exec)) {
  2164     // add extra info in product mode for vm_exit_out_of_memory():
  2165     PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
  2166     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
  2170 void os::pd_commit_memory_or_exit(char* addr, size_t size,
  2171                                   size_t alignment_hint, bool exec,
  2172                                   const char* mesg) {
  2173   // alignment_hint is ignored on this OS
  2174   pd_commit_memory_or_exit(addr, size, exec, mesg);
  2177 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2180 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2181   ::madvise(addr, bytes, MADV_DONTNEED);
  2184 void os::numa_make_global(char *addr, size_t bytes) {
  2187 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
  2190 bool os::numa_topology_changed()   { return false; }
  2192 size_t os::numa_get_groups_num() {
  2193   return 1;
  2196 int os::numa_get_group_id() {
  2197   return 0;
  2200 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2201   if (size > 0) {
  2202     ids[0] = 0;
  2203     return 1;
  2205   return 0;
  2208 bool os::get_page_info(char *start, page_info* info) {
  2209   return false;
  2212 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2213   return end;
  2217 bool os::pd_uncommit_memory(char* addr, size_t size) {
  2218 #ifdef __OpenBSD__
  2219   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2220   return ::mprotect(addr, size, PROT_NONE) == 0;
  2221 #else
  2222   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2223                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2224   return res  != (uintptr_t) MAP_FAILED;
  2225 #endif
  2228 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2229   return os::commit_memory(addr, size, !ExecMem);
  2232 // If this is a growable mapping, remove the guard pages entirely by
  2233 // munmap()ping them.  If not, just call uncommit_memory().
  2234 bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2235   return os::uncommit_memory(addr, size);
  2238 static address _highest_vm_reserved_address = NULL;
  2240 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
  2241 // at 'requested_addr'. If there are existing memory mappings at the same
  2242 // location, however, they will be overwritten. If 'fixed' is false,
  2243 // 'requested_addr' is only treated as a hint, the return value may or
  2244 // may not start from the requested address. Unlike Bsd mmap(), this
  2245 // function returns NULL to indicate failure.
  2246 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
  2247   char * addr;
  2248   int flags;
  2250   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
  2251   if (fixed) {
  2252     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
  2253     flags |= MAP_FIXED;
  2256   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
  2257   // touch an uncommitted page. Otherwise, the read/write might
  2258   // succeed if we have enough swap space to back the physical page.
  2259   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
  2260                        flags, -1, 0);
  2262   if (addr != MAP_FAILED) {
  2263     // anon_mmap() should only get called during VM initialization,
  2264     // don't need lock (actually we can skip locking even it can be called
  2265     // from multiple threads, because _highest_vm_reserved_address is just a
  2266     // hint about the upper limit of non-stack memory regions.)
  2267     if ((address)addr + bytes > _highest_vm_reserved_address) {
  2268       _highest_vm_reserved_address = (address)addr + bytes;
  2272   return addr == MAP_FAILED ? NULL : addr;
  2275 // Don't update _highest_vm_reserved_address, because there might be memory
  2276 // regions above addr + size. If so, releasing a memory region only creates
  2277 // a hole in the address space, it doesn't help prevent heap-stack collision.
  2278 //
  2279 static int anon_munmap(char * addr, size_t size) {
  2280   return ::munmap(addr, size) == 0;
  2283 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2284                          size_t alignment_hint) {
  2285   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2288 bool os::pd_release_memory(char* addr, size_t size) {
  2289   return anon_munmap(addr, size);
  2292 static bool bsd_mprotect(char* addr, size_t size, int prot) {
  2293   // Bsd wants the mprotect address argument to be page aligned.
  2294   char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
  2296   // According to SUSv3, mprotect() should only be used with mappings
  2297   // established by mmap(), and mmap() always maps whole pages. Unaligned
  2298   // 'addr' likely indicates problem in the VM (e.g. trying to change
  2299   // protection of malloc'ed or statically allocated memory). Check the
  2300   // caller if you hit this assert.
  2301   assert(addr == bottom, "sanity check");
  2303   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
  2304   return ::mprotect(bottom, size, prot) == 0;
  2307 // Set protections specified
  2308 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  2309                         bool is_committed) {
  2310   unsigned int p = 0;
  2311   switch (prot) {
  2312   case MEM_PROT_NONE: p = PROT_NONE; break;
  2313   case MEM_PROT_READ: p = PROT_READ; break;
  2314   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
  2315   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
  2316   default:
  2317     ShouldNotReachHere();
  2319   // is_committed is unused.
  2320   return bsd_mprotect(addr, bytes, p);
  2323 bool os::guard_memory(char* addr, size_t size) {
  2324   return bsd_mprotect(addr, size, PROT_NONE);
  2327 bool os::unguard_memory(char* addr, size_t size) {
  2328   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
  2331 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
  2332   return false;
  2335 // Large page support
  2337 static size_t _large_page_size = 0;
  2339 void os::large_page_init() {
  2343 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
  2344   fatal("This code is not used or maintained.");
  2346   // "exec" is passed in but not used.  Creating the shared image for
  2347   // the code cache doesn't have an SHM_X executable permission to check.
  2348   assert(UseLargePages && UseSHM, "only for SHM large pages");
  2350   key_t key = IPC_PRIVATE;
  2351   char *addr;
  2353   bool warn_on_failure = UseLargePages &&
  2354                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2355                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2356                         );
  2357   char msg[128];
  2359   // Create a large shared memory region to attach to based on size.
  2360   // Currently, size is the total size of the heap
  2361   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2362   if (shmid == -1) {
  2363      // Possible reasons for shmget failure:
  2364      // 1. shmmax is too small for Java heap.
  2365      //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2366      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2367      // 2. not enough large page memory.
  2368      //    > check available large pages: cat /proc/meminfo
  2369      //    > increase amount of large pages:
  2370      //          echo new_value > /proc/sys/vm/nr_hugepages
  2371      //      Note 1: different Bsd may use different name for this property,
  2372      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2373      //      Note 2: it's possible there's enough physical memory available but
  2374      //            they are so fragmented after a long run that they can't
  2375      //            coalesce into large pages. Try to reserve large pages when
  2376      //            the system is still "fresh".
  2377      if (warn_on_failure) {
  2378        jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
  2379        warning(msg);
  2381      return NULL;
  2384   // attach to the region
  2385   addr = (char*)shmat(shmid, req_addr, 0);
  2386   int err = errno;
  2388   // Remove shmid. If shmat() is successful, the actual shared memory segment
  2389   // will be deleted when it's detached by shmdt() or when the process
  2390   // terminates. If shmat() is not successful this will remove the shared
  2391   // segment immediately.
  2392   shmctl(shmid, IPC_RMID, NULL);
  2394   if ((intptr_t)addr == -1) {
  2395      if (warn_on_failure) {
  2396        jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
  2397        warning(msg);
  2399      return NULL;
  2402   // The memory is committed
  2403   MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
  2405   return addr;
  2408 bool os::release_memory_special(char* base, size_t bytes) {
  2409   MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
  2410   // detaching the SHM segment will also delete it, see reserve_memory_special()
  2411   int rslt = shmdt(base);
  2412   if (rslt == 0) {
  2413     tkr.record((address)base, bytes);
  2414     return true;
  2415   } else {
  2416     tkr.discard();
  2417     return false;
  2422 size_t os::large_page_size() {
  2423   return _large_page_size;
  2426 // HugeTLBFS allows application to commit large page memory on demand;
  2427 // with SysV SHM the entire memory region must be allocated as shared
  2428 // memory.
  2429 bool os::can_commit_large_page_memory() {
  2430   return UseHugeTLBFS;
  2433 bool os::can_execute_large_page_memory() {
  2434   return UseHugeTLBFS;
  2437 // Reserve memory at an arbitrary address, only if that area is
  2438 // available (and not reserved for something else).
  2440 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2441   const int max_tries = 10;
  2442   char* base[max_tries];
  2443   size_t size[max_tries];
  2444   const size_t gap = 0x000000;
  2446   // Assert only that the size is a multiple of the page size, since
  2447   // that's all that mmap requires, and since that's all we really know
  2448   // about at this low abstraction level.  If we need higher alignment,
  2449   // we can either pass an alignment to this method or verify alignment
  2450   // in one of the methods further up the call chain.  See bug 5044738.
  2451   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
  2453   // Repeatedly allocate blocks until the block is allocated at the
  2454   // right spot. Give up after max_tries. Note that reserve_memory() will
  2455   // automatically update _highest_vm_reserved_address if the call is
  2456   // successful. The variable tracks the highest memory address every reserved
  2457   // by JVM. It is used to detect heap-stack collision if running with
  2458   // fixed-stack BsdThreads. Because here we may attempt to reserve more
  2459   // space than needed, it could confuse the collision detecting code. To
  2460   // solve the problem, save current _highest_vm_reserved_address and
  2461   // calculate the correct value before return.
  2462   address old_highest = _highest_vm_reserved_address;
  2464   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2465   // if kernel honors the hint then we can return immediately.
  2466   char * addr = anon_mmap(requested_addr, bytes, false);
  2467   if (addr == requested_addr) {
  2468      return requested_addr;
  2471   if (addr != NULL) {
  2472      // mmap() is successful but it fails to reserve at the requested address
  2473      anon_munmap(addr, bytes);
  2476   int i;
  2477   for (i = 0; i < max_tries; ++i) {
  2478     base[i] = reserve_memory(bytes);
  2480     if (base[i] != NULL) {
  2481       // Is this the block we wanted?
  2482       if (base[i] == requested_addr) {
  2483         size[i] = bytes;
  2484         break;
  2487       // Does this overlap the block we wanted? Give back the overlapped
  2488       // parts and try again.
  2490       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
  2491       if (top_overlap >= 0 && top_overlap < bytes) {
  2492         unmap_memory(base[i], top_overlap);
  2493         base[i] += top_overlap;
  2494         size[i] = bytes - top_overlap;
  2495       } else {
  2496         size_t bottom_overlap = base[i] + bytes - requested_addr;
  2497         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
  2498           unmap_memory(requested_addr, bottom_overlap);
  2499           size[i] = bytes - bottom_overlap;
  2500         } else {
  2501           size[i] = bytes;
  2507   // Give back the unused reserved pieces.
  2509   for (int j = 0; j < i; ++j) {
  2510     if (base[j] != NULL) {
  2511       unmap_memory(base[j], size[j]);
  2515   if (i < max_tries) {
  2516     _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
  2517     return requested_addr;
  2518   } else {
  2519     _highest_vm_reserved_address = old_highest;
  2520     return NULL;
  2524 size_t os::read(int fd, void *buf, unsigned int nBytes) {
  2525   RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
  2528 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
  2529 // Solaris uses poll(), bsd uses park().
  2530 // Poll() is likely a better choice, assuming that Thread.interrupt()
  2531 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
  2532 // SIGSEGV, see 4355769.
  2534 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  2535   assert(thread == Thread::current(),  "thread consistency check");
  2537   ParkEvent * const slp = thread->_SleepEvent ;
  2538   slp->reset() ;
  2539   OrderAccess::fence() ;
  2541   if (interruptible) {
  2542     jlong prevtime = javaTimeNanos();
  2544     for (;;) {
  2545       if (os::is_interrupted(thread, true)) {
  2546         return OS_INTRPT;
  2549       jlong newtime = javaTimeNanos();
  2551       if (newtime - prevtime < 0) {
  2552         // time moving backwards, should only happen if no monotonic clock
  2553         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2554         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2555       } else {
  2556         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2559       if(millis <= 0) {
  2560         return OS_OK;
  2563       prevtime = newtime;
  2566         assert(thread->is_Java_thread(), "sanity check");
  2567         JavaThread *jt = (JavaThread *) thread;
  2568         ThreadBlockInVM tbivm(jt);
  2569         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
  2571         jt->set_suspend_equivalent();
  2572         // cleared by handle_special_suspend_equivalent_condition() or
  2573         // java_suspend_self() via check_and_wait_while_suspended()
  2575         slp->park(millis);
  2577         // were we externally suspended while we were waiting?
  2578         jt->check_and_wait_while_suspended();
  2581   } else {
  2582     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  2583     jlong prevtime = javaTimeNanos();
  2585     for (;;) {
  2586       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
  2587       // the 1st iteration ...
  2588       jlong newtime = javaTimeNanos();
  2590       if (newtime - prevtime < 0) {
  2591         // time moving backwards, should only happen if no monotonic clock
  2592         // not a guarantee() because JVM should not abort on kernel/glibc bugs
  2593         assert(!Bsd::supports_monotonic_clock(), "time moving backwards");
  2594       } else {
  2595         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
  2598       if(millis <= 0) break ;
  2600       prevtime = newtime;
  2601       slp->park(millis);
  2603     return OS_OK ;
  2607 void os::naked_short_sleep(jlong ms) {
  2608   struct timespec req;
  2610   assert(ms < 1000, "Un-interruptable sleep, short time use only");
  2611   req.tv_sec = 0;
  2612   if (ms > 0) {
  2613     req.tv_nsec = (ms % 1000) * 1000000;
  2615   else {
  2616     req.tv_nsec = 1;
  2619   nanosleep(&req, NULL);
  2621   return;
  2624 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  2625 void os::infinite_sleep() {
  2626   while (true) {    // sleep forever ...
  2627     ::sleep(100);   // ... 100 seconds at a time
  2631 // Used to convert frequent JVM_Yield() to nops
  2632 bool os::dont_yield() {
  2633   return DontYieldALot;
  2636 void os::yield() {
  2637   sched_yield();
  2640 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
  2642 void os::yield_all(int attempts) {
  2643   // Yields to all threads, including threads with lower priorities
  2644   // Threads on Bsd are all with same priority. The Solaris style
  2645   // os::yield_all() with nanosleep(1ms) is not necessary.
  2646   sched_yield();
  2649 // Called from the tight loops to possibly influence time-sharing heuristics
  2650 void os::loop_breaker(int attempts) {
  2651   os::yield_all(attempts);
  2654 ////////////////////////////////////////////////////////////////////////////////
  2655 // thread priority support
  2657 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
  2658 // only supports dynamic priority, static priority must be zero. For real-time
  2659 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
  2660 // However, for large multi-threaded applications, SCHED_RR is not only slower
  2661 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
  2662 // of 5 runs - Sep 2005).
  2663 //
  2664 // The following code actually changes the niceness of kernel-thread/LWP. It
  2665 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
  2666 // not the entire user process, and user level threads are 1:1 mapped to kernel
  2667 // threads. It has always been the case, but could change in the future. For
  2668 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
  2669 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
  2671 #if !defined(__APPLE__)
  2672 int os::java_to_os_priority[CriticalPriority + 1] = {
  2673   19,              // 0 Entry should never be used
  2675    0,              // 1 MinPriority
  2676    3,              // 2
  2677    6,              // 3
  2679   10,              // 4
  2680   15,              // 5 NormPriority
  2681   18,              // 6
  2683   21,              // 7
  2684   25,              // 8
  2685   28,              // 9 NearMaxPriority
  2687   31,              // 10 MaxPriority
  2689   31               // 11 CriticalPriority
  2690 };
  2691 #else
  2692 /* Using Mach high-level priority assignments */
  2693 int os::java_to_os_priority[CriticalPriority + 1] = {
  2694    0,              // 0 Entry should never be used (MINPRI_USER)
  2696   27,              // 1 MinPriority
  2697   28,              // 2
  2698   29,              // 3
  2700   30,              // 4
  2701   31,              // 5 NormPriority (BASEPRI_DEFAULT)
  2702   32,              // 6
  2704   33,              // 7
  2705   34,              // 8
  2706   35,              // 9 NearMaxPriority
  2708   36,              // 10 MaxPriority
  2710   36               // 11 CriticalPriority
  2711 };
  2712 #endif
  2714 static int prio_init() {
  2715   if (ThreadPriorityPolicy == 1) {
  2716     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
  2717     // if effective uid is not root. Perhaps, a more elegant way of doing
  2718     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
  2719     if (geteuid() != 0) {
  2720       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
  2721         warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
  2723       ThreadPriorityPolicy = 0;
  2726   if (UseCriticalJavaThreadPriority) {
  2727     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
  2729   return 0;
  2732 OSReturn os::set_native_priority(Thread* thread, int newpri) {
  2733   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
  2735 #ifdef __OpenBSD__
  2736   // OpenBSD pthread_setprio starves low priority threads
  2737   return OS_OK;
  2738 #elif defined(__FreeBSD__)
  2739   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
  2740 #elif defined(__APPLE__) || defined(__NetBSD__)
  2741   struct sched_param sp;
  2742   int policy;
  2743   pthread_t self = pthread_self();
  2745   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2746     return OS_ERR;
  2748   sp.sched_priority = newpri;
  2749   if (pthread_setschedparam(self, policy, &sp) != 0)
  2750     return OS_ERR;
  2752   return OS_OK;
  2753 #else
  2754   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2755   return (ret == 0) ? OS_OK : OS_ERR;
  2756 #endif
  2759 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
  2760   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
  2761     *priority_ptr = java_to_os_priority[NormPriority];
  2762     return OS_OK;
  2765   errno = 0;
  2766 #if defined(__OpenBSD__) || defined(__FreeBSD__)
  2767   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
  2768 #elif defined(__APPLE__) || defined(__NetBSD__)
  2769   int policy;
  2770   struct sched_param sp;
  2772   pthread_getschedparam(pthread_self(), &policy, &sp);
  2773   *priority_ptr = sp.sched_priority;
  2774 #else
  2775   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
  2776 #endif
  2777   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
  2780 // Hint to the underlying OS that a task switch would not be good.
  2781 // Void return because it's a hint and can fail.
  2782 void os::hint_no_preempt() {}
  2784 ////////////////////////////////////////////////////////////////////////////////
  2785 // suspend/resume support
  2787 //  the low-level signal-based suspend/resume support is a remnant from the
  2788 //  old VM-suspension that used to be for java-suspension, safepoints etc,
  2789 //  within hotspot. Now there is a single use-case for this:
  2790 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
  2791 //      that runs in the watcher thread.
  2792 //  The remaining code is greatly simplified from the more general suspension
  2793 //  code that used to be used.
  2794 //
  2795 //  The protocol is quite simple:
  2796 //  - suspend:
  2797 //      - sends a signal to the target thread
  2798 //      - polls the suspend state of the osthread using a yield loop
  2799 //      - target thread signal handler (SR_handler) sets suspend state
  2800 //        and blocks in sigsuspend until continued
  2801 //  - resume:
  2802 //      - sets target osthread state to continue
  2803 //      - sends signal to end the sigsuspend loop in the SR_handler
  2804 //
  2805 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2806 //
  2808 static void resume_clear_context(OSThread *osthread) {
  2809   osthread->set_ucontext(NULL);
  2810   osthread->set_siginfo(NULL);
  2813 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2814   osthread->set_ucontext(context);
  2815   osthread->set_siginfo(siginfo);
  2818 //
  2819 // Handler function invoked when a thread's execution is suspended or
  2820 // resumed. We have to be careful that only async-safe functions are
  2821 // called here (Note: most pthread functions are not async safe and
  2822 // should be avoided.)
  2823 //
  2824 // Note: sigwait() is a more natural fit than sigsuspend() from an
  2825 // interface point of view, but sigwait() prevents the signal hander
  2826 // from being run. libpthread would get very confused by not having
  2827 // its signal handlers run and prevents sigwait()'s use with the
  2828 // mutex granting granting signal.
  2829 //
  2830 // Currently only ever called on the VMThread or JavaThread
  2831 //
  2832 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
  2833   // Save and restore errno to avoid confusing native code with EINTR
  2834   // after sigsuspend.
  2835   int old_errno = errno;
  2837   Thread* thread = Thread::current();
  2838   OSThread* osthread = thread->osthread();
  2839   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
  2841   os::SuspendResume::State current = osthread->sr.state();
  2842   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
  2843     suspend_save_context(osthread, siginfo, context);
  2845     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
  2846     os::SuspendResume::State state = osthread->sr.suspended();
  2847     if (state == os::SuspendResume::SR_SUSPENDED) {
  2848       sigset_t suspend_set;  // signals for sigsuspend()
  2850       // get current set of blocked signals and unblock resume signal
  2851       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
  2852       sigdelset(&suspend_set, SR_signum);
  2854       sr_semaphore.signal();
  2855       // wait here until we are resumed
  2856       while (1) {
  2857         sigsuspend(&suspend_set);
  2859         os::SuspendResume::State result = osthread->sr.running();
  2860         if (result == os::SuspendResume::SR_RUNNING) {
  2861           sr_semaphore.signal();
  2862           break;
  2863         } else if (result != os::SuspendResume::SR_SUSPENDED) {
  2864           ShouldNotReachHere();
  2868     } else if (state == os::SuspendResume::SR_RUNNING) {
  2869       // request was cancelled, continue
  2870     } else {
  2871       ShouldNotReachHere();
  2874     resume_clear_context(osthread);
  2875   } else if (current == os::SuspendResume::SR_RUNNING) {
  2876     // request was cancelled, continue
  2877   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
  2878     // ignore
  2879   } else {
  2880     // ignore
  2883   errno = old_errno;
  2887 static int SR_initialize() {
  2888   struct sigaction act;
  2889   char *s;
  2890   /* Get signal number to use for suspend/resume */
  2891   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2892     int sig = ::strtol(s, 0, 10);
  2893     if (sig > 0 || sig < NSIG) {
  2894         SR_signum = sig;
  2898   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2899         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2901   sigemptyset(&SR_sigset);
  2902   sigaddset(&SR_sigset, SR_signum);
  2904   /* Set up signal handler for suspend/resume */
  2905   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2906   act.sa_handler = (void (*)(int)) SR_handler;
  2908   // SR_signum is blocked by default.
  2909   // 4528190 - We also need to block pthread restart signal (32 on all
  2910   // supported Bsd platforms). Note that BsdThreads need to block
  2911   // this signal for all threads to work properly. So we don't have
  2912   // to use hard-coded signal number when setting up the mask.
  2913   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
  2915   if (sigaction(SR_signum, &act, 0) == -1) {
  2916     return -1;
  2919   // Save signal flag
  2920   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
  2921   return 0;
  2924 static int sr_notify(OSThread* osthread) {
  2925   int status = pthread_kill(osthread->pthread_id(), SR_signum);
  2926   assert_status(status == 0, status, "pthread_kill");
  2927   return status;
  2930 // "Randomly" selected value for how long we want to spin
  2931 // before bailing out on suspending a thread, also how often
  2932 // we send a signal to a thread we want to resume
  2933 static const int RANDOMLY_LARGE_INTEGER = 1000000;
  2934 static const int RANDOMLY_LARGE_INTEGER2 = 100;
  2936 // returns true on success and false on error - really an error is fatal
  2937 // but this seems the normal response to library errors
  2938 static bool do_suspend(OSThread* osthread) {
  2939   assert(osthread->sr.is_running(), "thread should be running");
  2940   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
  2942   // mark as suspended and send signal
  2943   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
  2944     // failed to switch, state wasn't running?
  2945     ShouldNotReachHere();
  2946     return false;
  2949   if (sr_notify(osthread) != 0) {
  2950     ShouldNotReachHere();
  2953   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
  2954   while (true) {
  2955     if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  2956       break;
  2957     } else {
  2958       // timeout
  2959       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
  2960       if (cancelled == os::SuspendResume::SR_RUNNING) {
  2961         return false;
  2962       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
  2963         // make sure that we consume the signal on the semaphore as well
  2964         sr_semaphore.wait();
  2965         break;
  2966       } else {
  2967         ShouldNotReachHere();
  2968         return false;
  2973   guarantee(osthread->sr.is_suspended(), "Must be suspended");
  2974   return true;
  2977 static void do_resume(OSThread* osthread) {
  2978   assert(osthread->sr.is_suspended(), "thread should be suspended");
  2979   assert(!sr_semaphore.trywait(), "invalid semaphore state");
  2981   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
  2982     // failed to switch to WAKEUP_REQUEST
  2983     ShouldNotReachHere();
  2984     return;
  2987   while (true) {
  2988     if (sr_notify(osthread) == 0) {
  2989       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  2990         if (osthread->sr.is_running()) {
  2991           return;
  2994     } else {
  2995       ShouldNotReachHere();
  2999   guarantee(osthread->sr.is_running(), "Must be running!");
  3002 ////////////////////////////////////////////////////////////////////////////////
  3003 // interrupt support
  3005 void os::interrupt(Thread* thread) {
  3006   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  3007     "possibility of dangling Thread pointer");
  3009   OSThread* osthread = thread->osthread();
  3011   if (!osthread->interrupted()) {
  3012     osthread->set_interrupted(true);
  3013     // More than one thread can get here with the same value of osthread,
  3014     // resulting in multiple notifications.  We do, however, want the store
  3015     // to interrupted() to be visible to other threads before we execute unpark().
  3016     OrderAccess::fence();
  3017     ParkEvent * const slp = thread->_SleepEvent ;
  3018     if (slp != NULL) slp->unpark() ;
  3021   // For JSR166. Unpark even if interrupt status already was set
  3022   if (thread->is_Java_thread())
  3023     ((JavaThread*)thread)->parker()->unpark();
  3025   ParkEvent * ev = thread->_ParkEvent ;
  3026   if (ev != NULL) ev->unpark() ;
  3030 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  3031   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
  3032     "possibility of dangling Thread pointer");
  3034   OSThread* osthread = thread->osthread();
  3036   bool interrupted = osthread->interrupted();
  3038   if (interrupted && clear_interrupted) {
  3039     osthread->set_interrupted(false);
  3040     // consider thread->_SleepEvent->reset() ... optional optimization
  3043   return interrupted;
  3046 ///////////////////////////////////////////////////////////////////////////////////
  3047 // signal handling (except suspend/resume)
  3049 // This routine may be used by user applications as a "hook" to catch signals.
  3050 // The user-defined signal handler must pass unrecognized signals to this
  3051 // routine, and if it returns true (non-zero), then the signal handler must
  3052 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
  3053 // routine will never retun false (zero), but instead will execute a VM panic
  3054 // routine kill the process.
  3055 //
  3056 // If this routine returns false, it is OK to call it again.  This allows
  3057 // the user-defined signal handler to perform checks either before or after
  3058 // the VM performs its own checks.  Naturally, the user code would be making
  3059 // a serious error if it tried to handle an exception (such as a null check
  3060 // or breakpoint) that the VM was generating for its own correct operation.
  3061 //
  3062 // This routine may recognize any of the following kinds of signals:
  3063 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
  3064 // It should be consulted by handlers for any of those signals.
  3065 //
  3066 // The caller of this routine must pass in the three arguments supplied
  3067 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
  3068 // field of the structure passed to sigaction().  This routine assumes that
  3069 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  3070 //
  3071 // Note that the VM will print warnings if it detects conflicting signal
  3072 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  3073 //
  3074 extern "C" JNIEXPORT int
  3075 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  3076                         void* ucontext, int abort_if_unrecognized);
  3078 void signalHandler(int sig, siginfo_t* info, void* uc) {
  3079   assert(info != NULL && uc != NULL, "it must be old kernel");
  3080   int orig_errno = errno;  // Preserve errno value over signal handler.
  3081   JVM_handle_bsd_signal(sig, info, uc, true);
  3082   errno = orig_errno;
  3086 // This boolean allows users to forward their own non-matching signals
  3087 // to JVM_handle_bsd_signal, harmlessly.
  3088 bool os::Bsd::signal_handlers_are_installed = false;
  3090 // For signal-chaining
  3091 struct sigaction os::Bsd::sigact[MAXSIGNUM];
  3092 unsigned int os::Bsd::sigs = 0;
  3093 bool os::Bsd::libjsig_is_loaded = false;
  3094 typedef struct sigaction *(*get_signal_t)(int);
  3095 get_signal_t os::Bsd::get_signal_action = NULL;
  3097 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
  3098   struct sigaction *actp = NULL;
  3100   if (libjsig_is_loaded) {
  3101     // Retrieve the old signal handler from libjsig
  3102     actp = (*get_signal_action)(sig);
  3104   if (actp == NULL) {
  3105     // Retrieve the preinstalled signal handler from jvm
  3106     actp = get_preinstalled_handler(sig);
  3109   return actp;
  3112 static bool call_chained_handler(struct sigaction *actp, int sig,
  3113                                  siginfo_t *siginfo, void *context) {
  3114   // Call the old signal handler
  3115   if (actp->sa_handler == SIG_DFL) {
  3116     // It's more reasonable to let jvm treat it as an unexpected exception
  3117     // instead of taking the default action.
  3118     return false;
  3119   } else if (actp->sa_handler != SIG_IGN) {
  3120     if ((actp->sa_flags & SA_NODEFER) == 0) {
  3121       // automaticlly block the signal
  3122       sigaddset(&(actp->sa_mask), sig);
  3125     sa_handler_t hand;
  3126     sa_sigaction_t sa;
  3127     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
  3128     // retrieve the chained handler
  3129     if (siginfo_flag_set) {
  3130       sa = actp->sa_sigaction;
  3131     } else {
  3132       hand = actp->sa_handler;
  3135     if ((actp->sa_flags & SA_RESETHAND) != 0) {
  3136       actp->sa_handler = SIG_DFL;
  3139     // try to honor the signal mask
  3140     sigset_t oset;
  3141     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
  3143     // call into the chained handler
  3144     if (siginfo_flag_set) {
  3145       (*sa)(sig, siginfo, context);
  3146     } else {
  3147       (*hand)(sig);
  3150     // restore the signal mask
  3151     pthread_sigmask(SIG_SETMASK, &oset, 0);
  3153   // Tell jvm's signal handler the signal is taken care of.
  3154   return true;
  3157 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
  3158   bool chained = false;
  3159   // signal-chaining
  3160   if (UseSignalChaining) {
  3161     struct sigaction *actp = get_chained_signal_action(sig);
  3162     if (actp != NULL) {
  3163       chained = call_chained_handler(actp, sig, siginfo, context);
  3166   return chained;
  3169 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
  3170   if ((( (unsigned int)1 << sig ) & sigs) != 0) {
  3171     return &sigact[sig];
  3173   return NULL;
  3176 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
  3177   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3178   sigact[sig] = oldAct;
  3179   sigs |= (unsigned int)1 << sig;
  3182 // for diagnostic
  3183 int os::Bsd::sigflags[MAXSIGNUM];
  3185 int os::Bsd::get_our_sigflags(int sig) {
  3186   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3187   return sigflags[sig];
  3190 void os::Bsd::set_our_sigflags(int sig, int flags) {
  3191   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3192   sigflags[sig] = flags;
  3195 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
  3196   // Check for overwrite.
  3197   struct sigaction oldAct;
  3198   sigaction(sig, (struct sigaction*)NULL, &oldAct);
  3200   void* oldhand = oldAct.sa_sigaction
  3201                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
  3202                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
  3203   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
  3204       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
  3205       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
  3206     if (AllowUserSignalHandlers || !set_installed) {
  3207       // Do not overwrite; user takes responsibility to forward to us.
  3208       return;
  3209     } else if (UseSignalChaining) {
  3210       // save the old handler in jvm
  3211       save_preinstalled_handler(sig, oldAct);
  3212       // libjsig also interposes the sigaction() call below and saves the
  3213       // old sigaction on it own.
  3214     } else {
  3215       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
  3216                     "%#lx for signal %d.", (long)oldhand, sig));
  3220   struct sigaction sigAct;
  3221   sigfillset(&(sigAct.sa_mask));
  3222   sigAct.sa_handler = SIG_DFL;
  3223   if (!set_installed) {
  3224     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3225   } else {
  3226     sigAct.sa_sigaction = signalHandler;
  3227     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
  3229 #ifdef __APPLE__
  3230   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
  3231   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
  3232   // if the signal handler declares it will handle it on alternate stack.
  3233   // Notice we only declare we will handle it on alt stack, but we are not
  3234   // actually going to use real alt stack - this is just a workaround.
  3235   // Please see ux_exception.c, method catch_mach_exception_raise for details
  3236   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
  3237   if (sig == SIGSEGV) {
  3238     sigAct.sa_flags |= SA_ONSTACK;
  3240 #endif
  3242   // Save flags, which are set by ours
  3243   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
  3244   sigflags[sig] = sigAct.sa_flags;
  3246   int ret = sigaction(sig, &sigAct, &oldAct);
  3247   assert(ret == 0, "check");
  3249   void* oldhand2  = oldAct.sa_sigaction
  3250                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
  3251                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
  3252   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
  3255 // install signal handlers for signals that HotSpot needs to
  3256 // handle in order to support Java-level exception handling.
  3258 void os::Bsd::install_signal_handlers() {
  3259   if (!signal_handlers_are_installed) {
  3260     signal_handlers_are_installed = true;
  3262     // signal-chaining
  3263     typedef void (*signal_setting_t)();
  3264     signal_setting_t begin_signal_setting = NULL;
  3265     signal_setting_t end_signal_setting = NULL;
  3266     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3267                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3268     if (begin_signal_setting != NULL) {
  3269       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3270                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3271       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3272                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3273       libjsig_is_loaded = true;
  3274       assert(UseSignalChaining, "should enable signal-chaining");
  3276     if (libjsig_is_loaded) {
  3277       // Tell libjsig jvm is setting signal handlers
  3278       (*begin_signal_setting)();
  3281     set_signal_handler(SIGSEGV, true);
  3282     set_signal_handler(SIGPIPE, true);
  3283     set_signal_handler(SIGBUS, true);
  3284     set_signal_handler(SIGILL, true);
  3285     set_signal_handler(SIGFPE, true);
  3286     set_signal_handler(SIGXFSZ, true);
  3288 #if defined(__APPLE__)
  3289     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
  3290     // signals caught and handled by the JVM. To work around this, we reset the mach task
  3291     // signal handler that's placed on our process by CrashReporter. This disables
  3292     // CrashReporter-based reporting.
  3293     //
  3294     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
  3295     // on caught fatal signals.
  3296     //
  3297     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3298     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3299     // exception handling, while leaving the standard BSD signal handlers functional.
  3300     kern_return_t kr;
  3301     kr = task_set_exception_ports(mach_task_self(),
  3302         EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3303         MACH_PORT_NULL,
  3304         EXCEPTION_STATE_IDENTITY,
  3305         MACHINE_THREAD_STATE);
  3307     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3308 #endif
  3310     if (libjsig_is_loaded) {
  3311       // Tell libjsig jvm finishes setting signal handlers
  3312       (*end_signal_setting)();
  3315     // We don't activate signal checker if libjsig is in place, we trust ourselves
  3316     // and if UserSignalHandler is installed all bets are off
  3317     if (CheckJNICalls) {
  3318       if (libjsig_is_loaded) {
  3319         if (PrintJNIResolving) {
  3320           tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
  3322         check_signals = false;
  3324       if (AllowUserSignalHandlers) {
  3325         if (PrintJNIResolving) {
  3326           tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
  3328         check_signals = false;
  3335 /////
  3336 // glibc on Bsd platform uses non-documented flag
  3337 // to indicate, that some special sort of signal
  3338 // trampoline is used.
  3339 // We will never set this flag, and we should
  3340 // ignore this flag in our diagnostic
  3341 #ifdef SIGNIFICANT_SIGNAL_MASK
  3342 #undef SIGNIFICANT_SIGNAL_MASK
  3343 #endif
  3344 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3346 static const char* get_signal_handler_name(address handler,
  3347                                            char* buf, int buflen) {
  3348   int offset;
  3349   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
  3350   if (found) {
  3351     // skip directory names
  3352     const char *p1, *p2;
  3353     p1 = buf;
  3354     size_t len = strlen(os::file_separator());
  3355     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
  3356     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
  3357   } else {
  3358     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
  3360   return buf;
  3363 static void print_signal_handler(outputStream* st, int sig,
  3364                                  char* buf, size_t buflen) {
  3365   struct sigaction sa;
  3367   sigaction(sig, NULL, &sa);
  3369   // See comment for SIGNIFICANT_SIGNAL_MASK define
  3370   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3372   st->print("%s: ", os::exception_name(sig, buf, buflen));
  3374   address handler = (sa.sa_flags & SA_SIGINFO)
  3375     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
  3376     : CAST_FROM_FN_PTR(address, sa.sa_handler);
  3378   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
  3379     st->print("SIG_DFL");
  3380   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
  3381     st->print("SIG_IGN");
  3382   } else {
  3383     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
  3386   st->print(", sa_mask[0]=");
  3387   os::Posix::print_signal_set_short(st, &sa.sa_mask);
  3389   address rh = VMError::get_resetted_sighandler(sig);
  3390   // May be, handler was resetted by VMError?
  3391   if(rh != NULL) {
  3392     handler = rh;
  3393     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
  3396   st->print(", sa_flags=");
  3397   os::Posix::print_sa_flags(st, sa.sa_flags);
  3399   // Check: is it our handler?
  3400   if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3401      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3402     // It is our signal handler
  3403     // check for flags, reset system-used one!
  3404     if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3405       st->print(
  3406                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3407                 os::Bsd::get_our_sigflags(sig));
  3410   st->cr();
  3414 #define DO_SIGNAL_CHECK(sig) \
  3415   if (!sigismember(&check_signal_done, sig)) \
  3416     os::Bsd::check_signal_handler(sig)
  3418 // This method is a periodic task to check for misbehaving JNI applications
  3419 // under CheckJNI, we can add any periodic checks here
  3421 void os::run_periodic_checks() {
  3423   if (check_signals == false) return;
  3425   // SEGV and BUS if overridden could potentially prevent
  3426   // generation of hs*.log in the event of a crash, debugging
  3427   // such a case can be very challenging, so we absolutely
  3428   // check the following for a good measure:
  3429   DO_SIGNAL_CHECK(SIGSEGV);
  3430   DO_SIGNAL_CHECK(SIGILL);
  3431   DO_SIGNAL_CHECK(SIGFPE);
  3432   DO_SIGNAL_CHECK(SIGBUS);
  3433   DO_SIGNAL_CHECK(SIGPIPE);
  3434   DO_SIGNAL_CHECK(SIGXFSZ);
  3437   // ReduceSignalUsage allows the user to override these handlers
  3438   // see comments at the very top and jvm_solaris.h
  3439   if (!ReduceSignalUsage) {
  3440     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
  3441     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
  3442     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
  3443     DO_SIGNAL_CHECK(BREAK_SIGNAL);
  3446   DO_SIGNAL_CHECK(SR_signum);
  3447   DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
  3450 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
  3452 static os_sigaction_t os_sigaction = NULL;
  3454 void os::Bsd::check_signal_handler(int sig) {
  3455   char buf[O_BUFLEN];
  3456   address jvmHandler = NULL;
  3459   struct sigaction act;
  3460   if (os_sigaction == NULL) {
  3461     // only trust the default sigaction, in case it has been interposed
  3462     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
  3463     if (os_sigaction == NULL) return;
  3466   os_sigaction(sig, (struct sigaction*)NULL, &act);
  3469   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
  3471   address thisHandler = (act.sa_flags & SA_SIGINFO)
  3472     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
  3473     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
  3476   switch(sig) {
  3477   case SIGSEGV:
  3478   case SIGBUS:
  3479   case SIGFPE:
  3480   case SIGPIPE:
  3481   case SIGILL:
  3482   case SIGXFSZ:
  3483     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
  3484     break;
  3486   case SHUTDOWN1_SIGNAL:
  3487   case SHUTDOWN2_SIGNAL:
  3488   case SHUTDOWN3_SIGNAL:
  3489   case BREAK_SIGNAL:
  3490     jvmHandler = (address)user_handler();
  3491     break;
  3493   case INTERRUPT_SIGNAL:
  3494     jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
  3495     break;
  3497   default:
  3498     if (sig == SR_signum) {
  3499       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
  3500     } else {
  3501       return;
  3503     break;
  3506   if (thisHandler != jvmHandler) {
  3507     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
  3508     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
  3509     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
  3510     // No need to check this sig any longer
  3511     sigaddset(&check_signal_done, sig);
  3512   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3513     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
  3514     tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig));
  3515     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
  3516     // No need to check this sig any longer
  3517     sigaddset(&check_signal_done, sig);
  3520   // Dump all the signal
  3521   if (sigismember(&check_signal_done, sig)) {
  3522     print_signal_handlers(tty, buf, O_BUFLEN);
  3526 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3528 extern bool signal_name(int signo, char* buf, size_t len);
  3530 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3531   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3532     // signal
  3533     if (!signal_name(exception_code, buf, size)) {
  3534       jio_snprintf(buf, size, "SIG%d", exception_code);
  3536     return buf;
  3537   } else {
  3538     return NULL;
  3542 // this is called _before_ the most of global arguments have been parsed
  3543 void os::init(void) {
  3544   char dummy;   /* used to get a guess on initial stack address */
  3545 //  first_hrtime = gethrtime();
  3547   // With BsdThreads the JavaMain thread pid (primordial thread)
  3548   // is different than the pid of the java launcher thread.
  3549   // So, on Bsd, the launcher thread pid is passed to the VM
  3550   // via the sun.java.launcher.pid property.
  3551   // Use this property instead of getpid() if it was correctly passed.
  3552   // See bug 6351349.
  3553   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
  3555   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
  3557   clock_tics_per_sec = CLK_TCK;
  3559   init_random(1234567);
  3561   ThreadCritical::initialize();
  3563   Bsd::set_page_size(getpagesize());
  3564   if (Bsd::page_size() == -1) {
  3565     fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
  3566                   strerror(errno)));
  3568   init_page_sizes((size_t) Bsd::page_size());
  3570   Bsd::initialize_system_info();
  3572   // main_thread points to the aboriginal thread
  3573   Bsd::_main_thread = pthread_self();
  3575   Bsd::clock_init();
  3576   initial_time_count = javaTimeNanos();
  3578 #ifdef __APPLE__
  3579   // XXXDARWIN
  3580   // Work around the unaligned VM callbacks in hotspot's
  3581   // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
  3582   // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
  3583   // alignment when doing symbol lookup. To work around this, we force early
  3584   // binding of all symbols now, thus binding when alignment is known-good.
  3585   _dyld_bind_fully_image_containing_address((const void *) &os::init);
  3586 #endif
  3589 // To install functions for atexit system call
  3590 extern "C" {
  3591   static void perfMemory_exit_helper() {
  3592     perfMemory_exit();
  3596 // this is called _after_ the global arguments have been parsed
  3597 jint os::init_2(void)
  3599   // Allocate a single page and mark it as readable for safepoint polling
  3600   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3601   guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
  3603   os::set_polling_page( polling_page );
  3605 #ifndef PRODUCT
  3606   if(Verbose && PrintMiscellaneous)
  3607     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3608 #endif
  3610   if (!UseMembar) {
  3611     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3612     guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3613     os::set_memory_serialize_page( mem_serialize_page );
  3615 #ifndef PRODUCT
  3616     if(Verbose && PrintMiscellaneous)
  3617       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3618 #endif
  3621   // initialize suspend/resume support - must do this before signal_sets_init()
  3622   if (SR_initialize() != 0) {
  3623     perror("SR_initialize failed");
  3624     return JNI_ERR;
  3627   Bsd::signal_sets_init();
  3628   Bsd::install_signal_handlers();
  3630   // Check minimum allowable stack size for thread creation and to initialize
  3631   // the java system classes, including StackOverflowError - depends on page
  3632   // size.  Add a page for compiler2 recursion in main thread.
  3633   // Add in 2*BytesPerWord times page size to account for VM stack during
  3634   // class initialization depending on 32 or 64 bit VM.
  3635   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3636             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3637                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3639   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3640   if (threadStackSizeInBytes != 0 &&
  3641       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3642         tty->print_cr("\nThe stack size specified is too small, "
  3643                       "Specify at least %dk",
  3644                       os::Bsd::min_stack_allowed/ K);
  3645         return JNI_ERR;
  3648   // Make the stack size a multiple of the page size so that
  3649   // the yellow/red zones can be guarded.
  3650   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3651         vm_page_size()));
  3653   if (MaxFDLimit) {
  3654     // set the number of file descriptors to max. print out error
  3655     // if getrlimit/setrlimit fails but continue regardless.
  3656     struct rlimit nbr_files;
  3657     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3658     if (status != 0) {
  3659       if (PrintMiscellaneous && (Verbose || WizardMode))
  3660         perror("os::init_2 getrlimit failed");
  3661     } else {
  3662       nbr_files.rlim_cur = nbr_files.rlim_max;
  3664 #ifdef __APPLE__
  3665       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3666       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
  3667       // be used instead
  3668       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3669 #endif
  3671       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3672       if (status != 0) {
  3673         if (PrintMiscellaneous && (Verbose || WizardMode))
  3674           perror("os::init_2 setrlimit failed");
  3679   // at-exit methods are called in the reverse order of their registration.
  3680   // atexit functions are called on return from main or as a result of a
  3681   // call to exit(3C). There can be only 32 of these functions registered
  3682   // and atexit() does not set errno.
  3684   if (PerfAllowAtExitRegistration) {
  3685     // only register atexit functions if PerfAllowAtExitRegistration is set.
  3686     // atexit functions can be delayed until process exit time, which
  3687     // can be problematic for embedded VM situations. Embedded VMs should
  3688     // call DestroyJavaVM() to assure that VM resources are released.
  3690     // note: perfMemory_exit_helper atexit function may be removed in
  3691     // the future if the appropriate cleanup code can be added to the
  3692     // VM_Exit VMOperation's doit method.
  3693     if (atexit(perfMemory_exit_helper) != 0) {
  3694       warning("os::init2 atexit(perfMemory_exit_helper) failed");
  3698   // initialize thread priority policy
  3699   prio_init();
  3701 #ifdef __APPLE__
  3702   // dynamically link to objective c gc registration
  3703   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
  3704   if (handleLibObjc != NULL) {
  3705     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
  3707 #endif
  3709   return JNI_OK;
  3712 // this is called at the end of vm_initialization
  3713 void os::init_3(void) { }
  3715 // Mark the polling page as unreadable
  3716 void os::make_polling_page_unreadable(void) {
  3717   if( !guard_memory((char*)_polling_page, Bsd::page_size()) )
  3718     fatal("Could not disable polling page");
  3719 };
  3721 // Mark the polling page as readable
  3722 void os::make_polling_page_readable(void) {
  3723   if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3724     fatal("Could not enable polling page");
  3726 };
  3728 int os::active_processor_count() {
  3729   return _processor_count;
  3732 void os::set_native_thread_name(const char *name) {
  3733 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  3734   // This is only supported in Snow Leopard and beyond
  3735   if (name != NULL) {
  3736     // Add a "Java: " prefix to the name
  3737     char buf[MAXTHREADNAMESIZE];
  3738     snprintf(buf, sizeof(buf), "Java: %s", name);
  3739     pthread_setname_np(buf);
  3741 #endif
  3744 bool os::distribute_processes(uint length, uint* distribution) {
  3745   // Not yet implemented.
  3746   return false;
  3749 bool os::bind_to_processor(uint processor_id) {
  3750   // Not yet implemented.
  3751   return false;
  3754 void os::SuspendedThreadTask::internal_do_task() {
  3755   if (do_suspend(_thread->osthread())) {
  3756     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
  3757     do_task(context);
  3758     do_resume(_thread->osthread());
  3762 ///
  3763 class PcFetcher : public os::SuspendedThreadTask {
  3764 public:
  3765   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
  3766   ExtendedPC result();
  3767 protected:
  3768   void do_task(const os::SuspendedThreadTaskContext& context);
  3769 private:
  3770   ExtendedPC _epc;
  3771 };
  3773 ExtendedPC PcFetcher::result() {
  3774   guarantee(is_done(), "task is not done yet.");
  3775   return _epc;
  3778 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
  3779   Thread* thread = context.thread();
  3780   OSThread* osthread = thread->osthread();
  3781   if (osthread->ucontext() != NULL) {
  3782     _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext());
  3783   } else {
  3784     // NULL context is unexpected, double-check this is the VMThread
  3785     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
  3789 // Suspends the target using the signal mechanism and then grabs the PC before
  3790 // resuming the target. Used by the flat-profiler only
  3791 ExtendedPC os::get_thread_pc(Thread* thread) {
  3792   // Make sure that it is called by the watcher for the VMThread
  3793   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
  3794   assert(thread->is_VM_thread(), "Can only be called for VMThread");
  3796   PcFetcher fetcher(thread);
  3797   fetcher.run();
  3798   return fetcher.result();
  3801 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3803   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3806 ////////////////////////////////////////////////////////////////////////////////
  3807 // debug support
  3809 bool os::find(address addr, outputStream* st) {
  3810   Dl_info dlinfo;
  3811   memset(&dlinfo, 0, sizeof(dlinfo));
  3812   if (dladdr(addr, &dlinfo) != 0) {
  3813     st->print(PTR_FORMAT ": ", addr);
  3814     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
  3815       st->print("%s+%#x", dlinfo.dli_sname,
  3816                  addr - (intptr_t)dlinfo.dli_saddr);
  3817     } else if (dlinfo.dli_fbase != NULL) {
  3818       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3819     } else {
  3820       st->print("<absolute address>");
  3822     if (dlinfo.dli_fname != NULL) {
  3823       st->print(" in %s", dlinfo.dli_fname);
  3825     if (dlinfo.dli_fbase != NULL) {
  3826       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
  3828     st->cr();
  3830     if (Verbose) {
  3831       // decode some bytes around the PC
  3832       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
  3833       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
  3834       address       lowest = (address) dlinfo.dli_sname;
  3835       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3836       if (begin < lowest)  begin = lowest;
  3837       Dl_info dlinfo2;
  3838       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3839           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3840         end = (address) dlinfo2.dli_saddr;
  3841       Disassembler::decode(begin, end, st);
  3843     return true;
  3845   return false;
  3848 ////////////////////////////////////////////////////////////////////////////////
  3849 // misc
  3851 // This does not do anything on Bsd. This is basically a hook for being
  3852 // able to use structured exception handling (thread-local exception filters)
  3853 // on, e.g., Win32.
  3854 void
  3855 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3856                          JavaCallArguments* args, Thread* thread) {
  3857   f(value, method, args, thread);
  3860 void os::print_statistics() {
  3863 int os::message_box(const char* title, const char* message) {
  3864   int i;
  3865   fdStream err(defaultStream::error_fd());
  3866   for (i = 0; i < 78; i++) err.print_raw("=");
  3867   err.cr();
  3868   err.print_raw_cr(title);
  3869   for (i = 0; i < 78; i++) err.print_raw("-");
  3870   err.cr();
  3871   err.print_raw_cr(message);
  3872   for (i = 0; i < 78; i++) err.print_raw("=");
  3873   err.cr();
  3875   char buf[16];
  3876   // Prevent process from exiting upon "read error" without consuming all CPU
  3877   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
  3879   return buf[0] == 'y' || buf[0] == 'Y';
  3882 int os::stat(const char *path, struct stat *sbuf) {
  3883   char pathbuf[MAX_PATH];
  3884   if (strlen(path) > MAX_PATH - 1) {
  3885     errno = ENAMETOOLONG;
  3886     return -1;
  3888   os::native_path(strcpy(pathbuf, path));
  3889   return ::stat(pathbuf, sbuf);
  3892 bool os::check_heap(bool force) {
  3893   return true;
  3896 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
  3897   return ::vsnprintf(buf, count, format, args);
  3900 // Is a (classpath) directory empty?
  3901 bool os::dir_is_empty(const char* path) {
  3902   DIR *dir = NULL;
  3903   struct dirent *ptr;
  3905   dir = opendir(path);
  3906   if (dir == NULL) return true;
  3908   /* Scan the directory */
  3909   bool result = true;
  3910   char buf[sizeof(struct dirent) + MAX_PATH];
  3911   while (result && (ptr = ::readdir(dir)) != NULL) {
  3912     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3913       result = false;
  3916   closedir(dir);
  3917   return result;
  3920 // This code originates from JDK's sysOpen and open64_w
  3921 // from src/solaris/hpi/src/system_md.c
  3923 #ifndef O_DELETE
  3924 #define O_DELETE 0x10000
  3925 #endif
  3927 // Open a file. Unlink the file immediately after open returns
  3928 // if the specified oflag has the O_DELETE flag set.
  3929 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3931 int os::open(const char *path, int oflag, int mode) {
  3933   if (strlen(path) > MAX_PATH - 1) {
  3934     errno = ENAMETOOLONG;
  3935     return -1;
  3937   int fd;
  3938   int o_delete = (oflag & O_DELETE);
  3939   oflag = oflag & ~O_DELETE;
  3941   fd = ::open(path, oflag, mode);
  3942   if (fd == -1) return -1;
  3944   //If the open succeeded, the file might still be a directory
  3946     struct stat buf;
  3947     int ret = ::fstat(fd, &buf);
  3948     int st_mode = buf.st_mode;
  3950     if (ret != -1) {
  3951       if ((st_mode & S_IFMT) == S_IFDIR) {
  3952         errno = EISDIR;
  3953         ::close(fd);
  3954         return -1;
  3956     } else {
  3957       ::close(fd);
  3958       return -1;
  3962     /*
  3963      * All file descriptors that are opened in the JVM and not
  3964      * specifically destined for a subprocess should have the
  3965      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3966      * party native code might fork and exec without closing all
  3967      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3968      * UNIXProcess.c), and this in turn might:
  3970      * - cause end-of-file to fail to be detected on some file
  3971      *   descriptors, resulting in mysterious hangs, or
  3973      * - might cause an fopen in the subprocess to fail on a system
  3974      *   suffering from bug 1085341.
  3976      * (Yes, the default setting of the close-on-exec flag is a Unix
  3977      * design flaw)
  3979      * See:
  3980      * 1085341: 32-bit stdio routines should support file descriptors >255
  3981      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3982      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3983      */
  3984 #ifdef FD_CLOEXEC
  3986         int flags = ::fcntl(fd, F_GETFD);
  3987         if (flags != -1)
  3988             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3990 #endif
  3992   if (o_delete != 0) {
  3993     ::unlink(path);
  3995   return fd;
  3999 // create binary file, rewriting existing file if required
  4000 int os::create_binary_file(const char* path, bool rewrite_existing) {
  4001   int oflags = O_WRONLY | O_CREAT;
  4002   if (!rewrite_existing) {
  4003     oflags |= O_EXCL;
  4005   return ::open(path, oflags, S_IREAD | S_IWRITE);
  4008 // return current position of file pointer
  4009 jlong os::current_file_offset(int fd) {
  4010   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
  4013 // move file pointer to the specified offset
  4014 jlong os::seek_to_file_offset(int fd, jlong offset) {
  4015   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
  4018 // This code originates from JDK's sysAvailable
  4019 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
  4021 int os::available(int fd, jlong *bytes) {
  4022   jlong cur, end;
  4023   int mode;
  4024   struct stat buf;
  4026   if (::fstat(fd, &buf) >= 0) {
  4027     mode = buf.st_mode;
  4028     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  4029       /*
  4030       * XXX: is the following call interruptible? If so, this might
  4031       * need to go through the INTERRUPT_IO() wrapper as for other
  4032       * blocking, interruptible calls in this file.
  4033       */
  4034       int n;
  4035       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  4036         *bytes = n;
  4037         return 1;
  4041   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
  4042     return 0;
  4043   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
  4044     return 0;
  4045   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
  4046     return 0;
  4048   *bytes = end - cur;
  4049   return 1;
  4052 int os::socket_available(int fd, jint *pbytes) {
  4053    if (fd < 0)
  4054      return OS_OK;
  4056    int ret;
  4058    RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  4060    //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  4061    // is expected to return 0 on failure and 1 on success to the jdk.
  4063    return (ret == OS_ERR) ? 0 : 1;
  4066 // Map a block of memory.
  4067 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  4068                      char *addr, size_t bytes, bool read_only,
  4069                      bool allow_exec) {
  4070   int prot;
  4071   int flags;
  4073   if (read_only) {
  4074     prot = PROT_READ;
  4075     flags = MAP_SHARED;
  4076   } else {
  4077     prot = PROT_READ | PROT_WRITE;
  4078     flags = MAP_PRIVATE;
  4081   if (allow_exec) {
  4082     prot |= PROT_EXEC;
  4085   if (addr != NULL) {
  4086     flags |= MAP_FIXED;
  4089   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
  4090                                      fd, file_offset);
  4091   if (mapped_address == MAP_FAILED) {
  4092     return NULL;
  4094   return mapped_address;
  4098 // Remap a block of memory.
  4099 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  4100                        char *addr, size_t bytes, bool read_only,
  4101                        bool allow_exec) {
  4102   // same as map_memory() on this OS
  4103   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  4104                         allow_exec);
  4108 // Unmap a block of memory.
  4109 bool os::pd_unmap_memory(char* addr, size_t bytes) {
  4110   return munmap(addr, bytes) == 0;
  4113 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  4114 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  4115 // of a thread.
  4116 //
  4117 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
  4118 // the fast estimate available on the platform.
  4120 jlong os::current_thread_cpu_time() {
  4121 #ifdef __APPLE__
  4122   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
  4123 #else
  4124   Unimplemented();
  4125   return 0;
  4126 #endif
  4129 jlong os::thread_cpu_time(Thread* thread) {
  4130 #ifdef __APPLE__
  4131   return os::thread_cpu_time(thread, true /* user + sys */);
  4132 #else
  4133   Unimplemented();
  4134   return 0;
  4135 #endif
  4138 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  4139 #ifdef __APPLE__
  4140   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  4141 #else
  4142   Unimplemented();
  4143   return 0;
  4144 #endif
  4147 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
  4148 #ifdef __APPLE__
  4149   struct thread_basic_info tinfo;
  4150   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
  4151   kern_return_t kr;
  4152   thread_t mach_thread;
  4154   mach_thread = thread->osthread()->thread_id();
  4155   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4156   if (kr != KERN_SUCCESS)
  4157     return -1;
  4159   if (user_sys_cpu_time) {
  4160     jlong nanos;
  4161     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4162     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4163     return nanos;
  4164   } else {
  4165     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
  4167 #else
  4168   Unimplemented();
  4169   return 0;
  4170 #endif
  4174 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  4175   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  4176   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  4177   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  4178   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  4181 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  4182   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
  4183   info_ptr->may_skip_backward = false;     // elapsed time not wall time
  4184   info_ptr->may_skip_forward = false;      // elapsed time not wall time
  4185   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
  4188 bool os::is_thread_cpu_time_supported() {
  4189 #ifdef __APPLE__
  4190   return true;
  4191 #else
  4192   return false;
  4193 #endif
  4196 // System loadavg support.  Returns -1 if load average cannot be obtained.
  4197 // Bsd doesn't yet have a (official) notion of processor sets,
  4198 // so just return the system wide load average.
  4199 int os::loadavg(double loadavg[], int nelem) {
  4200   return ::getloadavg(loadavg, nelem);
  4203 void os::pause() {
  4204   char filename[MAX_PATH];
  4205   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  4206     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  4207   } else {
  4208     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  4211   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4212   if (fd != -1) {
  4213     struct stat buf;
  4214     ::close(fd);
  4215     while (::stat(filename, &buf) == 0) {
  4216       (void)::poll(NULL, 0, 100);
  4218   } else {
  4219     jio_fprintf(stderr,
  4220       "Could not open pause file '%s', continuing immediately.\n", filename);
  4225 // Refer to the comments in os_solaris.cpp park-unpark.
  4226 //
  4227 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
  4228 // hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
  4229 // For specifics regarding the bug see GLIBC BUGID 261237 :
  4230 //    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
  4231 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
  4232 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
  4233 // is used.  (The simple C test-case provided in the GLIBC bug report manifests the
  4234 // hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
  4235 // and monitorenter when we're using 1-0 locking.  All those operations may result in
  4236 // calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
  4237 // of libpthread avoids the problem, but isn't practical.
  4238 //
  4239 // Possible remedies:
  4240 //
  4241 // 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
  4242 //      This is palliative and probabilistic, however.  If the thread is preempted
  4243 //      between the call to compute_abstime() and pthread_cond_timedwait(), more
  4244 //      than the minimum period may have passed, and the abstime may be stale (in the
  4245 //      past) resultin in a hang.   Using this technique reduces the odds of a hang
  4246 //      but the JVM is still vulnerable, particularly on heavily loaded systems.
  4247 //
  4248 // 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
  4249 //      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
  4250 //      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
  4251 //      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
  4252 //      thread.
  4253 //
  4254 // 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
  4255 //      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
  4256 //      a timeout request to the chron thread and then blocking via pthread_cond_wait().
  4257 //      This also works well.  In fact it avoids kernel-level scalability impediments
  4258 //      on certain platforms that don't handle lots of active pthread_cond_timedwait()
  4259 //      timers in a graceful fashion.
  4260 //
  4261 // 4.   When the abstime value is in the past it appears that control returns
  4262 //      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
  4263 //      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
  4264 //      can avoid the problem by reinitializing the condvar -- by cond_destroy()
  4265 //      followed by cond_init() -- after all calls to pthread_cond_timedwait().
  4266 //      It may be possible to avoid reinitialization by checking the return
  4267 //      value from pthread_cond_timedwait().  In addition to reinitializing the
  4268 //      condvar we must establish the invariant that cond_signal() is only called
  4269 //      within critical sections protected by the adjunct mutex.  This prevents
  4270 //      cond_signal() from "seeing" a condvar that's in the midst of being
  4271 //      reinitialized or that is corrupt.  Sadly, this invariant obviates the
  4272 //      desirable signal-after-unlock optimization that avoids futile context switching.
  4273 //
  4274 //      I'm also concerned that some versions of NTPL might allocate an auxilliary
  4275 //      structure when a condvar is used or initialized.  cond_destroy()  would
  4276 //      release the helper structure.  Our reinitialize-after-timedwait fix
  4277 //      put excessive stress on malloc/free and locks protecting the c-heap.
  4278 //
  4279 // We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
  4280 // It may be possible to refine (4) by checking the kernel and NTPL verisons
  4281 // and only enabling the work-around for vulnerable environments.
  4283 // utility to compute the abstime argument to timedwait:
  4284 // millis is the relative timeout time
  4285 // abstime will be the absolute timeout time
  4286 // TODO: replace compute_abstime() with unpackTime()
  4288 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4289   if (millis < 0)  millis = 0;
  4290   struct timeval now;
  4291   int status = gettimeofday(&now, NULL);
  4292   assert(status == 0, "gettimeofday");
  4293   jlong seconds = millis / 1000;
  4294   millis %= 1000;
  4295   if (seconds > 50000000) { // see man cond_timedwait(3T)
  4296     seconds = 50000000;
  4298   abstime->tv_sec = now.tv_sec  + seconds;
  4299   long       usec = now.tv_usec + millis * 1000;
  4300   if (usec >= 1000000) {
  4301     abstime->tv_sec += 1;
  4302     usec -= 1000000;
  4304   abstime->tv_nsec = usec * 1000;
  4305   return abstime;
  4309 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
  4310 // Conceptually TryPark() should be equivalent to park(0).
  4312 int os::PlatformEvent::TryPark() {
  4313   for (;;) {
  4314     const int v = _Event ;
  4315     guarantee ((v == 0) || (v == 1), "invariant") ;
  4316     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
  4320 void os::PlatformEvent::park() {       // AKA "down()"
  4321   // Invariant: Only the thread associated with the Event/PlatformEvent
  4322   // may call park().
  4323   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4324   int v ;
  4325   for (;;) {
  4326       v = _Event ;
  4327       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4329   guarantee (v >= 0, "invariant") ;
  4330   if (v == 0) {
  4331      // Do this the hard way by blocking ...
  4332      int status = pthread_mutex_lock(_mutex);
  4333      assert_status(status == 0, status, "mutex_lock");
  4334      guarantee (_nParked == 0, "invariant") ;
  4335      ++ _nParked ;
  4336      while (_Event < 0) {
  4337         status = pthread_cond_wait(_cond, _mutex);
  4338         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4339         // Treat this the same as if the wait was interrupted
  4340         if (status == ETIMEDOUT) { status = EINTR; }
  4341         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4343      -- _nParked ;
  4345     _Event = 0 ;
  4346      status = pthread_mutex_unlock(_mutex);
  4347      assert_status(status == 0, status, "mutex_unlock");
  4348     // Paranoia to ensure our locked and lock-free paths interact
  4349     // correctly with each other.
  4350     OrderAccess::fence();
  4352   guarantee (_Event >= 0, "invariant") ;
  4355 int os::PlatformEvent::park(jlong millis) {
  4356   guarantee (_nParked == 0, "invariant") ;
  4358   int v ;
  4359   for (;;) {
  4360       v = _Event ;
  4361       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  4363   guarantee (v >= 0, "invariant") ;
  4364   if (v != 0) return OS_OK ;
  4366   // We do this the hard way, by blocking the thread.
  4367   // Consider enforcing a minimum timeout value.
  4368   struct timespec abst;
  4369   compute_abstime(&abst, millis);
  4371   int ret = OS_TIMEOUT;
  4372   int status = pthread_mutex_lock(_mutex);
  4373   assert_status(status == 0, status, "mutex_lock");
  4374   guarantee (_nParked == 0, "invariant") ;
  4375   ++_nParked ;
  4377   // Object.wait(timo) will return because of
  4378   // (a) notification
  4379   // (b) timeout
  4380   // (c) thread.interrupt
  4381   //
  4382   // Thread.interrupt and object.notify{All} both call Event::set.
  4383   // That is, we treat thread.interrupt as a special case of notification.
  4384   // The underlying Solaris implementation, cond_timedwait, admits
  4385   // spurious/premature wakeups, but the JLS/JVM spec prevents the
  4386   // JVM from making those visible to Java code.  As such, we must
  4387   // filter out spurious wakeups.  We assume all ETIME returns are valid.
  4388   //
  4389   // TODO: properly differentiate simultaneous notify+interrupt.
  4390   // In that case, we should propagate the notify to another waiter.
  4392   while (_Event < 0) {
  4393     status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst);
  4394     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4395       pthread_cond_destroy (_cond);
  4396       pthread_cond_init (_cond, NULL) ;
  4398     assert_status(status == 0 || status == EINTR ||
  4399                   status == ETIMEDOUT,
  4400                   status, "cond_timedwait");
  4401     if (!FilterSpuriousWakeups) break ;                 // previous semantics
  4402     if (status == ETIMEDOUT) break ;
  4403     // We consume and ignore EINTR and spurious wakeups.
  4405   --_nParked ;
  4406   if (_Event >= 0) {
  4407      ret = OS_OK;
  4409   _Event = 0 ;
  4410   status = pthread_mutex_unlock(_mutex);
  4411   assert_status(status == 0, status, "mutex_unlock");
  4412   assert (_nParked == 0, "invariant") ;
  4413   // Paranoia to ensure our locked and lock-free paths interact
  4414   // correctly with each other.
  4415   OrderAccess::fence();
  4416   return ret;
  4419 void os::PlatformEvent::unpark() {
  4420   // Transitions for _Event:
  4421   //    0 :=> 1
  4422   //    1 :=> 1
  4423   //   -1 :=> either 0 or 1; must signal target thread
  4424   //          That is, we can safely transition _Event from -1 to either
  4425   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
  4426   //          unpark() calls.
  4427   // See also: "Semaphores in Plan 9" by Mullender & Cox
  4428   //
  4429   // Note: Forcing a transition from "-1" to "1" on an unpark() means
  4430   // that it will take two back-to-back park() calls for the owning
  4431   // thread to block. This has the benefit of forcing a spurious return
  4432   // from the first park() call after an unpark() call which will help
  4433   // shake out uses of park() and unpark() without condition variables.
  4435   if (Atomic::xchg(1, &_Event) >= 0) return;
  4437   // Wait for the thread associated with the event to vacate
  4438   int status = pthread_mutex_lock(_mutex);
  4439   assert_status(status == 0, status, "mutex_lock");
  4440   int AnyWaiters = _nParked;
  4441   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
  4442   if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
  4443     AnyWaiters = 0;
  4444     pthread_cond_signal(_cond);
  4446   status = pthread_mutex_unlock(_mutex);
  4447   assert_status(status == 0, status, "mutex_unlock");
  4448   if (AnyWaiters != 0) {
  4449     status = pthread_cond_signal(_cond);
  4450     assert_status(status == 0, status, "cond_signal");
  4453   // Note that we signal() _after dropping the lock for "immortal" Events.
  4454   // This is safe and avoids a common class of  futile wakeups.  In rare
  4455   // circumstances this can cause a thread to return prematurely from
  4456   // cond_{timed}wait() but the spurious wakeup is benign and the victim will
  4457   // simply re-test the condition and re-park itself.
  4461 // JSR166
  4462 // -------------------------------------------------------
  4464 /*
  4465  * The solaris and bsd implementations of park/unpark are fairly
  4466  * conservative for now, but can be improved. They currently use a
  4467  * mutex/condvar pair, plus a a count.
  4468  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4469  * sets count to 1 and signals condvar.  Only one thread ever waits
  4470  * on the condvar. Contention seen when trying to park implies that someone
  4471  * is unparking you, so don't wait. And spurious returns are fine, so there
  4472  * is no need to track notifications.
  4473  */
  4475 #define MAX_SECS 100000000
  4476 /*
  4477  * This code is common to bsd and solaris and will be moved to a
  4478  * common place in dolphin.
  4480  * The passed in time value is either a relative time in nanoseconds
  4481  * or an absolute time in milliseconds. Either way it has to be unpacked
  4482  * into suitable seconds and nanoseconds components and stored in the
  4483  * given timespec structure.
  4484  * Given time is a 64-bit value and the time_t used in the timespec is only
  4485  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4486  * overflow if times way in the future are given. Further on Solaris versions
  4487  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4488  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4489  * As it will be 28 years before "now + 100000000" will overflow we can
  4490  * ignore overflow and just impose a hard-limit on seconds using the value
  4491  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4492  * years from "now".
  4493  */
  4495 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4496   assert (time > 0, "convertTime");
  4498   struct timeval now;
  4499   int status = gettimeofday(&now, NULL);
  4500   assert(status == 0, "gettimeofday");
  4502   time_t max_secs = now.tv_sec + MAX_SECS;
  4504   if (isAbsolute) {
  4505     jlong secs = time / 1000;
  4506     if (secs > max_secs) {
  4507       absTime->tv_sec = max_secs;
  4509     else {
  4510       absTime->tv_sec = secs;
  4512     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4514   else {
  4515     jlong secs = time / NANOSECS_PER_SEC;
  4516     if (secs >= MAX_SECS) {
  4517       absTime->tv_sec = max_secs;
  4518       absTime->tv_nsec = 0;
  4520     else {
  4521       absTime->tv_sec = now.tv_sec + secs;
  4522       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4523       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4524         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4525         ++absTime->tv_sec; // note: this must be <= max_secs
  4529   assert(absTime->tv_sec >= 0, "tv_sec < 0");
  4530   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
  4531   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
  4532   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
  4535 void Parker::park(bool isAbsolute, jlong time) {
  4536   // Ideally we'd do something useful while spinning, such
  4537   // as calling unpackTime().
  4539   // Optional fast-path check:
  4540   // Return immediately if a permit is available.
  4541   // We depend on Atomic::xchg() having full barrier semantics
  4542   // since we are doing a lock-free update to _counter.
  4543   if (Atomic::xchg(0, &_counter) > 0) return;
  4545   Thread* thread = Thread::current();
  4546   assert(thread->is_Java_thread(), "Must be JavaThread");
  4547   JavaThread *jt = (JavaThread *)thread;
  4549   // Optional optimization -- avoid state transitions if there's an interrupt pending.
  4550   // Check interrupt before trying to wait
  4551   if (Thread::is_interrupted(thread, false)) {
  4552     return;
  4555   // Next, demultiplex/decode time arguments
  4556   struct timespec absTime;
  4557   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
  4558     return;
  4560   if (time > 0) {
  4561     unpackTime(&absTime, isAbsolute, time);
  4565   // Enter safepoint region
  4566   // Beware of deadlocks such as 6317397.
  4567   // The per-thread Parker:: mutex is a classic leaf-lock.
  4568   // In particular a thread must never block on the Threads_lock while
  4569   // holding the Parker:: mutex.  If safepoints are pending both the
  4570   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
  4571   ThreadBlockInVM tbivm(jt);
  4573   // Don't wait if cannot get lock since interference arises from
  4574   // unblocking.  Also. check interrupt before trying wait
  4575   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
  4576     return;
  4579   int status ;
  4580   if (_counter > 0)  { // no wait needed
  4581     _counter = 0;
  4582     status = pthread_mutex_unlock(_mutex);
  4583     assert (status == 0, "invariant") ;
  4584     // Paranoia to ensure our locked and lock-free paths interact
  4585     // correctly with each other and Java-level accesses.
  4586     OrderAccess::fence();
  4587     return;
  4590 #ifdef ASSERT
  4591   // Don't catch signals while blocked; let the running threads have the signals.
  4592   // (This allows a debugger to break into the running thread.)
  4593   sigset_t oldsigs;
  4594   sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
  4595   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
  4596 #endif
  4598   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  4599   jt->set_suspend_equivalent();
  4600   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  4602   if (time == 0) {
  4603     status = pthread_cond_wait (_cond, _mutex) ;
  4604   } else {
  4605     status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ;
  4606     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
  4607       pthread_cond_destroy (_cond) ;
  4608       pthread_cond_init    (_cond, NULL);
  4611   assert_status(status == 0 || status == EINTR ||
  4612                 status == ETIMEDOUT,
  4613                 status, "cond_timedwait");
  4615 #ifdef ASSERT
  4616   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
  4617 #endif
  4619   _counter = 0 ;
  4620   status = pthread_mutex_unlock(_mutex) ;
  4621   assert_status(status == 0, status, "invariant") ;
  4622   // Paranoia to ensure our locked and lock-free paths interact
  4623   // correctly with each other and Java-level accesses.
  4624   OrderAccess::fence();
  4626   // If externally suspended while waiting, re-suspend
  4627   if (jt->handle_special_suspend_equivalent_condition()) {
  4628     jt->java_suspend_self();
  4632 void Parker::unpark() {
  4633   int s, status ;
  4634   status = pthread_mutex_lock(_mutex);
  4635   assert (status == 0, "invariant") ;
  4636   s = _counter;
  4637   _counter = 1;
  4638   if (s < 1) {
  4639      if (WorkAroundNPTLTimedWaitHang) {
  4640         status = pthread_cond_signal (_cond) ;
  4641         assert (status == 0, "invariant") ;
  4642         status = pthread_mutex_unlock(_mutex);
  4643         assert (status == 0, "invariant") ;
  4644      } else {
  4645         status = pthread_mutex_unlock(_mutex);
  4646         assert (status == 0, "invariant") ;
  4647         status = pthread_cond_signal (_cond) ;
  4648         assert (status == 0, "invariant") ;
  4650   } else {
  4651     pthread_mutex_unlock(_mutex);
  4652     assert (status == 0, "invariant") ;
  4657 /* Darwin has no "environ" in a dynamic library. */
  4658 #ifdef __APPLE__
  4659 #include <crt_externs.h>
  4660 #define environ (*_NSGetEnviron())
  4661 #else
  4662 extern char** environ;
  4663 #endif
  4665 // Run the specified command in a separate process. Return its exit value,
  4666 // or -1 on failure (e.g. can't fork a new process).
  4667 // Unlike system(), this function can be called from signal handler. It
  4668 // doesn't block SIGINT et al.
  4669 int os::fork_and_exec(char* cmd) {
  4670   const char * argv[4] = {"sh", "-c", cmd, NULL};
  4672   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
  4673   // pthread_atfork handlers and reset pthread library. All we need is a
  4674   // separate process to execve. Make a direct syscall to fork process.
  4675   // On IA64 there's no fork syscall, we have to use fork() and hope for
  4676   // the best...
  4677   pid_t pid = fork();
  4679   if (pid < 0) {
  4680     // fork failed
  4681     return -1;
  4683   } else if (pid == 0) {
  4684     // child process
  4686     // execve() in BsdThreads will call pthread_kill_other_threads_np()
  4687     // first to kill every thread on the thread list. Because this list is
  4688     // not reset by fork() (see notes above), execve() will instead kill
  4689     // every thread in the parent process. We know this is the only thread
  4690     // in the new process, so make a system call directly.
  4691     // IA64 should use normal execve() from glibc to match the glibc fork()
  4692     // above.
  4693     execve("/bin/sh", (char* const*)argv, environ);
  4695     // execve failed
  4696     _exit(-1);
  4698   } else  {
  4699     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
  4700     // care about the actual exit code, for now.
  4702     int status;
  4704     // Wait for the child process to exit.  This returns immediately if
  4705     // the child has already exited. */
  4706     while (waitpid(pid, &status, 0) < 0) {
  4707         switch (errno) {
  4708         case ECHILD: return 0;
  4709         case EINTR: break;
  4710         default: return -1;
  4714     if (WIFEXITED(status)) {
  4715        // The child exited normally; get its exit code.
  4716        return WEXITSTATUS(status);
  4717     } else if (WIFSIGNALED(status)) {
  4718        // The child exited because of a signal
  4719        // The best value to return is 0x80 + signal number,
  4720        // because that is what all Unix shells do, and because
  4721        // it allows callers to distinguish between process exit and
  4722        // process death by signal.
  4723        return 0x80 + WTERMSIG(status);
  4724     } else {
  4725        // Unknown exit code; pass it through
  4726        return status;
  4731 // is_headless_jre()
  4732 //
  4733 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
  4734 // in order to report if we are running in a headless jre
  4735 //
  4736 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4737 // as libawt.so, and renamed libawt_xawt.so
  4738 //
  4739 bool os::is_headless_jre() {
  4740 #ifdef __APPLE__
  4741     // We no longer build headless-only on Mac OS X
  4742     return false;
  4743 #else
  4744     struct stat statbuf;
  4745     char buf[MAXPATHLEN];
  4746     char libmawtpath[MAXPATHLEN];
  4747     const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
  4748     const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
  4749     char *p;
  4751     // Get path to libjvm.so
  4752     os::jvm_path(buf, sizeof(buf));
  4754     // Get rid of libjvm.so
  4755     p = strrchr(buf, '/');
  4756     if (p == NULL) return false;
  4757     else *p = '\0';
  4759     // Get rid of client or server
  4760     p = strrchr(buf, '/');
  4761     if (p == NULL) return false;
  4762     else *p = '\0';
  4764     // check xawt/libmawt.so
  4765     strcpy(libmawtpath, buf);
  4766     strcat(libmawtpath, xawtstr);
  4767     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4769     // check libawt_xawt.so
  4770     strcpy(libmawtpath, buf);
  4771     strcat(libmawtpath, new_xawtstr);
  4772     if (::stat(libmawtpath, &statbuf) == 0) return false;
  4774     return true;
  4775 #endif
  4778 // Get the default path to the core file
  4779 // Returns the length of the string
  4780 int os::get_core_path(char* buffer, size_t bufferSize) {
  4781   int n = jio_snprintf(buffer, bufferSize, "/cores");
  4783   // Truncate if theoretical string was longer than bufferSize
  4784   n = MIN2(n, (int)bufferSize);
  4786   return n;
  4789 #ifndef PRODUCT
  4790 void TestReserveMemorySpecial_test() {
  4791   // No tests available for this platform
  4793 #endif

mercurial