hotspot/src/os/bsd/vm/os_bsd.cpp
changeset 26704 36bff23b2c2e
parent 26698 2a7f85720535
parent 26685 aa239a0dfbea
child 27157 364276bc8d8b
equal deleted inserted replaced
26703:a5739f4f8eca 26704:36bff23b2c2e
   104 # include <inttypes.h>
   104 # include <inttypes.h>
   105 # include <sys/ioctl.h>
   105 # include <sys/ioctl.h>
   106 # include <sys/syscall.h>
   106 # include <sys/syscall.h>
   107 
   107 
   108 #if defined(__FreeBSD__) || defined(__NetBSD__)
   108 #if defined(__FreeBSD__) || defined(__NetBSD__)
   109 # include <elf.h>
   109   #include <elf.h>
   110 #endif
   110 #endif
   111 
   111 
   112 #ifdef __APPLE__
   112 #ifdef __APPLE__
   113 # include <mach/mach.h> // semaphore_* API
   113   #include <mach/mach.h> // semaphore_* API
   114 # include <mach-o/dyld.h>
   114   #include <mach-o/dyld.h>
   115 # include <sys/proc_info.h>
   115   #include <sys/proc_info.h>
   116 # include <objc/objc-auto.h>
   116   #include <objc/objc-auto.h>
   117 #endif
   117 #endif
   118 
   118 
   119 #ifndef MAP_ANONYMOUS
   119 #ifndef MAP_ANONYMOUS
   120 #define MAP_ANONYMOUS MAP_ANON
   120   #define MAP_ANONYMOUS MAP_ANON
   121 #endif
   121 #endif
   122 
   122 
   123 #define MAX_PATH    (2 * K)
   123 #define MAX_PATH    (2 * K)
   124 
   124 
   125 // for timer info max values which include all bits
   125 // for timer info max values which include all bits
   150 static sigset_t check_signal_done;
   150 static sigset_t check_signal_done;
   151 static bool check_signals = true;
   151 static bool check_signals = true;
   152 
   152 
   153 static pid_t _initial_pid = 0;
   153 static pid_t _initial_pid = 0;
   154 
   154 
   155 /* Signal number used to suspend/resume a thread */
   155 // Signal number used to suspend/resume a thread
   156 
   156 
   157 /* do not use any signal number less than SIGSEGV, see 4355769 */
   157 // do not use any signal number less than SIGSEGV, see 4355769
   158 static int SR_signum = SIGUSR2;
   158 static int SR_signum = SIGUSR2;
   159 sigset_t SR_sigset;
   159 sigset_t SR_sigset;
   160 
   160 
   161 
   161 
   162 ////////////////////////////////////////////////////////////////////////////////
   162 ////////////////////////////////////////////////////////////////////////////////
   230 #elif defined(ARM)
   230 #elif defined(ARM)
   231 static char cpu_arch[] = "arm";
   231 static char cpu_arch[] = "arm";
   232 #elif defined(PPC32)
   232 #elif defined(PPC32)
   233 static char cpu_arch[] = "ppc";
   233 static char cpu_arch[] = "ppc";
   234 #elif defined(SPARC)
   234 #elif defined(SPARC)
   235 #  ifdef _LP64
   235   #ifdef _LP64
   236 static char cpu_arch[] = "sparcv9";
   236 static char cpu_arch[] = "sparcv9";
   237 #  else
   237   #else
   238 static char cpu_arch[] = "sparc";
   238 static char cpu_arch[] = "sparc";
   239 #  endif
   239   #endif
   240 #else
   240 #else
   241 #error Add appropriate cpu_arch setting
   241   #error Add appropriate cpu_arch setting
   242 #endif
   242 #endif
   243 
   243 
   244 // Compiler variant
   244 // Compiler variant
   245 #ifdef COMPILER2
   245 #ifdef COMPILER2
   246 #define COMPILER_VARIANT "server"
   246   #define COMPILER_VARIANT "server"
   247 #else
   247 #else
   248 #define COMPILER_VARIANT "client"
   248   #define COMPILER_VARIANT "client"
   249 #endif
   249 #endif
   250 
   250 
   251 
   251 
   252 void os::Bsd::initialize_system_info() {
   252 void os::Bsd::initialize_system_info() {
   253   int mib[2];
   253   int mib[2];
   254   size_t len;
   254   size_t len;
   255   int cpu_val;
   255   int cpu_val;
   256   julong mem_val;
   256   julong mem_val;
   257 
   257 
   258   /* get processors count via hw.ncpus sysctl */
   258   // get processors count via hw.ncpus sysctl
   259   mib[0] = CTL_HW;
   259   mib[0] = CTL_HW;
   260   mib[1] = HW_NCPU;
   260   mib[1] = HW_NCPU;
   261   len = sizeof(cpu_val);
   261   len = sizeof(cpu_val);
   262   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
   262   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
   263        assert(len == sizeof(cpu_val), "unexpected data size");
   263     assert(len == sizeof(cpu_val), "unexpected data size");
   264        set_processor_count(cpu_val);
   264     set_processor_count(cpu_val);
   265   }
   265   } else {
   266   else {
   266     set_processor_count(1);   // fallback
   267        set_processor_count(1);   // fallback
   267   }
   268   }
   268 
   269 
   269   // get physical memory via hw.memsize sysctl (hw.memsize is used
   270   /* get physical memory via hw.memsize sysctl (hw.memsize is used
   270   // since it returns a 64 bit value)
   271    * since it returns a 64 bit value)
       
   272    */
       
   273   mib[0] = CTL_HW;
   271   mib[0] = CTL_HW;
   274 
   272 
   275 #if defined (HW_MEMSIZE) // Apple
   273 #if defined (HW_MEMSIZE) // Apple
   276   mib[1] = HW_MEMSIZE;
   274   mib[1] = HW_MEMSIZE;
   277 #elif defined(HW_PHYSMEM) // Most of BSD
   275 #elif defined(HW_PHYSMEM) // Most of BSD
   282   #error No ways to get physmem
   280   #error No ways to get physmem
   283 #endif
   281 #endif
   284 
   282 
   285   len = sizeof(mem_val);
   283   len = sizeof(mem_val);
   286   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
   284   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
   287        assert(len == sizeof(mem_val), "unexpected data size");
   285     assert(len == sizeof(mem_val), "unexpected data size");
   288        _physical_memory = mem_val;
   286     _physical_memory = mem_val;
   289   } else {
   287   } else {
   290        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
   288     _physical_memory = 256 * 1024 * 1024;       // fallback (XXXBSD?)
   291   }
   289   }
   292 
   290 
   293 #ifdef __OpenBSD__
   291 #ifdef __OpenBSD__
   294   {
   292   {
   295        // limit _physical_memory memory view on OpenBSD since
   293     // limit _physical_memory memory view on OpenBSD since
   296        // datasize rlimit restricts us anyway.
   294     // datasize rlimit restricts us anyway.
   297        struct rlimit limits;
   295     struct rlimit limits;
   298        getrlimit(RLIMIT_DATA, &limits);
   296     getrlimit(RLIMIT_DATA, &limits);
   299        _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
   297     _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
   300   }
   298   }
   301 #endif
   299 #endif
   302 }
   300 }
   303 
   301 
   304 #ifdef __APPLE__
   302 #ifdef __APPLE__
   340   // Otherwise exit.
   338   // Otherwise exit.
   341   //
   339   //
   342   // Important note: if the location of libjvm.so changes this
   340   // Important note: if the location of libjvm.so changes this
   343   // code needs to be changed accordingly.
   341   // code needs to be changed accordingly.
   344 
   342 
   345 // See ld(1):
   343   // See ld(1):
   346 //      The linker uses the following search paths to locate required
   344   //      The linker uses the following search paths to locate required
   347 //      shared libraries:
   345   //      shared libraries:
   348 //        1: ...
   346   //        1: ...
   349 //        ...
   347   //        ...
   350 //        7: The default directories, normally /lib and /usr/lib.
   348   //        7: The default directories, normally /lib and /usr/lib.
   351 #ifndef DEFAULT_LIBPATH
   349 #ifndef DEFAULT_LIBPATH
   352 #define DEFAULT_LIBPATH "/lib:/usr/lib"
   350   #define DEFAULT_LIBPATH "/lib:/usr/lib"
   353 #endif
   351 #endif
   354 
   352 
   355 // Base path of extensions installed on the system.
   353 // Base path of extensions installed on the system.
   356 #define SYS_EXT_DIR     "/usr/java/packages"
   354 #define SYS_EXT_DIR     "/usr/java/packages"
   357 #define EXTENSIONS_DIR  "/lib/ext"
   355 #define EXTENSIONS_DIR  "/lib/ext"
   433 
   431 
   434   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
   432   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
   435 
   433 
   436 #else // __APPLE__
   434 #else // __APPLE__
   437 
   435 
   438 #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
   436   #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
   439 #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
   437   #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
   440 
   438 
   441   const char *user_home_dir = get_home();
   439   const char *user_home_dir = get_home();
   442   // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
   440   // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
   443   size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
   441   size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
   444     sizeof(SYS_EXTENSIONS_DIRS);
   442     sizeof(SYS_EXTENSIONS_DIRS);
   559 
   557 
   560 debug_only(static bool signal_sets_initialized = false);
   558 debug_only(static bool signal_sets_initialized = false);
   561 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
   559 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
   562 
   560 
   563 bool os::Bsd::is_sig_ignored(int sig) {
   561 bool os::Bsd::is_sig_ignored(int sig) {
   564       struct sigaction oact;
   562   struct sigaction oact;
   565       sigaction(sig, (struct sigaction*)NULL, &oact);
   563   sigaction(sig, (struct sigaction*)NULL, &oact);
   566       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
   564   void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
   567                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
   565                                  : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
   568       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
   566   if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) {
   569            return true;
   567     return true;
   570       else
   568   } else {
   571            return false;
   569     return false;
       
   570   }
   572 }
   571 }
   573 
   572 
   574 void os::Bsd::signal_sets_init() {
   573 void os::Bsd::signal_sets_init() {
   575   // Should also have an assertion stating we are still single-threaded.
   574   // Should also have an assertion stating we are still single-threaded.
   576   assert(!signal_sets_initialized, "Already initialized");
   575   assert(!signal_sets_initialized, "Already initialized");
   594   sigaddset(&unblocked_sigs, SIGBUS);
   593   sigaddset(&unblocked_sigs, SIGBUS);
   595   sigaddset(&unblocked_sigs, SIGFPE);
   594   sigaddset(&unblocked_sigs, SIGFPE);
   596   sigaddset(&unblocked_sigs, SR_signum);
   595   sigaddset(&unblocked_sigs, SR_signum);
   597 
   596 
   598   if (!ReduceSignalUsage) {
   597   if (!ReduceSignalUsage) {
   599    if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
   598     if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
   600       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
   599       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
   601       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
   600       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
   602    }
   601     }
   603    if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
   602     if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
   604       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
   603       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
   605       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
   604       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
   606    }
   605     }
   607    if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
   606     if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
   608       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
   607       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
   609       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
   608       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
   610    }
   609     }
   611   }
   610   }
   612   // Fill in signals that are blocked by all but the VM thread.
   611   // Fill in signals that are blocked by all but the VM thread.
   613   sigemptyset(&vm_sigs);
   612   sigemptyset(&vm_sigs);
   614   if (!ReduceSignalUsage)
   613   if (!ReduceSignalUsage) {
   615     sigaddset(&vm_sigs, BREAK_SIGNAL);
   614     sigaddset(&vm_sigs, BREAK_SIGNAL);
       
   615   }
   616   debug_only(signal_sets_initialized = true);
   616   debug_only(signal_sets_initialized = true);
   617 
   617 
   618 }
   618 }
   619 
   619 
   620 // These are signals that are unblocked while a thread is running Java.
   620 // These are signals that are unblocked while a thread is running Java.
   669 }
   669 }
   670 
   670 
   671 #ifdef __APPLE__
   671 #ifdef __APPLE__
   672 // library handle for calling objc_registerThreadWithCollector()
   672 // library handle for calling objc_registerThreadWithCollector()
   673 // without static linking to the libobjc library
   673 // without static linking to the libobjc library
   674 #define OBJC_LIB "/usr/lib/libobjc.dylib"
   674   #define OBJC_LIB "/usr/lib/libobjc.dylib"
   675 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
   675   #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
   676 typedef void (*objc_registerThreadWithCollector_t)();
   676 typedef void (*objc_registerThreadWithCollector_t)();
   677 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
   677 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
   678 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
   678 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
   679 #endif
   679 #endif
   680 
   680 
   844 
   844 
   845   }
   845   }
   846 
   846 
   847   // Aborted due to thread limit being reached
   847   // Aborted due to thread limit being reached
   848   if (state == ZOMBIE) {
   848   if (state == ZOMBIE) {
   849       thread->set_osthread(NULL);
   849     thread->set_osthread(NULL);
   850       delete osthread;
   850     delete osthread;
   851       return false;
   851     return false;
   852   }
   852   }
   853 
   853 
   854   // The thread is returned suspended (in state INITIALIZED),
   854   // The thread is returned suspended (in state INITIALIZED),
   855   // and is started higher up in the call chain
   855   // and is started higher up in the call chain
   856   assert(state == INITIALIZED, "race condition");
   856   assert(state == INITIALIZED, "race condition");
   866   return create_attached_thread(thread);
   866   return create_attached_thread(thread);
   867 }
   867 }
   868 
   868 
   869 bool os::create_attached_thread(JavaThread* thread) {
   869 bool os::create_attached_thread(JavaThread* thread) {
   870 #ifdef ASSERT
   870 #ifdef ASSERT
   871     thread->verify_not_published();
   871   thread->verify_not_published();
   872 #endif
   872 #endif
   873 
   873 
   874   // Allocate the OSThread object
   874   // Allocate the OSThread object
   875   OSThread* osthread = new OSThread(NULL, NULL);
   875   OSThread* osthread = new OSThread(NULL, NULL);
   876 
   876 
   917 
   917 
   918   if (Thread::current()->osthread() == osthread) {
   918   if (Thread::current()->osthread() == osthread) {
   919     // Restore caller's signal mask
   919     // Restore caller's signal mask
   920     sigset_t sigmask = osthread->caller_sigmask();
   920     sigset_t sigmask = osthread->caller_sigmask();
   921     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   921     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
   922    }
   922   }
   923 
   923 
   924   delete osthread;
   924   delete osthread;
   925 }
   925 }
   926 
   926 
   927 //////////////////////////////////////////////////////////////////////////////
   927 //////////////////////////////////////////////////////////////////////////////
   995   assert(status != -1, "bsd error");
   995   assert(status != -1, "bsd error");
   996   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   996   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
   997 }
   997 }
   998 
   998 
   999 #ifndef __APPLE__
   999 #ifndef __APPLE__
  1000 #ifndef CLOCK_MONOTONIC
  1000   #ifndef CLOCK_MONOTONIC
  1001 #define CLOCK_MONOTONIC (1)
  1001     #define CLOCK_MONOTONIC (1)
  1002 #endif
  1002   #endif
  1003 #endif
  1003 #endif
  1004 
  1004 
  1005 #ifdef __APPLE__
  1005 #ifdef __APPLE__
  1006 void os::Bsd::clock_init() {
  1006 void os::Bsd::clock_init() {
  1007   mach_timebase_info(&_timebase_info);
  1007   mach_timebase_info(&_timebase_info);
  1021 
  1021 
  1022 
  1022 
  1023 #ifdef __APPLE__
  1023 #ifdef __APPLE__
  1024 
  1024 
  1025 jlong os::javaTimeNanos() {
  1025 jlong os::javaTimeNanos() {
  1026     const uint64_t tm = mach_absolute_time();
  1026   const uint64_t tm = mach_absolute_time();
  1027     const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;
  1027   const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;
  1028     const uint64_t prev = Bsd::_max_abstime;
  1028   const uint64_t prev = Bsd::_max_abstime;
  1029     if (now <= prev) {
  1029   if (now <= prev) {
  1030       return prev;   // same or retrograde time;
  1030     return prev;   // same or retrograde time;
  1031     }
  1031   }
  1032     const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev);
  1032   const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev);
  1033     assert(obsv >= prev, "invariant");   // Monotonicity
  1033   assert(obsv >= prev, "invariant");   // Monotonicity
  1034     // If the CAS succeeded then we're done and return "now".
  1034   // If the CAS succeeded then we're done and return "now".
  1035     // If the CAS failed and the observed value "obsv" is >= now then
  1035   // If the CAS failed and the observed value "obsv" is >= now then
  1036     // we should return "obsv".  If the CAS failed and now > obsv > prv then
  1036   // we should return "obsv".  If the CAS failed and now > obsv > prv then
  1037     // some other thread raced this thread and installed a new value, in which case
  1037   // some other thread raced this thread and installed a new value, in which case
  1038     // we could either (a) retry the entire operation, (b) retry trying to install now
  1038   // we could either (a) retry the entire operation, (b) retry trying to install now
  1039     // or (c) just return obsv.  We use (c).   No loop is required although in some cases
  1039   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
  1040     // we might discard a higher "now" value in deference to a slightly lower but freshly
  1040   // we might discard a higher "now" value in deference to a slightly lower but freshly
  1041     // installed obsv value.   That's entirely benign -- it admits no new orderings compared
  1041   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
  1042     // to (a) or (b) -- and greatly reduces coherence traffic.
  1042   // to (a) or (b) -- and greatly reduces coherence traffic.
  1043     // We might also condition (c) on the magnitude of the delta between obsv and now.
  1043   // We might also condition (c) on the magnitude of the delta between obsv and now.
  1044     // Avoiding excessive CAS operations to hot RW locations is critical.
  1044   // Avoiding excessive CAS operations to hot RW locations is critical.
  1045     // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
  1045   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
  1046     return (prev == obsv) ? now : obsv;
  1046   return (prev == obsv) ? now : obsv;
  1047 }
  1047 }
  1048 
  1048 
  1049 #else // __APPLE__
  1049 #else // __APPLE__
  1050 
  1050 
  1051 jlong os::javaTimeNanos() {
  1051 jlong os::javaTimeNanos() {
  1174 
  1174 
  1175 // This method is a copy of JDK's sysGetLastErrorString
  1175 // This method is a copy of JDK's sysGetLastErrorString
  1176 // from src/solaris/hpi/src/system_md.c
  1176 // from src/solaris/hpi/src/system_md.c
  1177 
  1177 
  1178 size_t os::lasterror(char *buf, size_t len) {
  1178 size_t os::lasterror(char *buf, size_t len) {
  1179 
       
  1180   if (errno == 0)  return 0;
  1179   if (errno == 0)  return 0;
  1181 
  1180 
  1182   const char *s = ::strerror(errno);
  1181   const char *s = ::strerror(errno);
  1183   size_t n = ::strlen(s);
  1182   size_t n = ::strlen(s);
  1184   if (n >= len) {
  1183   if (n >= len) {
  1244 
  1243 
  1245 // DLL functions
  1244 // DLL functions
  1246 
  1245 
  1247 #define JNI_LIB_PREFIX "lib"
  1246 #define JNI_LIB_PREFIX "lib"
  1248 #ifdef __APPLE__
  1247 #ifdef __APPLE__
  1249 #define JNI_LIB_SUFFIX ".dylib"
  1248   #define JNI_LIB_SUFFIX ".dylib"
  1250 #else
  1249 #else
  1251 #define JNI_LIB_SUFFIX ".so"
  1250   #define JNI_LIB_SUFFIX ".so"
  1252 #endif
  1251 #endif
  1253 
  1252 
  1254 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1253 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
  1255 
  1254 
  1256 // This must be hard coded because it's the system's temporary
  1255 // This must be hard coded because it's the system's temporary
  1267     }
  1266     }
  1268     temp_path = temp_path_storage;
  1267     temp_path = temp_path_storage;
  1269   }
  1268   }
  1270   return temp_path;
  1269   return temp_path;
  1271 }
  1270 }
  1272 #else /* __APPLE__ */
  1271 #else // __APPLE__
  1273 const char* os::get_temp_directory() { return "/tmp"; }
  1272 const char* os::get_temp_directory() { return "/tmp"; }
  1274 #endif /* __APPLE__ */
  1273 #endif // __APPLE__
  1275 
  1274 
  1276 static bool file_exists(const char* filename) {
  1275 static bool file_exists(const char* filename) {
  1277   struct stat statbuf;
  1276   struct stat statbuf;
  1278   if (filename == NULL || strlen(filename) == 0) {
  1277   if (filename == NULL || strlen(filename) == 0) {
  1279     return false;
  1278     return false;
  1305       // Really shouldn't be NULL, but check can't hurt
  1304       // Really shouldn't be NULL, but check can't hurt
  1306       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1305       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1307         continue; // skip the empty path values
  1306         continue; // skip the empty path values
  1308       }
  1307       }
  1309       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1308       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
  1310           pelements[i], fname);
  1309                pelements[i], fname);
  1311       if (file_exists(buffer)) {
  1310       if (file_exists(buffer)) {
  1312         retval = true;
  1311         retval = true;
  1313         break;
  1312         break;
  1314       }
  1313       }
  1315     }
  1314     }
  1370     }
  1369     }
  1371     // no matching symbol so try for just file info
  1370     // no matching symbol so try for just file info
  1372     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1371     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1373       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1372       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1374                           buf, buflen, offset, dlinfo.dli_fname)) {
  1373                           buf, buflen, offset, dlinfo.dli_fname)) {
  1375          return true;
  1374         return true;
  1376       }
  1375       }
  1377     }
  1376     }
  1378 
  1377 
  1379     // Handle non-dynamic manually:
  1378     // Handle non-dynamic manually:
  1380     if (dlinfo.dli_fbase != NULL &&
  1379     if (dlinfo.dli_fbase != NULL &&
  1381         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
  1380         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) {
  1382                         dlinfo.dli_fbase)) {
       
  1383       if (!Decoder::demangle(localbuf, buf, buflen)) {
  1381       if (!Decoder::demangle(localbuf, buf, buflen)) {
  1384         jio_snprintf(buf, buflen, "%s", localbuf);
  1382         jio_snprintf(buf, buflen, "%s", localbuf);
  1385       }
  1383       }
  1386       return true;
  1384       return true;
  1387     }
  1385     }
  1431   ebuf[ebuflen-1]='\0';
  1429   ebuf[ebuflen-1]='\0';
  1432 
  1430 
  1433   return NULL;
  1431   return NULL;
  1434 }
  1432 }
  1435 #else
  1433 #else
  1436 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1434 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
  1437 {
       
  1438   void * result= ::dlopen(filename, RTLD_LAZY);
  1435   void * result= ::dlopen(filename, RTLD_LAZY);
  1439   if (result != NULL) {
  1436   if (result != NULL) {
  1440     // Successful loading
  1437     // Successful loading
  1441     return result;
  1438     return result;
  1442   }
  1439   }
  1463     return NULL;
  1460     return NULL;
  1464   }
  1461   }
  1465 
  1462 
  1466   bool failed_to_read_elf_head=
  1463   bool failed_to_read_elf_head=
  1467     (sizeof(elf_head)!=
  1464     (sizeof(elf_head)!=
  1468         (::read(file_descriptor, &elf_head,sizeof(elf_head))));
  1465      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
  1469 
  1466 
  1470   ::close(file_descriptor);
  1467   ::close(file_descriptor);
  1471   if (failed_to_read_elf_head) {
  1468   if (failed_to_read_elf_head) {
  1472     // file i/o error - report dlerror() msg
  1469     // file i/o error - report dlerror() msg
  1473     return NULL;
  1470     return NULL;
  1480     char        endianess;    // MSB or LSB
  1477     char        endianess;    // MSB or LSB
  1481     char*       name;         // String representation
  1478     char*       name;         // String representation
  1482   } arch_t;
  1479   } arch_t;
  1483 
  1480 
  1484   #ifndef EM_486
  1481   #ifndef EM_486
  1485   #define EM_486          6               /* Intel 80486 */
  1482     #define EM_486          6               /* Intel 80486 */
  1486   #endif
  1483   #endif
  1487 
  1484 
  1488   #ifndef EM_MIPS_RS3_LE
  1485   #ifndef EM_MIPS_RS3_LE
  1489   #define EM_MIPS_RS3_LE  10              /* MIPS */
  1486     #define EM_MIPS_RS3_LE  10              /* MIPS */
  1490   #endif
  1487   #endif
  1491 
  1488 
  1492   #ifndef EM_PPC64
  1489   #ifndef EM_PPC64
  1493   #define EM_PPC64        21              /* PowerPC64 */
  1490     #define EM_PPC64        21              /* PowerPC64 */
  1494   #endif
  1491   #endif
  1495 
  1492 
  1496   #ifndef EM_S390
  1493   #ifndef EM_S390
  1497   #define EM_S390         22              /* IBM System/390 */
  1494     #define EM_S390         22              /* IBM System/390 */
  1498   #endif
  1495   #endif
  1499 
  1496 
  1500   #ifndef EM_IA_64
  1497   #ifndef EM_IA_64
  1501   #define EM_IA_64        50              /* HP/Intel IA-64 */
  1498     #define EM_IA_64        50              /* HP/Intel IA-64 */
  1502   #endif
  1499   #endif
  1503 
  1500 
  1504   #ifndef EM_X86_64
  1501   #ifndef EM_X86_64
  1505   #define EM_X86_64       62              /* AMD x86-64 */
  1502     #define EM_X86_64       62              /* AMD x86-64 */
  1506   #endif
  1503   #endif
  1507 
  1504 
  1508   static const arch_t arch_array[]={
  1505   static const arch_t arch_array[]={
  1509     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1506     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1510     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1507     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1523     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1520     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
  1524     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1521     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
  1525   };
  1522   };
  1526 
  1523 
  1527   #if  (defined IA32)
  1524   #if  (defined IA32)
  1528     static  Elf32_Half running_arch_code=EM_386;
  1525   static  Elf32_Half running_arch_code=EM_386;
  1529   #elif   (defined AMD64)
  1526   #elif   (defined AMD64)
  1530     static  Elf32_Half running_arch_code=EM_X86_64;
  1527   static  Elf32_Half running_arch_code=EM_X86_64;
  1531   #elif  (defined IA64)
  1528   #elif  (defined IA64)
  1532     static  Elf32_Half running_arch_code=EM_IA_64;
  1529   static  Elf32_Half running_arch_code=EM_IA_64;
  1533   #elif  (defined __sparc) && (defined _LP64)
  1530   #elif  (defined __sparc) && (defined _LP64)
  1534     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1531   static  Elf32_Half running_arch_code=EM_SPARCV9;
  1535   #elif  (defined __sparc) && (!defined _LP64)
  1532   #elif  (defined __sparc) && (!defined _LP64)
  1536     static  Elf32_Half running_arch_code=EM_SPARC;
  1533   static  Elf32_Half running_arch_code=EM_SPARC;
  1537   #elif  (defined __powerpc64__)
  1534   #elif  (defined __powerpc64__)
  1538     static  Elf32_Half running_arch_code=EM_PPC64;
  1535   static  Elf32_Half running_arch_code=EM_PPC64;
  1539   #elif  (defined __powerpc__)
  1536   #elif  (defined __powerpc__)
  1540     static  Elf32_Half running_arch_code=EM_PPC;
  1537   static  Elf32_Half running_arch_code=EM_PPC;
  1541   #elif  (defined ARM)
  1538   #elif  (defined ARM)
  1542     static  Elf32_Half running_arch_code=EM_ARM;
  1539   static  Elf32_Half running_arch_code=EM_ARM;
  1543   #elif  (defined S390)
  1540   #elif  (defined S390)
  1544     static  Elf32_Half running_arch_code=EM_S390;
  1541   static  Elf32_Half running_arch_code=EM_S390;
  1545   #elif  (defined ALPHA)
  1542   #elif  (defined ALPHA)
  1546     static  Elf32_Half running_arch_code=EM_ALPHA;
  1543   static  Elf32_Half running_arch_code=EM_ALPHA;
  1547   #elif  (defined MIPSEL)
  1544   #elif  (defined MIPSEL)
  1548     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1545   static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
  1549   #elif  (defined PARISC)
  1546   #elif  (defined PARISC)
  1550     static  Elf32_Half running_arch_code=EM_PARISC;
  1547   static  Elf32_Half running_arch_code=EM_PARISC;
  1551   #elif  (defined MIPS)
  1548   #elif  (defined MIPS)
  1552     static  Elf32_Half running_arch_code=EM_MIPS;
  1549   static  Elf32_Half running_arch_code=EM_MIPS;
  1553   #elif  (defined M68K)
  1550   #elif  (defined M68K)
  1554     static  Elf32_Half running_arch_code=EM_68K;
  1551   static  Elf32_Half running_arch_code=EM_68K;
  1555   #else
  1552   #else
  1556     #error Method os::dll_load requires that one of following is defined:\
  1553     #error Method os::dll_load requires that one of following is defined:\
  1557          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1554          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
  1558   #endif
  1555   #endif
  1559 
  1556 
  1572       lib_arch.name         = arch_array[i].name;
  1569       lib_arch.name         = arch_array[i].name;
  1573     }
  1570     }
  1574   }
  1571   }
  1575 
  1572 
  1576   assert(running_arch_index != -1,
  1573   assert(running_arch_index != -1,
  1577     "Didn't find running architecture code (running_arch_code) in arch_array");
  1574          "Didn't find running architecture code (running_arch_code) in arch_array");
  1578   if (running_arch_index == -1) {
  1575   if (running_arch_index == -1) {
  1579     // Even though running architecture detection failed
  1576     // Even though running architecture detection failed
  1580     // we may still continue with reporting dlerror() message
  1577     // we may still continue with reporting dlerror() message
  1581     return NULL;
  1578     return NULL;
  1582   }
  1579   }
  1594 #endif // !S390
  1591 #endif // !S390
  1595 
  1592 
  1596   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1593   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1597     if (lib_arch.name!=NULL) {
  1594     if (lib_arch.name!=NULL) {
  1598       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1595       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1599         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1596                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1600         lib_arch.name, arch_array[running_arch_index].name);
  1597                  lib_arch.name, arch_array[running_arch_index].name);
  1601     } else {
  1598     } else {
  1602       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1599       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1603       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1600                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1604         lib_arch.code,
  1601                  lib_arch.code,
  1605         arch_array[running_arch_index].name);
  1602                  arch_array[running_arch_index].name);
  1606     }
  1603     }
  1607   }
  1604   }
  1608 
  1605 
  1609   return NULL;
  1606   return NULL;
  1610 }
  1607 }
  1611 #endif /* !__APPLE__ */
  1608 #endif // !__APPLE__
  1612 
  1609 
  1613 void* os::get_default_process_handle() {
  1610 void* os::get_default_process_handle() {
  1614 #ifdef __APPLE__
  1611 #ifdef __APPLE__
  1615   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
  1612   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
  1616   // to avoid finding unexpected symbols on second (or later)
  1613   // to avoid finding unexpected symbols on second (or later)
  1628 
  1625 
  1629 
  1626 
  1630 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1627 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1631   int fd = ::open(filename, O_RDONLY);
  1628   int fd = ::open(filename, O_RDONLY);
  1632   if (fd == -1) {
  1629   if (fd == -1) {
  1633      return false;
  1630     return false;
  1634   }
  1631   }
  1635 
  1632 
  1636   char buf[32];
  1633   char buf[32];
  1637   int bytes;
  1634   int bytes;
  1638   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1635   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1795     return;
  1792     return;
  1796   }
  1793   }
  1797 
  1794 
  1798   char dli_fname[MAXPATHLEN];
  1795   char dli_fname[MAXPATHLEN];
  1799   bool ret = dll_address_to_library_name(
  1796   bool ret = dll_address_to_library_name(
  1800                 CAST_FROM_FN_PTR(address, os::jvm_path),
  1797                                          CAST_FROM_FN_PTR(address, os::jvm_path),
  1801                 dli_fname, sizeof(dli_fname), NULL);
  1798                                          dli_fname, sizeof(dli_fname), NULL);
  1802   assert(ret, "cannot locate libjvm");
  1799   assert(ret, "cannot locate libjvm");
  1803   char *rp = NULL;
  1800   char *rp = NULL;
  1804   if (ret && dli_fname[0] != '\0') {
  1801   if (ret && dli_fname[0] != '\0') {
  1805     rp = realpath(dli_fname, buf);
  1802     rp = realpath(dli_fname, buf);
  1806   }
  1803   }
  1807   if (rp == NULL)
  1804   if (rp == NULL) {
  1808     return;
  1805     return;
       
  1806   }
  1809 
  1807 
  1810   if (Arguments::sun_java_launcher_is_altjvm()) {
  1808   if (Arguments::sun_java_launcher_is_altjvm()) {
  1811     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
  1809     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
  1812     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
  1810     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
  1813     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
  1811     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
  1832         // Check the current module name "libjvm"
  1830         // Check the current module name "libjvm"
  1833         p = strrchr(buf, '/');
  1831         p = strrchr(buf, '/');
  1834         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1832         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1835 
  1833 
  1836         rp = realpath(java_home_var, buf);
  1834         rp = realpath(java_home_var, buf);
  1837         if (rp == NULL)
  1835         if (rp == NULL) {
  1838           return;
  1836           return;
       
  1837         }
  1839 
  1838 
  1840         // determine if this is a legacy image or modules image
  1839         // determine if this is a legacy image or modules image
  1841         // modules image doesn't have "jre" subdirectory
  1840         // modules image doesn't have "jre" subdirectory
  1842         len = strlen(buf);
  1841         len = strlen(buf);
  1843         assert(len < buflen, "Ran out of buffer space");
  1842         assert(len < buflen, "Ran out of buffer space");
  1865           len = strlen(buf);
  1864           len = strlen(buf);
  1866           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1865           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1867         } else {
  1866         } else {
  1868           // Fall back to path of current library
  1867           // Fall back to path of current library
  1869           rp = realpath(dli_fname, buf);
  1868           rp = realpath(dli_fname, buf);
  1870           if (rp == NULL)
  1869           if (rp == NULL) {
  1871             return;
  1870             return;
       
  1871           }
  1872         }
  1872         }
  1873       }
  1873       }
  1874     }
  1874     }
  1875   }
  1875   }
  1876 
  1876 
  1888 ////////////////////////////////////////////////////////////////////////////////
  1888 ////////////////////////////////////////////////////////////////////////////////
  1889 // sun.misc.Signal support
  1889 // sun.misc.Signal support
  1890 
  1890 
  1891 static volatile jint sigint_count = 0;
  1891 static volatile jint sigint_count = 0;
  1892 
  1892 
  1893 static void
  1893 static void UserHandler(int sig, void *siginfo, void *context) {
  1894 UserHandler(int sig, void *siginfo, void *context) {
       
  1895   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1894   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1896   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1895   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1897   // don't want to flood the manager thread with sem_post requests.
  1896   // don't want to flood the manager thread with sem_post requests.
  1898   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1897   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) {
  1899       return;
  1898     return;
       
  1899   }
  1900 
  1900 
  1901   // Ctrl-C is pressed during error reporting, likely because the error
  1901   // Ctrl-C is pressed during error reporting, likely because the error
  1902   // handler fails to abort. Let VM die immediately.
  1902   // handler fails to abort. Let VM die immediately.
  1903   if (sig == SIGINT && is_error_reported()) {
  1903   if (sig == SIGINT && is_error_reported()) {
  1904      os::die();
  1904     os::die();
  1905   }
  1905   }
  1906 
  1906 
  1907   os::signal_notify(sig);
  1907   os::signal_notify(sig);
  1908 }
  1908 }
  1909 
  1909 
  1933 
  1933 
  1934 void os::signal_raise(int signal_number) {
  1934 void os::signal_raise(int signal_number) {
  1935   ::raise(signal_number);
  1935   ::raise(signal_number);
  1936 }
  1936 }
  1937 
  1937 
  1938 /*
  1938 // The following code is moved from os.cpp for making this
  1939  * The following code is moved from os.cpp for making this
  1939 // code platform specific, which it is by its very nature.
  1940  * code platform specific, which it is by its very nature.
       
  1941  */
       
  1942 
  1940 
  1943 // Will be modified when max signal is changed to be dynamic
  1941 // Will be modified when max signal is changed to be dynamic
  1944 int os::sigexitnum_pd() {
  1942 int os::sigexitnum_pd() {
  1945   return NSIG;
  1943   return NSIG;
  1946 }
  1944 }
  1949 static volatile jint pending_signals[NSIG+1] = { 0 };
  1947 static volatile jint pending_signals[NSIG+1] = { 0 };
  1950 
  1948 
  1951 // Bsd(POSIX) specific hand shaking semaphore.
  1949 // Bsd(POSIX) specific hand shaking semaphore.
  1952 #ifdef __APPLE__
  1950 #ifdef __APPLE__
  1953 typedef semaphore_t os_semaphore_t;
  1951 typedef semaphore_t os_semaphore_t;
  1954 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1952 
  1955 #define SEM_WAIT(sem)           semaphore_wait(sem)
  1953   #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1956 #define SEM_POST(sem)           semaphore_signal(sem)
  1954   #define SEM_WAIT(sem)           semaphore_wait(sem)
  1957 #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1955   #define SEM_POST(sem)           semaphore_signal(sem)
       
  1956   #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1958 #else
  1957 #else
  1959 typedef sem_t os_semaphore_t;
  1958 typedef sem_t os_semaphore_t;
  1960 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1959 
  1961 #define SEM_WAIT(sem)           sem_wait(&sem)
  1960   #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1962 #define SEM_POST(sem)           sem_post(&sem)
  1961   #define SEM_WAIT(sem)           sem_wait(&sem)
  1963 #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1962   #define SEM_POST(sem)           sem_post(&sem)
       
  1963   #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1964 #endif
  1964 #endif
  1965 
  1965 
  1966 class Semaphore : public StackObj {
  1966 class Semaphore : public StackObj {
  1967   public:
  1967  public:
  1968     Semaphore();
  1968   Semaphore();
  1969     ~Semaphore();
  1969   ~Semaphore();
  1970     void signal();
  1970   void signal();
  1971     void wait();
  1971   void wait();
  1972     bool trywait();
  1972   bool trywait();
  1973     bool timedwait(unsigned int sec, int nsec);
  1973   bool timedwait(unsigned int sec, int nsec);
  1974   private:
  1974  private:
  1975     jlong currenttime() const;
  1975   jlong currenttime() const;
  1976     os_semaphore_t _semaphore;
  1976   os_semaphore_t _semaphore;
  1977 };
  1977 };
  1978 
  1978 
  1979 Semaphore::Semaphore() : _semaphore(0) {
  1979 Semaphore::Semaphore() : _semaphore(0) {
  1980   SEM_INIT(_semaphore, 0);
  1980   SEM_INIT(_semaphore, 0);
  1981 }
  1981 }
  1991 void Semaphore::wait() {
  1991 void Semaphore::wait() {
  1992   SEM_WAIT(_semaphore);
  1992   SEM_WAIT(_semaphore);
  1993 }
  1993 }
  1994 
  1994 
  1995 jlong Semaphore::currenttime() const {
  1995 jlong Semaphore::currenttime() const {
  1996     struct timeval tv;
  1996   struct timeval tv;
  1997     gettimeofday(&tv, NULL);
  1997   gettimeofday(&tv, NULL);
  1998     return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
  1998   return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
  1999 }
  1999 }
  2000 
  2000 
  2001 #ifdef __APPLE__
  2001 #ifdef __APPLE__
  2002 bool Semaphore::trywait() {
  2002 bool Semaphore::trywait() {
  2003   return timedwait(0, 0);
  2003   return timedwait(0, 0);
  2097       ::SEM_WAIT(sig_sem);
  2097       ::SEM_WAIT(sig_sem);
  2098 
  2098 
  2099       // were we externally suspended while we were waiting?
  2099       // were we externally suspended while we were waiting?
  2100       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  2100       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  2101       if (threadIsSuspended) {
  2101       if (threadIsSuspended) {
  2102         //
       
  2103         // The semaphore has been incremented, but while we were waiting
  2102         // The semaphore has been incremented, but while we were waiting
  2104         // another thread suspended us. We don't want to continue running
  2103         // another thread suspended us. We don't want to continue running
  2105         // while suspended because that would surprise the thread that
  2104         // while suspended because that would surprise the thread that
  2106         // suspended us.
  2105         // suspended us.
  2107         //
       
  2108         ::SEM_POST(sig_sem);
  2106         ::SEM_POST(sig_sem);
  2109 
  2107 
  2110         thread->java_suspend_self();
  2108         thread->java_suspend_self();
  2111       }
  2109       }
  2112     } while (threadIsSuspended);
  2110     } while (threadIsSuspended);
  2190   if (::mprotect(addr, size, prot) == 0) {
  2188   if (::mprotect(addr, size, prot) == 0) {
  2191     return true;
  2189     return true;
  2192   }
  2190   }
  2193 #else
  2191 #else
  2194   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2192   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
  2195                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2193                                      MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
  2196   if (res != (uintptr_t) MAP_FAILED) {
  2194   if (res != (uintptr_t) MAP_FAILED) {
  2197     return true;
  2195     return true;
  2198   }
  2196   }
  2199 #endif
  2197 #endif
  2200 
  2198 
  2204 
  2202 
  2205   return false;
  2203   return false;
  2206 }
  2204 }
  2207 
  2205 
  2208 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2206 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
  2209                        bool exec) {
  2207                           bool exec) {
  2210   // alignment_hint is ignored on this OS
  2208   // alignment_hint is ignored on this OS
  2211   return pd_commit_memory(addr, size, exec);
  2209   return pd_commit_memory(addr, size, exec);
  2212 }
  2210 }
  2213 
  2211 
  2214 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
  2212 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
  2272 #ifdef __OpenBSD__
  2270 #ifdef __OpenBSD__
  2273   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2271   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
  2274   return ::mprotect(addr, size, PROT_NONE) == 0;
  2272   return ::mprotect(addr, size, PROT_NONE) == 0;
  2275 #else
  2273 #else
  2276   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2274   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
  2277                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2275                                      MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
  2278   return res  != (uintptr_t) MAP_FAILED;
  2276   return res  != (uintptr_t) MAP_FAILED;
  2279 #endif
  2277 #endif
  2280 }
  2278 }
  2281 
  2279 
  2282 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2280 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2333 static int anon_munmap(char * addr, size_t size) {
  2331 static int anon_munmap(char * addr, size_t size) {
  2334   return ::munmap(addr, size) == 0;
  2332   return ::munmap(addr, size) == 0;
  2335 }
  2333 }
  2336 
  2334 
  2337 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2335 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
  2338                          size_t alignment_hint) {
  2336                             size_t alignment_hint) {
  2339   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2337   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
  2340 }
  2338 }
  2341 
  2339 
  2342 bool os::pd_release_memory(char* addr, size_t size) {
  2340 bool os::pd_release_memory(char* addr, size_t size) {
  2343   return anon_munmap(addr, size);
  2341   return anon_munmap(addr, size);
  2403 
  2401 
  2404   key_t key = IPC_PRIVATE;
  2402   key_t key = IPC_PRIVATE;
  2405   char *addr;
  2403   char *addr;
  2406 
  2404 
  2407   bool warn_on_failure = UseLargePages &&
  2405   bool warn_on_failure = UseLargePages &&
  2408                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2406                          (!FLAG_IS_DEFAULT(UseLargePages) ||
  2409                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2407                           !FLAG_IS_DEFAULT(LargePageSizeInBytes));
  2410                         );
       
  2411 
  2408 
  2412   // Create a large shared memory region to attach to based on size.
  2409   // Create a large shared memory region to attach to based on size.
  2413   // Currently, size is the total size of the heap
  2410   // Currently, size is the total size of the heap
  2414   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2411   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2415   if (shmid == -1) {
  2412   if (shmid == -1) {
  2416      // Possible reasons for shmget failure:
  2413     // Possible reasons for shmget failure:
  2417      // 1. shmmax is too small for Java heap.
  2414     // 1. shmmax is too small for Java heap.
  2418      //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2415     //    > check shmmax value: cat /proc/sys/kernel/shmmax
  2419      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2416     //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
  2420      // 2. not enough large page memory.
  2417     // 2. not enough large page memory.
  2421      //    > check available large pages: cat /proc/meminfo
  2418     //    > check available large pages: cat /proc/meminfo
  2422      //    > increase amount of large pages:
  2419     //    > increase amount of large pages:
  2423      //          echo new_value > /proc/sys/vm/nr_hugepages
  2420     //          echo new_value > /proc/sys/vm/nr_hugepages
  2424      //      Note 1: different Bsd may use different name for this property,
  2421     //      Note 1: different Bsd may use different name for this property,
  2425      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2422     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
  2426      //      Note 2: it's possible there's enough physical memory available but
  2423     //      Note 2: it's possible there's enough physical memory available but
  2427      //            they are so fragmented after a long run that they can't
  2424     //            they are so fragmented after a long run that they can't
  2428      //            coalesce into large pages. Try to reserve large pages when
  2425     //            coalesce into large pages. Try to reserve large pages when
  2429      //            the system is still "fresh".
  2426     //            the system is still "fresh".
  2430      if (warn_on_failure) {
  2427     if (warn_on_failure) {
  2431        warning("Failed to reserve shared memory (errno = %d).", errno);
  2428       warning("Failed to reserve shared memory (errno = %d).", errno);
  2432      }
  2429     }
  2433      return NULL;
  2430     return NULL;
  2434   }
  2431   }
  2435 
  2432 
  2436   // attach to the region
  2433   // attach to the region
  2437   addr = (char*)shmat(shmid, req_addr, 0);
  2434   addr = (char*)shmat(shmid, req_addr, 0);
  2438   int err = errno;
  2435   int err = errno;
  2442   // terminates. If shmat() is not successful this will remove the shared
  2439   // terminates. If shmat() is not successful this will remove the shared
  2443   // segment immediately.
  2440   // segment immediately.
  2444   shmctl(shmid, IPC_RMID, NULL);
  2441   shmctl(shmid, IPC_RMID, NULL);
  2445 
  2442 
  2446   if ((intptr_t)addr == -1) {
  2443   if ((intptr_t)addr == -1) {
  2447      if (warn_on_failure) {
  2444     if (warn_on_failure) {
  2448        warning("Failed to attach shared memory (errno = %d).", err);
  2445       warning("Failed to attach shared memory (errno = %d).", err);
  2449      }
  2446     }
  2450      return NULL;
  2447     return NULL;
  2451   }
  2448   }
  2452 
  2449 
  2453   // The memory is committed
  2450   // The memory is committed
  2454   MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);
  2451   MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);
  2455 
  2452 
  2516 
  2513 
  2517   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2514   // Bsd mmap allows caller to pass an address as hint; give it a try first,
  2518   // if kernel honors the hint then we can return immediately.
  2515   // if kernel honors the hint then we can return immediately.
  2519   char * addr = anon_mmap(requested_addr, bytes, false);
  2516   char * addr = anon_mmap(requested_addr, bytes, false);
  2520   if (addr == requested_addr) {
  2517   if (addr == requested_addr) {
  2521      return requested_addr;
  2518     return requested_addr;
  2522   }
  2519   }
  2523 
  2520 
  2524   if (addr != NULL) {
  2521   if (addr != NULL) {
  2525      // mmap() is successful but it fails to reserve at the requested address
  2522     // mmap() is successful but it fails to reserve at the requested address
  2526      anon_munmap(addr, bytes);
  2523     anon_munmap(addr, bytes);
  2527   }
  2524   }
  2528 
  2525 
  2529   int i;
  2526   int i;
  2530   for (i = 0; i < max_tries; ++i) {
  2527   for (i = 0; i < max_tries; ++i) {
  2531     base[i] = reserve_memory(bytes);
  2528     base[i] = reserve_memory(bytes);
  2583 
  2580 
  2584   assert(ms < 1000, "Un-interruptable sleep, short time use only");
  2581   assert(ms < 1000, "Un-interruptable sleep, short time use only");
  2585   req.tv_sec = 0;
  2582   req.tv_sec = 0;
  2586   if (ms > 0) {
  2583   if (ms > 0) {
  2587     req.tv_nsec = (ms % 1000) * 1000000;
  2584     req.tv_nsec = (ms % 1000) * 1000000;
  2588   }
  2585   } else {
  2589   else {
       
  2590     req.tv_nsec = 1;
  2586     req.tv_nsec = 1;
  2591   }
  2587   }
  2592 
  2588 
  2593   nanosleep(&req, NULL);
  2589   nanosleep(&req, NULL);
  2594 
  2590 
  2647   31,              // 10 MaxPriority
  2643   31,              // 10 MaxPriority
  2648 
  2644 
  2649   31               // 11 CriticalPriority
  2645   31               // 11 CriticalPriority
  2650 };
  2646 };
  2651 #else
  2647 #else
  2652 /* Using Mach high-level priority assignments */
  2648 // Using Mach high-level priority assignments
  2653 int os::java_to_os_priority[CriticalPriority + 1] = {
  2649 int os::java_to_os_priority[CriticalPriority + 1] = {
  2654    0,              // 0 Entry should never be used (MINPRI_USER)
  2650    0,              // 0 Entry should never be used (MINPRI_USER)
  2655 
  2651 
  2656   27,              // 1 MinPriority
  2652   27,              // 1 MinPriority
  2657   28,              // 2
  2653   28,              // 2
  2700 #elif defined(__APPLE__) || defined(__NetBSD__)
  2696 #elif defined(__APPLE__) || defined(__NetBSD__)
  2701   struct sched_param sp;
  2697   struct sched_param sp;
  2702   int policy;
  2698   int policy;
  2703   pthread_t self = pthread_self();
  2699   pthread_t self = pthread_self();
  2704 
  2700 
  2705   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2701   if (pthread_getschedparam(self, &policy, &sp) != 0) {
  2706     return OS_ERR;
  2702     return OS_ERR;
       
  2703   }
  2707 
  2704 
  2708   sp.sched_priority = newpri;
  2705   sp.sched_priority = newpri;
  2709   if (pthread_setschedparam(self, policy, &sp) != 0)
  2706   if (pthread_setschedparam(self, policy, &sp) != 0) {
  2710     return OS_ERR;
  2707     return OS_ERR;
       
  2708   }
  2711 
  2709 
  2712   return OS_OK;
  2710   return OS_OK;
  2713 #else
  2711 #else
  2714   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2712   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2715   return (ret == 0) ? OS_OK : OS_ERR;
  2713   return (ret == 0) ? OS_OK : OS_ERR;
  2761 //  - resume:
  2759 //  - resume:
  2762 //      - sets target osthread state to continue
  2760 //      - sets target osthread state to continue
  2763 //      - sends signal to end the sigsuspend loop in the SR_handler
  2761 //      - sends signal to end the sigsuspend loop in the SR_handler
  2764 //
  2762 //
  2765 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2763 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2766 //
       
  2767 
  2764 
  2768 static void resume_clear_context(OSThread *osthread) {
  2765 static void resume_clear_context(OSThread *osthread) {
  2769   osthread->set_ucontext(NULL);
  2766   osthread->set_ucontext(NULL);
  2770   osthread->set_siginfo(NULL);
  2767   osthread->set_siginfo(NULL);
  2771 }
  2768 }
  2773 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2770 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2774   osthread->set_ucontext(context);
  2771   osthread->set_ucontext(context);
  2775   osthread->set_siginfo(siginfo);
  2772   osthread->set_siginfo(siginfo);
  2776 }
  2773 }
  2777 
  2774 
  2778 //
       
  2779 // Handler function invoked when a thread's execution is suspended or
  2775 // Handler function invoked when a thread's execution is suspended or
  2780 // resumed. We have to be careful that only async-safe functions are
  2776 // resumed. We have to be careful that only async-safe functions are
  2781 // called here (Note: most pthread functions are not async safe and
  2777 // called here (Note: most pthread functions are not async safe and
  2782 // should be avoided.)
  2778 // should be avoided.)
  2783 //
  2779 //
  2845 
  2841 
  2846 
  2842 
  2847 static int SR_initialize() {
  2843 static int SR_initialize() {
  2848   struct sigaction act;
  2844   struct sigaction act;
  2849   char *s;
  2845   char *s;
  2850   /* Get signal number to use for suspend/resume */
  2846   // Get signal number to use for suspend/resume
  2851   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2847   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2852     int sig = ::strtol(s, 0, 10);
  2848     int sig = ::strtol(s, 0, 10);
  2853     if (sig > 0 || sig < NSIG) {
  2849     if (sig > 0 || sig < NSIG) {
  2854         SR_signum = sig;
  2850       SR_signum = sig;
  2855     }
  2851     }
  2856   }
  2852   }
  2857 
  2853 
  2858   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2854   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
  2859         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2855          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2860 
  2856 
  2861   sigemptyset(&SR_sigset);
  2857   sigemptyset(&SR_sigset);
  2862   sigaddset(&SR_sigset, SR_signum);
  2858   sigaddset(&SR_sigset, SR_signum);
  2863 
  2859 
  2864   /* Set up signal handler for suspend/resume */
  2860   // Set up signal handler for suspend/resume
  2865   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2861   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2866   act.sa_handler = (void (*)(int)) SR_handler;
  2862   act.sa_handler = (void (*)(int)) SR_handler;
  2867 
  2863 
  2868   // SR_signum is blocked by default.
  2864   // SR_signum is blocked by default.
  2869   // 4528190 - We also need to block pthread restart signal (32 on all
  2865   // 4528190 - We also need to block pthread restart signal (32 on all
  2985 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2981 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2986 //
  2982 //
  2987 // Note that the VM will print warnings if it detects conflicting signal
  2983 // Note that the VM will print warnings if it detects conflicting signal
  2988 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2984 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2989 //
  2985 //
  2990 extern "C" JNIEXPORT int
  2986 extern "C" JNIEXPORT int JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2991 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2987                                                void* ucontext,
  2992                         void* ucontext, int abort_if_unrecognized);
  2988                                                int abort_if_unrecognized);
  2993 
  2989 
  2994 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2990 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2995   assert(info != NULL && uc != NULL, "it must be old kernel");
  2991   assert(info != NULL && uc != NULL, "it must be old kernel");
  2996   int orig_errno = errno;  // Preserve errno value over signal handler.
  2992   int orig_errno = errno;  // Preserve errno value over signal handler.
  2997   JVM_handle_bsd_signal(sig, info, uc, true);
  2993   JVM_handle_bsd_signal(sig, info, uc, true);
  3178     // signal-chaining
  3174     // signal-chaining
  3179     typedef void (*signal_setting_t)();
  3175     typedef void (*signal_setting_t)();
  3180     signal_setting_t begin_signal_setting = NULL;
  3176     signal_setting_t begin_signal_setting = NULL;
  3181     signal_setting_t end_signal_setting = NULL;
  3177     signal_setting_t end_signal_setting = NULL;
  3182     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3178     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3183                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3179                                           dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  3184     if (begin_signal_setting != NULL) {
  3180     if (begin_signal_setting != NULL) {
  3185       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3181       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  3186                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3182                                           dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  3187       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3183       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  3188                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3184                                          dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  3189       libjsig_is_loaded = true;
  3185       libjsig_is_loaded = true;
  3190       assert(UseSignalChaining, "should enable signal-chaining");
  3186       assert(UseSignalChaining, "should enable signal-chaining");
  3191     }
  3187     }
  3192     if (libjsig_is_loaded) {
  3188     if (libjsig_is_loaded) {
  3193       // Tell libjsig jvm is setting signal handlers
  3189       // Tell libjsig jvm is setting signal handlers
  3213     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3209     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
  3214     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3210     // handlers. By replacing the existing task exception handler, we disable gdb's mach
  3215     // exception handling, while leaving the standard BSD signal handlers functional.
  3211     // exception handling, while leaving the standard BSD signal handlers functional.
  3216     kern_return_t kr;
  3212     kern_return_t kr;
  3217     kr = task_set_exception_ports(mach_task_self(),
  3213     kr = task_set_exception_ports(mach_task_self(),
  3218         EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3214                                   EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
  3219         MACH_PORT_NULL,
  3215                                   MACH_PORT_NULL,
  3220         EXCEPTION_STATE_IDENTITY,
  3216                                   EXCEPTION_STATE_IDENTITY,
  3221         MACHINE_THREAD_STATE);
  3217                                   MACHINE_THREAD_STATE);
  3222 
  3218 
  3223     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3219     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
  3224 #endif
  3220 #endif
  3225 
  3221 
  3226     if (libjsig_is_loaded) {
  3222     if (libjsig_is_loaded) {
  3253 // to indicate, that some special sort of signal
  3249 // to indicate, that some special sort of signal
  3254 // trampoline is used.
  3250 // trampoline is used.
  3255 // We will never set this flag, and we should
  3251 // We will never set this flag, and we should
  3256 // ignore this flag in our diagnostic
  3252 // ignore this flag in our diagnostic
  3257 #ifdef SIGNIFICANT_SIGNAL_MASK
  3253 #ifdef SIGNIFICANT_SIGNAL_MASK
  3258 #undef SIGNIFICANT_SIGNAL_MASK
  3254   #undef SIGNIFICANT_SIGNAL_MASK
  3259 #endif
  3255 #endif
  3260 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3256 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3261 
  3257 
  3262 static const char* get_signal_handler_name(address handler,
  3258 static const char* get_signal_handler_name(address handler,
  3263                                            char* buf, int buflen) {
  3259                                            char* buf, int buflen) {
  3312   st->print(", sa_flags=");
  3308   st->print(", sa_flags=");
  3313   os::Posix::print_sa_flags(st, sa.sa_flags);
  3309   os::Posix::print_sa_flags(st, sa.sa_flags);
  3314 
  3310 
  3315   // Check: is it our handler?
  3311   // Check: is it our handler?
  3316   if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3312   if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
  3317      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3313       handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
  3318     // It is our signal handler
  3314     // It is our signal handler
  3319     // check for flags, reset system-used one!
  3315     // check for flags, reset system-used one!
  3320     if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3316     if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
  3321       st->print(
  3317       st->print(
  3322                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3318                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  3325   }
  3321   }
  3326   st->cr();
  3322   st->cr();
  3327 }
  3323 }
  3328 
  3324 
  3329 
  3325 
  3330 #define DO_SIGNAL_CHECK(sig) \
  3326 #define DO_SIGNAL_CHECK(sig)                      \
  3331   if (!sigismember(&check_signal_done, sig)) \
  3327   do {                                            \
  3332     os::Bsd::check_signal_handler(sig)
  3328     if (!sigismember(&check_signal_done, sig)) {  \
       
  3329       os::Bsd::check_signal_handler(sig);         \
       
  3330     }                                             \
       
  3331   } while (0)
  3333 
  3332 
  3334 // This method is a periodic task to check for misbehaving JNI applications
  3333 // This method is a periodic task to check for misbehaving JNI applications
  3335 // under CheckJNI, we can add any periodic checks here
  3334 // under CheckJNI, we can add any periodic checks here
  3336 
  3335 
  3337 void os::run_periodic_checks() {
  3336 void os::run_periodic_checks() {
  3442   if (sigismember(&check_signal_done, sig)) {
  3441   if (sigismember(&check_signal_done, sig)) {
  3443     print_signal_handlers(tty, buf, O_BUFLEN);
  3442     print_signal_handlers(tty, buf, O_BUFLEN);
  3444   }
  3443   }
  3445 }
  3444 }
  3446 
  3445 
  3447 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3446 extern void report_error(char* file_name, int line_no, char* title,
       
  3447                          char* format, ...);
  3448 
  3448 
  3449 extern bool signal_name(int signo, char* buf, size_t len);
  3449 extern bool signal_name(int signo, char* buf, size_t len);
  3450 
  3450 
  3451 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3451 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3452   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3452   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3460   }
  3460   }
  3461 }
  3461 }
  3462 
  3462 
  3463 // this is called _before_ the most of global arguments have been parsed
  3463 // this is called _before_ the most of global arguments have been parsed
  3464 void os::init(void) {
  3464 void os::init(void) {
  3465   char dummy;   /* used to get a guess on initial stack address */
  3465   char dummy;   // used to get a guess on initial stack address
  3466 //  first_hrtime = gethrtime();
  3466 //  first_hrtime = gethrtime();
  3467 
  3467 
  3468   // With BsdThreads the JavaMain thread pid (primordial thread)
  3468   // With BsdThreads the JavaMain thread pid (primordial thread)
  3469   // is different than the pid of the java launcher thread.
  3469   // is different than the pid of the java launcher thread.
  3470   // So, on Bsd, the launcher thread pid is passed to the VM
  3470   // So, on Bsd, the launcher thread pid is passed to the VM
  3513     perfMemory_exit();
  3513     perfMemory_exit();
  3514   }
  3514   }
  3515 }
  3515 }
  3516 
  3516 
  3517 // this is called _after_ the global arguments have been parsed
  3517 // this is called _after_ the global arguments have been parsed
  3518 jint os::init_2(void)
  3518 jint os::init_2(void) {
  3519 {
       
  3520   // Allocate a single page and mark it as readable for safepoint polling
  3519   // Allocate a single page and mark it as readable for safepoint polling
  3521   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3520   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3522   guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page");
  3521   guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page");
  3523 
  3522 
  3524   os::set_polling_page(polling_page);
  3523   os::set_polling_page(polling_page);
  3525 
  3524 
  3526 #ifndef PRODUCT
  3525 #ifndef PRODUCT
  3527   if (Verbose && PrintMiscellaneous)
  3526   if (Verbose && PrintMiscellaneous) {
  3528     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3527     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n",
       
  3528                (intptr_t)polling_page);
       
  3529   }
  3529 #endif
  3530 #endif
  3530 
  3531 
  3531   if (!UseMembar) {
  3532   if (!UseMembar) {
  3532     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3533     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3533     guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3534     guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3534     os::set_memory_serialize_page(mem_serialize_page);
  3535     os::set_memory_serialize_page(mem_serialize_page);
  3535 
  3536 
  3536 #ifndef PRODUCT
  3537 #ifndef PRODUCT
  3537     if (Verbose && PrintMiscellaneous)
  3538     if (Verbose && PrintMiscellaneous) {
  3538       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3539       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n",
       
  3540                  (intptr_t)mem_serialize_page);
       
  3541     }
  3539 #endif
  3542 #endif
  3540   }
  3543   }
  3541 
  3544 
  3542   // initialize suspend/resume support - must do this before signal_sets_init()
  3545   // initialize suspend/resume support - must do this before signal_sets_init()
  3543   if (SR_initialize() != 0) {
  3546   if (SR_initialize() != 0) {
  3552   // the java system classes, including StackOverflowError - depends on page
  3555   // the java system classes, including StackOverflowError - depends on page
  3553   // size.  Add a page for compiler2 recursion in main thread.
  3556   // size.  Add a page for compiler2 recursion in main thread.
  3554   // Add in 2*BytesPerWord times page size to account for VM stack during
  3557   // Add in 2*BytesPerWord times page size to account for VM stack during
  3555   // class initialization depending on 32 or 64 bit VM.
  3558   // class initialization depending on 32 or 64 bit VM.
  3556   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3559   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
  3557             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3560                                     (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  3558                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3561                                     2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
  3559 
  3562 
  3560   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3563   size_t threadStackSizeInBytes = ThreadStackSize * K;
  3561   if (threadStackSizeInBytes != 0 &&
  3564   if (threadStackSizeInBytes != 0 &&
  3562       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3565       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
  3563         tty->print_cr("\nThe stack size specified is too small, "
  3566     tty->print_cr("\nThe stack size specified is too small, "
  3564                       "Specify at least %dk",
  3567                   "Specify at least %dk",
  3565                       os::Bsd::min_stack_allowed/ K);
  3568                   os::Bsd::min_stack_allowed/ K);
  3566         return JNI_ERR;
  3569     return JNI_ERR;
  3567   }
  3570   }
  3568 
  3571 
  3569   // Make the stack size a multiple of the page size so that
  3572   // Make the stack size a multiple of the page size so that
  3570   // the yellow/red zones can be guarded.
  3573   // the yellow/red zones can be guarded.
  3571   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3574   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  3572         vm_page_size()));
  3575                                                 vm_page_size()));
  3573 
  3576 
  3574   if (MaxFDLimit) {
  3577   if (MaxFDLimit) {
  3575     // set the number of file descriptors to max. print out error
  3578     // set the number of file descriptors to max. print out error
  3576     // if getrlimit/setrlimit fails but continue regardless.
  3579     // if getrlimit/setrlimit fails but continue regardless.
  3577     struct rlimit nbr_files;
  3580     struct rlimit nbr_files;
  3578     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3581     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3579     if (status != 0) {
  3582     if (status != 0) {
  3580       if (PrintMiscellaneous && (Verbose || WizardMode))
  3583       if (PrintMiscellaneous && (Verbose || WizardMode)) {
  3581         perror("os::init_2 getrlimit failed");
  3584         perror("os::init_2 getrlimit failed");
       
  3585       }
  3582     } else {
  3586     } else {
  3583       nbr_files.rlim_cur = nbr_files.rlim_max;
  3587       nbr_files.rlim_cur = nbr_files.rlim_max;
  3584 
  3588 
  3585 #ifdef __APPLE__
  3589 #ifdef __APPLE__
  3586       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3590       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3589       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3593       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3590 #endif
  3594 #endif
  3591 
  3595 
  3592       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3596       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3593       if (status != 0) {
  3597       if (status != 0) {
  3594         if (PrintMiscellaneous && (Verbose || WizardMode))
  3598         if (PrintMiscellaneous && (Verbose || WizardMode)) {
  3595           perror("os::init_2 setrlimit failed");
  3599           perror("os::init_2 setrlimit failed");
       
  3600         }
  3596       }
  3601       }
  3597     }
  3602     }
  3598   }
  3603   }
  3599 
  3604 
  3600   // at-exit methods are called in the reverse order of their registration.
  3605   // at-exit methods are called in the reverse order of their registration.
  3633 // this is called at the end of vm_initialization
  3638 // this is called at the end of vm_initialization
  3634 void os::init_3(void) { }
  3639 void os::init_3(void) { }
  3635 
  3640 
  3636 // Mark the polling page as unreadable
  3641 // Mark the polling page as unreadable
  3637 void os::make_polling_page_unreadable(void) {
  3642 void os::make_polling_page_unreadable(void) {
  3638   if (!guard_memory((char*)_polling_page, Bsd::page_size()))
  3643   if (!guard_memory((char*)_polling_page, Bsd::page_size())) {
  3639     fatal("Could not disable polling page");
  3644     fatal("Could not disable polling page");
  3640 };
  3645   }
       
  3646 }
  3641 
  3647 
  3642 // Mark the polling page as readable
  3648 // Mark the polling page as readable
  3643 void os::make_polling_page_readable(void) {
  3649 void os::make_polling_page_readable(void) {
  3644   if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3650   if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3645     fatal("Could not enable polling page");
  3651     fatal("Could not enable polling page");
  3646   }
  3652   }
  3647 };
  3653 }
  3648 
  3654 
  3649 int os::active_processor_count() {
  3655 int os::active_processor_count() {
  3650   return _processor_count;
  3656   return _processor_count;
  3651 }
  3657 }
  3652 
  3658 
  3680   }
  3686   }
  3681 }
  3687 }
  3682 
  3688 
  3683 ///
  3689 ///
  3684 class PcFetcher : public os::SuspendedThreadTask {
  3690 class PcFetcher : public os::SuspendedThreadTask {
  3685 public:
  3691  public:
  3686   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
  3692   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
  3687   ExtendedPC result();
  3693   ExtendedPC result();
  3688 protected:
  3694  protected:
  3689   void do_task(const os::SuspendedThreadTaskContext& context);
  3695   void do_task(const os::SuspendedThreadTaskContext& context);
  3690 private:
  3696  private:
  3691   ExtendedPC _epc;
  3697   ExtendedPC _epc;
  3692 };
  3698 };
  3693 
  3699 
  3694 ExtendedPC PcFetcher::result() {
  3700 ExtendedPC PcFetcher::result() {
  3695   guarantee(is_done(), "task is not done yet.");
  3701   guarantee(is_done(), "task is not done yet.");
  3717   PcFetcher fetcher(thread);
  3723   PcFetcher fetcher(thread);
  3718   fetcher.run();
  3724   fetcher.run();
  3719   return fetcher.result();
  3725   return fetcher.result();
  3720 }
  3726 }
  3721 
  3727 
  3722 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3728 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond,
  3723 {
  3729                                  pthread_mutex_t *_mutex,
       
  3730                                  const struct timespec *_abstime) {
  3724   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3731   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3725 }
  3732 }
  3726 
  3733 
  3727 ////////////////////////////////////////////////////////////////////////////////
  3734 ////////////////////////////////////////////////////////////////////////////////
  3728 // debug support
  3735 // debug support
  3732   memset(&dlinfo, 0, sizeof(dlinfo));
  3739   memset(&dlinfo, 0, sizeof(dlinfo));
  3733   if (dladdr(addr, &dlinfo) != 0) {
  3740   if (dladdr(addr, &dlinfo) != 0) {
  3734     st->print(PTR_FORMAT ": ", addr);
  3741     st->print(PTR_FORMAT ": ", addr);
  3735     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
  3742     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
  3736       st->print("%s+%#x", dlinfo.dli_sname,
  3743       st->print("%s+%#x", dlinfo.dli_sname,
  3737                  addr - (intptr_t)dlinfo.dli_saddr);
  3744                 addr - (intptr_t)dlinfo.dli_saddr);
  3738     } else if (dlinfo.dli_fbase != NULL) {
  3745     } else if (dlinfo.dli_fbase != NULL) {
  3739       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3746       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
  3740     } else {
  3747     } else {
  3741       st->print("<absolute address>");
  3748       st->print("<absolute address>");
  3742     }
  3749     }
  3755       address       lowest = (address) dlinfo.dli_sname;
  3762       address       lowest = (address) dlinfo.dli_sname;
  3756       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3763       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3757       if (begin < lowest)  begin = lowest;
  3764       if (begin < lowest)  begin = lowest;
  3758       Dl_info dlinfo2;
  3765       Dl_info dlinfo2;
  3759       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3766       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3760           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3767           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
  3761         end = (address) dlinfo2.dli_saddr;
  3768         end = (address) dlinfo2.dli_saddr;
       
  3769       }
  3762       Disassembler::decode(begin, end, st);
  3770       Disassembler::decode(begin, end, st);
  3763     }
  3771     }
  3764     return true;
  3772     return true;
  3765   }
  3773   }
  3766   return false;
  3774   return false;
  3770 // misc
  3778 // misc
  3771 
  3779 
  3772 // This does not do anything on Bsd. This is basically a hook for being
  3780 // This does not do anything on Bsd. This is basically a hook for being
  3773 // able to use structured exception handling (thread-local exception filters)
  3781 // able to use structured exception handling (thread-local exception filters)
  3774 // on, e.g., Win32.
  3782 // on, e.g., Win32.
  3775 void
  3783 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
  3776 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3784                               methodHandle* method, JavaCallArguments* args,
  3777                          JavaCallArguments* args, Thread* thread) {
  3785                               Thread* thread) {
  3778   f(value, method, args, thread);
  3786   f(value, method, args, thread);
  3779 }
  3787 }
  3780 
  3788 
  3781 void os::print_statistics() {
  3789 void os::print_statistics() {
  3782 }
  3790 }
  3820   struct dirent *ptr;
  3828   struct dirent *ptr;
  3821 
  3829 
  3822   dir = opendir(path);
  3830   dir = opendir(path);
  3823   if (dir == NULL) return true;
  3831   if (dir == NULL) return true;
  3824 
  3832 
  3825   /* Scan the directory */
  3833   // Scan the directory
  3826   bool result = true;
  3834   bool result = true;
  3827   char buf[sizeof(struct dirent) + MAX_PATH];
  3835   char buf[sizeof(struct dirent) + MAX_PATH];
  3828   while (result && (ptr = ::readdir(dir)) != NULL) {
  3836   while (result && (ptr = ::readdir(dir)) != NULL) {
  3829     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3837     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3830       result = false;
  3838       result = false;
  3836 
  3844 
  3837 // This code originates from JDK's sysOpen and open64_w
  3845 // This code originates from JDK's sysOpen and open64_w
  3838 // from src/solaris/hpi/src/system_md.c
  3846 // from src/solaris/hpi/src/system_md.c
  3839 
  3847 
  3840 #ifndef O_DELETE
  3848 #ifndef O_DELETE
  3841 #define O_DELETE 0x10000
  3849   #define O_DELETE 0x10000
  3842 #endif
  3850 #endif
  3843 
  3851 
  3844 // Open a file. Unlink the file immediately after open returns
  3852 // Open a file. Unlink the file immediately after open returns
  3845 // if the specified oflag has the O_DELETE flag set.
  3853 // if the specified oflag has the O_DELETE flag set.
  3846 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3854 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3847 
  3855 
  3848 int os::open(const char *path, int oflag, int mode) {
  3856 int os::open(const char *path, int oflag, int mode) {
  3849 
       
  3850   if (strlen(path) > MAX_PATH - 1) {
  3857   if (strlen(path) > MAX_PATH - 1) {
  3851     errno = ENAMETOOLONG;
  3858     errno = ENAMETOOLONG;
  3852     return -1;
  3859     return -1;
  3853   }
  3860   }
  3854   int fd;
  3861   int fd;
  3856   oflag = oflag & ~O_DELETE;
  3863   oflag = oflag & ~O_DELETE;
  3857 
  3864 
  3858   fd = ::open(path, oflag, mode);
  3865   fd = ::open(path, oflag, mode);
  3859   if (fd == -1) return -1;
  3866   if (fd == -1) return -1;
  3860 
  3867 
  3861   //If the open succeeded, the file might still be a directory
  3868   // If the open succeeded, the file might still be a directory
  3862   {
  3869   {
  3863     struct stat buf;
  3870     struct stat buf;
  3864     int ret = ::fstat(fd, &buf);
  3871     int ret = ::fstat(fd, &buf);
  3865     int st_mode = buf.st_mode;
  3872     int st_mode = buf.st_mode;
  3866 
  3873 
  3874       ::close(fd);
  3881       ::close(fd);
  3875       return -1;
  3882       return -1;
  3876     }
  3883     }
  3877   }
  3884   }
  3878 
  3885 
  3879     /*
  3886   // All file descriptors that are opened in the JVM and not
  3880      * All file descriptors that are opened in the JVM and not
  3887   // specifically destined for a subprocess should have the
  3881      * specifically destined for a subprocess should have the
  3888   // close-on-exec flag set.  If we don't set it, then careless 3rd
  3882      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3889   // party native code might fork and exec without closing all
  3883      * party native code might fork and exec without closing all
  3890   // appropriate file descriptors (e.g. as we do in closeDescriptors in
  3884      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3891   // UNIXProcess.c), and this in turn might:
  3885      * UNIXProcess.c), and this in turn might:
  3892   //
  3886      *
  3893   // - cause end-of-file to fail to be detected on some file
  3887      * - cause end-of-file to fail to be detected on some file
  3894   //   descriptors, resulting in mysterious hangs, or
  3888      *   descriptors, resulting in mysterious hangs, or
  3895   //
  3889      *
  3896   // - might cause an fopen in the subprocess to fail on a system
  3890      * - might cause an fopen in the subprocess to fail on a system
  3897   //   suffering from bug 1085341.
  3891      *   suffering from bug 1085341.
  3898   //
  3892      *
  3899   // (Yes, the default setting of the close-on-exec flag is a Unix
  3893      * (Yes, the default setting of the close-on-exec flag is a Unix
  3900   // design flaw)
  3894      * design flaw)
  3901   //
  3895      *
  3902   // See:
  3896      * See:
  3903   // 1085341: 32-bit stdio routines should support file descriptors >255
  3897      * 1085341: 32-bit stdio routines should support file descriptors >255
  3904   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3898      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3905   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3899      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3906   //
  3900      */
       
  3901 #ifdef FD_CLOEXEC
  3907 #ifdef FD_CLOEXEC
  3902     {
  3908   {
  3903         int flags = ::fcntl(fd, F_GETFD);
  3909     int flags = ::fcntl(fd, F_GETFD);
  3904         if (flags != -1)
  3910     if (flags != -1) {
  3905             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3911       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3906     }
  3912     }
       
  3913   }
  3907 #endif
  3914 #endif
  3908 
  3915 
  3909   if (o_delete != 0) {
  3916   if (o_delete != 0) {
  3910     ::unlink(path);
  3917     ::unlink(path);
  3911   }
  3918   }
  3941   struct stat buf;
  3948   struct stat buf;
  3942 
  3949 
  3943   if (::fstat(fd, &buf) >= 0) {
  3950   if (::fstat(fd, &buf) >= 0) {
  3944     mode = buf.st_mode;
  3951     mode = buf.st_mode;
  3945     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3952     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3946       /*
  3953       // XXX: is the following call interruptible? If so, this might
  3947       * XXX: is the following call interruptible? If so, this might
  3954       // need to go through the INTERRUPT_IO() wrapper as for other
  3948       * need to go through the INTERRUPT_IO() wrapper as for other
  3955       // blocking, interruptible calls in this file.
  3949       * blocking, interruptible calls in this file.
       
  3950       */
       
  3951       int n;
  3956       int n;
  3952       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3957       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3953         *bytes = n;
  3958         *bytes = n;
  3954         return 1;
  3959         return 1;
  3955       }
  3960       }
  3965   *bytes = end - cur;
  3970   *bytes = end - cur;
  3966   return 1;
  3971   return 1;
  3967 }
  3972 }
  3968 
  3973 
  3969 int os::socket_available(int fd, jint *pbytes) {
  3974 int os::socket_available(int fd, jint *pbytes) {
  3970    if (fd < 0)
  3975   if (fd < 0) {
  3971      return OS_OK;
  3976     return OS_OK;
  3972 
  3977   }
  3973    int ret;
  3978 
  3974 
  3979   int ret;
  3975    RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3980 
  3976 
  3981   RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3977    //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  3982 
  3978    // is expected to return 0 on failure and 1 on success to the jdk.
  3983   //%% note ioctl can return 0 when successful, JVM_SocketAvailable
  3979 
  3984   // is expected to return 0 on failure and 1 on success to the jdk.
  3980    return (ret == OS_ERR) ? 0 : 1;
  3985 
       
  3986   return (ret == OS_ERR) ? 0 : 1;
  3981 }
  3987 }
  3982 
  3988 
  3983 // Map a block of memory.
  3989 // Map a block of memory.
  3984 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  3990 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  3985                      char *addr, size_t bytes, bool read_only,
  3991                         char *addr, size_t bytes, bool read_only,
  3986                      bool allow_exec) {
  3992                         bool allow_exec) {
  3987   int prot;
  3993   int prot;
  3988   int flags;
  3994   int flags;
  3989 
  3995 
  3990   if (read_only) {
  3996   if (read_only) {
  3991     prot = PROT_READ;
  3997     prot = PROT_READ;
  4012 }
  4018 }
  4013 
  4019 
  4014 
  4020 
  4015 // Remap a block of memory.
  4021 // Remap a block of memory.
  4016 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  4022 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  4017                        char *addr, size_t bytes, bool read_only,
  4023                           char *addr, size_t bytes, bool read_only,
  4018                        bool allow_exec) {
  4024                           bool allow_exec) {
  4019   // same as map_memory() on this OS
  4025   // same as map_memory() on this OS
  4020   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  4026   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  4021                         allow_exec);
  4027                         allow_exec);
  4022 }
  4028 }
  4023 
  4029 
  4068   kern_return_t kr;
  4074   kern_return_t kr;
  4069   thread_t mach_thread;
  4075   thread_t mach_thread;
  4070 
  4076 
  4071   mach_thread = thread->osthread()->thread_id();
  4077   mach_thread = thread->osthread()->thread_id();
  4072   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4078   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4073   if (kr != KERN_SUCCESS)
  4079   if (kr != KERN_SUCCESS) {
  4074     return -1;
  4080     return -1;
       
  4081   }
  4075 
  4082 
  4076   if (user_sys_cpu_time) {
  4083   if (user_sys_cpu_time) {
  4077     jlong nanos;
  4084     jlong nanos;
  4078     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4085     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4079     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4086     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4132     while (::stat(filename, &buf) == 0) {
  4139     while (::stat(filename, &buf) == 0) {
  4133       (void)::poll(NULL, 0, 100);
  4140       (void)::poll(NULL, 0, 100);
  4134     }
  4141     }
  4135   } else {
  4142   } else {
  4136     jio_fprintf(stderr,
  4143     jio_fprintf(stderr,
  4137       "Could not open pause file '%s', continuing immediately.\n", filename);
  4144                 "Could not open pause file '%s', continuing immediately.\n", filename);
  4138   }
  4145   }
  4139 }
  4146 }
  4140 
  4147 
  4141 
  4148 
  4142 // Refer to the comments in os_solaris.cpp park-unpark.
  4149 // Refer to the comments in os_solaris.cpp park-unpark.
  4200 // utility to compute the abstime argument to timedwait:
  4207 // utility to compute the abstime argument to timedwait:
  4201 // millis is the relative timeout time
  4208 // millis is the relative timeout time
  4202 // abstime will be the absolute timeout time
  4209 // abstime will be the absolute timeout time
  4203 // TODO: replace compute_abstime() with unpackTime()
  4210 // TODO: replace compute_abstime() with unpackTime()
  4204 
  4211 
  4205 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4212 static struct timespec* compute_abstime(struct timespec* abstime,
       
  4213                                         jlong millis) {
  4206   if (millis < 0)  millis = 0;
  4214   if (millis < 0)  millis = 0;
  4207   struct timeval now;
  4215   struct timeval now;
  4208   int status = gettimeofday(&now, NULL);
  4216   int status = gettimeofday(&now, NULL);
  4209   assert(status == 0, "gettimeofday");
  4217   assert(status == 0, "gettimeofday");
  4210   jlong seconds = millis / 1000;
  4218   jlong seconds = millis / 1000;
  4228   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4236   // TODO: assert that _Assoc != NULL or _Assoc == Self
  4229   assert(_nParked == 0, "invariant");
  4237   assert(_nParked == 0, "invariant");
  4230 
  4238 
  4231   int v;
  4239   int v;
  4232   for (;;) {
  4240   for (;;) {
  4233       v = _Event;
  4241     v = _Event;
  4234       if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
  4242     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
  4235   }
  4243   }
  4236   guarantee(v >= 0, "invariant");
  4244   guarantee(v >= 0, "invariant");
  4237   if (v == 0) {
  4245   if (v == 0) {
  4238      // Do this the hard way by blocking ...
  4246     // Do this the hard way by blocking ...
  4239      int status = pthread_mutex_lock(_mutex);
  4247     int status = pthread_mutex_lock(_mutex);
  4240      assert_status(status == 0, status, "mutex_lock");
  4248     assert_status(status == 0, status, "mutex_lock");
  4241      guarantee(_nParked == 0, "invariant");
  4249     guarantee(_nParked == 0, "invariant");
  4242      ++_nParked;
  4250     ++_nParked;
  4243      while (_Event < 0) {
  4251     while (_Event < 0) {
  4244         status = pthread_cond_wait(_cond, _mutex);
  4252       status = pthread_cond_wait(_cond, _mutex);
  4245         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4253       // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  4246         // Treat this the same as if the wait was interrupted
  4254       // Treat this the same as if the wait was interrupted
  4247         if (status == ETIMEDOUT) { status = EINTR; }
  4255       if (status == ETIMEDOUT) { status = EINTR; }
  4248         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4256       assert_status(status == 0 || status == EINTR, status, "cond_wait");
  4249      }
  4257     }
  4250      --_nParked;
  4258     --_nParked;
  4251 
  4259 
  4252     _Event = 0;
  4260     _Event = 0;
  4253      status = pthread_mutex_unlock(_mutex);
  4261     status = pthread_mutex_unlock(_mutex);
  4254      assert_status(status == 0, status, "mutex_unlock");
  4262     assert_status(status == 0, status, "mutex_unlock");
  4255     // Paranoia to ensure our locked and lock-free paths interact
  4263     // Paranoia to ensure our locked and lock-free paths interact
  4256     // correctly with each other.
  4264     // correctly with each other.
  4257     OrderAccess::fence();
  4265     OrderAccess::fence();
  4258   }
  4266   }
  4259   guarantee(_Event >= 0, "invariant");
  4267   guarantee(_Event >= 0, "invariant");
  4262 int os::PlatformEvent::park(jlong millis) {
  4270 int os::PlatformEvent::park(jlong millis) {
  4263   guarantee(_nParked == 0, "invariant");
  4271   guarantee(_nParked == 0, "invariant");
  4264 
  4272 
  4265   int v;
  4273   int v;
  4266   for (;;) {
  4274   for (;;) {
  4267       v = _Event;
  4275     v = _Event;
  4268       if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
  4276     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
  4269   }
  4277   }
  4270   guarantee(v >= 0, "invariant");
  4278   guarantee(v >= 0, "invariant");
  4271   if (v != 0) return OS_OK;
  4279   if (v != 0) return OS_OK;
  4272 
  4280 
  4273   // We do this the hard way, by blocking the thread.
  4281   // We do this the hard way, by blocking the thread.
  4307     if (status == ETIMEDOUT) break;
  4315     if (status == ETIMEDOUT) break;
  4308     // We consume and ignore EINTR and spurious wakeups.
  4316     // We consume and ignore EINTR and spurious wakeups.
  4309   }
  4317   }
  4310   --_nParked;
  4318   --_nParked;
  4311   if (_Event >= 0) {
  4319   if (_Event >= 0) {
  4312      ret = OS_OK;
  4320     ret = OS_OK;
  4313   }
  4321   }
  4314   _Event = 0;
  4322   _Event = 0;
  4315   status = pthread_mutex_unlock(_mutex);
  4323   status = pthread_mutex_unlock(_mutex);
  4316   assert_status(status == 0, status, "mutex_unlock");
  4324   assert_status(status == 0, status, "mutex_unlock");
  4317   assert(_nParked == 0, "invariant");
  4325   assert(_nParked == 0, "invariant");
  4363 
  4371 
  4364 
  4372 
  4365 // JSR166
  4373 // JSR166
  4366 // -------------------------------------------------------
  4374 // -------------------------------------------------------
  4367 
  4375 
  4368 /*
  4376 // The solaris and bsd implementations of park/unpark are fairly
  4369  * The solaris and bsd implementations of park/unpark are fairly
  4377 // conservative for now, but can be improved. They currently use a
  4370  * conservative for now, but can be improved. They currently use a
  4378 // mutex/condvar pair, plus a a count.
  4371  * mutex/condvar pair, plus a a count.
  4379 // Park decrements count if > 0, else does a condvar wait.  Unpark
  4372  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4380 // sets count to 1 and signals condvar.  Only one thread ever waits
  4373  * sets count to 1 and signals condvar.  Only one thread ever waits
  4381 // on the condvar. Contention seen when trying to park implies that someone
  4374  * on the condvar. Contention seen when trying to park implies that someone
  4382 // is unparking you, so don't wait. And spurious returns are fine, so there
  4375  * is unparking you, so don't wait. And spurious returns are fine, so there
  4383 // is no need to track notifications.
  4376  * is no need to track notifications.
       
  4377  */
       
  4378 
  4384 
  4379 #define MAX_SECS 100000000
  4385 #define MAX_SECS 100000000
  4380 /*
  4386 
  4381  * This code is common to bsd and solaris and will be moved to a
  4387 // This code is common to bsd and solaris and will be moved to a
  4382  * common place in dolphin.
  4388 // common place in dolphin.
  4383  *
  4389 //
  4384  * The passed in time value is either a relative time in nanoseconds
  4390 // The passed in time value is either a relative time in nanoseconds
  4385  * or an absolute time in milliseconds. Either way it has to be unpacked
  4391 // or an absolute time in milliseconds. Either way it has to be unpacked
  4386  * into suitable seconds and nanoseconds components and stored in the
  4392 // into suitable seconds and nanoseconds components and stored in the
  4387  * given timespec structure.
  4393 // given timespec structure.
  4388  * Given time is a 64-bit value and the time_t used in the timespec is only
  4394 // Given time is a 64-bit value and the time_t used in the timespec is only
  4389  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4395 // a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4390  * overflow if times way in the future are given. Further on Solaris versions
  4396 // overflow if times way in the future are given. Further on Solaris versions
  4391  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4397 // prior to 10 there is a restriction (see cond_timedwait) that the specified
  4392  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4398 // number of seconds, in abstime, is less than current_time  + 100,000,000.
  4393  * As it will be 28 years before "now + 100000000" will overflow we can
  4399 // As it will be 28 years before "now + 100000000" will overflow we can
  4394  * ignore overflow and just impose a hard-limit on seconds using the value
  4400 // ignore overflow and just impose a hard-limit on seconds using the value
  4395  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4401 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4396  * years from "now".
  4402 // years from "now".
  4397  */
       
  4398 
  4403 
  4399 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4404 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4400   assert(time > 0, "convertTime");
  4405   assert(time > 0, "convertTime");
  4401 
  4406 
  4402   struct timeval now;
  4407   struct timeval now;
  4407 
  4412 
  4408   if (isAbsolute) {
  4413   if (isAbsolute) {
  4409     jlong secs = time / 1000;
  4414     jlong secs = time / 1000;
  4410     if (secs > max_secs) {
  4415     if (secs > max_secs) {
  4411       absTime->tv_sec = max_secs;
  4416       absTime->tv_sec = max_secs;
  4412     }
  4417     } else {
  4413     else {
       
  4414       absTime->tv_sec = secs;
  4418       absTime->tv_sec = secs;
  4415     }
  4419     }
  4416     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4420     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4417   }
  4421   } else {
  4418   else {
       
  4419     jlong secs = time / NANOSECS_PER_SEC;
  4422     jlong secs = time / NANOSECS_PER_SEC;
  4420     if (secs >= MAX_SECS) {
  4423     if (secs >= MAX_SECS) {
  4421       absTime->tv_sec = max_secs;
  4424       absTime->tv_sec = max_secs;
  4422       absTime->tv_nsec = 0;
  4425       absTime->tv_nsec = 0;
  4423     }
  4426     } else {
  4424     else {
       
  4425       absTime->tv_sec = now.tv_sec + secs;
  4427       absTime->tv_sec = now.tv_sec + secs;
  4426       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4428       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4427       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4429       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4428         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4430         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4429         ++absTime->tv_sec; // note: this must be <= max_secs
  4431         ++absTime->tv_sec; // note: this must be <= max_secs
  4537   int status = pthread_mutex_lock(_mutex);
  4539   int status = pthread_mutex_lock(_mutex);
  4538   assert(status == 0, "invariant");
  4540   assert(status == 0, "invariant");
  4539   const int s = _counter;
  4541   const int s = _counter;
  4540   _counter = 1;
  4542   _counter = 1;
  4541   if (s < 1) {
  4543   if (s < 1) {
  4542      if (WorkAroundNPTLTimedWaitHang) {
  4544     if (WorkAroundNPTLTimedWaitHang) {
  4543         status = pthread_cond_signal(_cond);
  4545       status = pthread_cond_signal(_cond);
  4544         assert(status == 0, "invariant");
  4546       assert(status == 0, "invariant");
  4545         status = pthread_mutex_unlock(_mutex);
  4547       status = pthread_mutex_unlock(_mutex);
  4546         assert(status == 0, "invariant");
  4548       assert(status == 0, "invariant");
  4547      } else {
  4549     } else {
  4548         status = pthread_mutex_unlock(_mutex);
  4550       status = pthread_mutex_unlock(_mutex);
  4549         assert(status == 0, "invariant");
  4551       assert(status == 0, "invariant");
  4550         status = pthread_cond_signal(_cond);
  4552       status = pthread_cond_signal(_cond);
  4551         assert(status == 0, "invariant");
  4553       assert(status == 0, "invariant");
  4552      }
  4554     }
  4553   } else {
  4555   } else {
  4554     pthread_mutex_unlock(_mutex);
  4556     pthread_mutex_unlock(_mutex);
  4555     assert(status == 0, "invariant");
  4557     assert(status == 0, "invariant");
  4556   }
  4558   }
  4557 }
  4559 }
  4558 
  4560 
  4559 
  4561 
  4560 /* Darwin has no "environ" in a dynamic library. */
  4562 // Darwin has no "environ" in a dynamic library.
  4561 #ifdef __APPLE__
  4563 #ifdef __APPLE__
  4562 #include <crt_externs.h>
  4564   #include <crt_externs.h>
  4563 #define environ (*_NSGetEnviron())
  4565   #define environ (*_NSGetEnviron())
  4564 #else
  4566 #else
  4565 extern char** environ;
  4567 extern char** environ;
  4566 #endif
  4568 #endif
  4567 
  4569 
  4568 // Run the specified command in a separate process. Return its exit value,
  4570 // Run the specified command in a separate process. Return its exit value,
  4605     int status;
  4607     int status;
  4606 
  4608 
  4607     // Wait for the child process to exit.  This returns immediately if
  4609     // Wait for the child process to exit.  This returns immediately if
  4608     // the child has already exited. */
  4610     // the child has already exited. */
  4609     while (waitpid(pid, &status, 0) < 0) {
  4611     while (waitpid(pid, &status, 0) < 0) {
  4610         switch (errno) {
  4612       switch (errno) {
  4611         case ECHILD: return 0;
  4613       case ECHILD: return 0;
  4612         case EINTR: break;
  4614       case EINTR: break;
  4613         default: return -1;
  4615       default: return -1;
  4614         }
  4616       }
  4615     }
  4617     }
  4616 
  4618 
  4617     if (WIFEXITED(status)) {
  4619     if (WIFEXITED(status)) {
  4618        // The child exited normally; get its exit code.
  4620       // The child exited normally; get its exit code.
  4619        return WEXITSTATUS(status);
  4621       return WEXITSTATUS(status);
  4620     } else if (WIFSIGNALED(status)) {
  4622     } else if (WIFSIGNALED(status)) {
  4621        // The child exited because of a signal
  4623       // The child exited because of a signal
  4622        // The best value to return is 0x80 + signal number,
  4624       // The best value to return is 0x80 + signal number,
  4623        // because that is what all Unix shells do, and because
  4625       // because that is what all Unix shells do, and because
  4624        // it allows callers to distinguish between process exit and
  4626       // it allows callers to distinguish between process exit and
  4625        // process death by signal.
  4627       // process death by signal.
  4626        return 0x80 + WTERMSIG(status);
  4628       return 0x80 + WTERMSIG(status);
  4627     } else {
  4629     } else {
  4628        // Unknown exit code; pass it through
  4630       // Unknown exit code; pass it through
  4629        return status;
  4631       return status;
  4630     }
  4632     }
  4631   }
  4633   }
  4632 }
  4634 }
  4633 
  4635 
  4634 // is_headless_jre()
  4636 // is_headless_jre()
  4639 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4641 // Since JDK8 xawt/libmawt.so was moved into the same directory
  4640 // as libawt.so, and renamed libawt_xawt.so
  4642 // as libawt.so, and renamed libawt_xawt.so
  4641 //
  4643 //
  4642 bool os::is_headless_jre() {
  4644 bool os::is_headless_jre() {
  4643 #ifdef __APPLE__
  4645 #ifdef __APPLE__
  4644     // We no longer build headless-only on Mac OS X
  4646   // We no longer build headless-only on Mac OS X
       
  4647   return false;
       
  4648 #else
       
  4649   struct stat statbuf;
       
  4650   char buf[MAXPATHLEN];
       
  4651   char libmawtpath[MAXPATHLEN];
       
  4652   const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
       
  4653   const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
       
  4654   char *p;
       
  4655 
       
  4656   // Get path to libjvm.so
       
  4657   os::jvm_path(buf, sizeof(buf));
       
  4658 
       
  4659   // Get rid of libjvm.so
       
  4660   p = strrchr(buf, '/');
       
  4661   if (p == NULL) {
  4645     return false;
  4662     return false;
  4646 #else
  4663   } else {
  4647     struct stat statbuf;
  4664     *p = '\0';
  4648     char buf[MAXPATHLEN];
  4665   }
  4649     char libmawtpath[MAXPATHLEN];
  4666 
  4650     const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
  4667   // Get rid of client or server
  4651     const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
  4668   p = strrchr(buf, '/');
  4652     char *p;
  4669   if (p == NULL) {
  4653 
  4670     return false;
  4654     // Get path to libjvm.so
  4671   } else {
  4655     os::jvm_path(buf, sizeof(buf));
  4672     *p = '\0';
  4656 
  4673   }
  4657     // Get rid of libjvm.so
  4674 
  4658     p = strrchr(buf, '/');
  4675   // check xawt/libmawt.so
  4659     if (p == NULL) return false;
  4676   strcpy(libmawtpath, buf);
  4660     else *p = '\0';
  4677   strcat(libmawtpath, xawtstr);
  4661 
  4678   if (::stat(libmawtpath, &statbuf) == 0) return false;
  4662     // Get rid of client or server
  4679 
  4663     p = strrchr(buf, '/');
  4680   // check libawt_xawt.so
  4664     if (p == NULL) return false;
  4681   strcpy(libmawtpath, buf);
  4665     else *p = '\0';
  4682   strcat(libmawtpath, new_xawtstr);
  4666 
  4683   if (::stat(libmawtpath, &statbuf) == 0) return false;
  4667     // check xawt/libmawt.so
  4684 
  4668     strcpy(libmawtpath, buf);
  4685   return true;
  4669     strcat(libmawtpath, xawtstr);
       
  4670     if (::stat(libmawtpath, &statbuf) == 0) return false;
       
  4671 
       
  4672     // check libawt_xawt.so
       
  4673     strcpy(libmawtpath, buf);
       
  4674     strcat(libmawtpath, new_xawtstr);
       
  4675     if (::stat(libmawtpath, &statbuf) == 0) return false;
       
  4676 
       
  4677     return true;
       
  4678 #endif
  4686 #endif
  4679 }
  4687 }
  4680 
  4688 
  4681 // Get the default path to the core file
  4689 // Get the default path to the core file
  4682 // Returns the length of the string
  4690 // Returns the length of the string