hotspot/src/os/bsd/vm/os_bsd.cpp
changeset 26684 d1221849ea3d
parent 26683 a02753d5a0b2
child 26685 aa239a0dfbea
equal deleted inserted replaced
26683:a02753d5a0b2 26684:d1221849ea3d
   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 {
       
   267     set_processor_count(1);   // fallback
   266     set_processor_count(1);   // fallback
   268   }
   267   }
   269 
   268 
   270   /* get physical memory via hw.memsize sysctl (hw.memsize is used
   269   // get physical memory via hw.memsize sysctl (hw.memsize is used
   271    * since it returns a 64 bit value)
   270   // 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
   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
   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);
   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");
   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 
   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);
  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;
  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   }
  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"},
  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)
  1790   assert(ret, "cannot locate libjvm");
  1787   assert(ret, "cannot locate libjvm");
  1791   char *rp = NULL;
  1788   char *rp = NULL;
  1792   if (ret && dli_fname[0] != '\0') {
  1789   if (ret && dli_fname[0] != '\0') {
  1793     rp = realpath(dli_fname, buf);
  1790     rp = realpath(dli_fname, buf);
  1794   }
  1791   }
  1795   if (rp == NULL)
  1792   if (rp == NULL) {
  1796     return;
  1793     return;
       
  1794   }
  1797 
  1795 
  1798   if (Arguments::sun_java_launcher_is_altjvm()) {
  1796   if (Arguments::sun_java_launcher_is_altjvm()) {
  1799     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
  1797     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
  1800     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
  1798     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
  1801     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
  1799     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
  1820         // Check the current module name "libjvm"
  1818         // Check the current module name "libjvm"
  1821         p = strrchr(buf, '/');
  1819         p = strrchr(buf, '/');
  1822         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1820         assert(strstr(p, "/libjvm") == p, "invalid library name");
  1823 
  1821 
  1824         rp = realpath(java_home_var, buf);
  1822         rp = realpath(java_home_var, buf);
  1825         if (rp == NULL)
  1823         if (rp == NULL) {
  1826           return;
  1824           return;
       
  1825         }
  1827 
  1826 
  1828         // determine if this is a legacy image or modules image
  1827         // determine if this is a legacy image or modules image
  1829         // modules image doesn't have "jre" subdirectory
  1828         // modules image doesn't have "jre" subdirectory
  1830         len = strlen(buf);
  1829         len = strlen(buf);
  1831         assert(len < buflen, "Ran out of buffer space");
  1830         assert(len < buflen, "Ran out of buffer space");
  1853           len = strlen(buf);
  1852           len = strlen(buf);
  1854           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1853           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
  1855         } else {
  1854         } else {
  1856           // Fall back to path of current library
  1855           // Fall back to path of current library
  1857           rp = realpath(dli_fname, buf);
  1856           rp = realpath(dli_fname, buf);
  1858           if (rp == NULL)
  1857           if (rp == NULL) {
  1859             return;
  1858             return;
       
  1859           }
  1860         }
  1860         }
  1861       }
  1861       }
  1862     }
  1862     }
  1863   }
  1863   }
  1864 
  1864 
  1876 ////////////////////////////////////////////////////////////////////////////////
  1876 ////////////////////////////////////////////////////////////////////////////////
  1877 // sun.misc.Signal support
  1877 // sun.misc.Signal support
  1878 
  1878 
  1879 static volatile jint sigint_count = 0;
  1879 static volatile jint sigint_count = 0;
  1880 
  1880 
  1881 static void
  1881 static void UserHandler(int sig, void *siginfo, void *context) {
  1882 UserHandler(int sig, void *siginfo, void *context) {
       
  1883   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1882   // 4511530 - sem_post is serialized and handled by the manager thread. When
  1884   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1883   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
  1885   // don't want to flood the manager thread with sem_post requests.
  1884   // don't want to flood the manager thread with sem_post requests.
  1886   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
  1885   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) {
  1887     return;
  1886     return;
       
  1887   }
  1888 
  1888 
  1889   // Ctrl-C is pressed during error reporting, likely because the error
  1889   // Ctrl-C is pressed during error reporting, likely because the error
  1890   // handler fails to abort. Let VM die immediately.
  1890   // handler fails to abort. Let VM die immediately.
  1891   if (sig == SIGINT && is_error_reported()) {
  1891   if (sig == SIGINT && is_error_reported()) {
  1892     os::die();
  1892     os::die();
  1921 
  1921 
  1922 void os::signal_raise(int signal_number) {
  1922 void os::signal_raise(int signal_number) {
  1923   ::raise(signal_number);
  1923   ::raise(signal_number);
  1924 }
  1924 }
  1925 
  1925 
  1926 /*
  1926 // The following code is moved from os.cpp for making this
  1927  * The following code is moved from os.cpp for making this
  1927 // code platform specific, which it is by its very nature.
  1928  * code platform specific, which it is by its very nature.
       
  1929  */
       
  1930 
  1928 
  1931 // Will be modified when max signal is changed to be dynamic
  1929 // Will be modified when max signal is changed to be dynamic
  1932 int os::sigexitnum_pd() {
  1930 int os::sigexitnum_pd() {
  1933   return NSIG;
  1931   return NSIG;
  1934 }
  1932 }
  1937 static volatile jint pending_signals[NSIG+1] = { 0 };
  1935 static volatile jint pending_signals[NSIG+1] = { 0 };
  1938 
  1936 
  1939 // Bsd(POSIX) specific hand shaking semaphore.
  1937 // Bsd(POSIX) specific hand shaking semaphore.
  1940 #ifdef __APPLE__
  1938 #ifdef __APPLE__
  1941 typedef semaphore_t os_semaphore_t;
  1939 typedef semaphore_t os_semaphore_t;
  1942 #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1940 
  1943 #define SEM_WAIT(sem)           semaphore_wait(sem)
  1941   #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
  1944 #define SEM_POST(sem)           semaphore_signal(sem)
  1942   #define SEM_WAIT(sem)           semaphore_wait(sem)
  1945 #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1943   #define SEM_POST(sem)           semaphore_signal(sem)
       
  1944   #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
  1946 #else
  1945 #else
  1947 typedef sem_t os_semaphore_t;
  1946 typedef sem_t os_semaphore_t;
  1948 #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1947 
  1949 #define SEM_WAIT(sem)           sem_wait(&sem)
  1948   #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
  1950 #define SEM_POST(sem)           sem_post(&sem)
  1949   #define SEM_WAIT(sem)           sem_wait(&sem)
  1951 #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1950   #define SEM_POST(sem)           sem_post(&sem)
       
  1951   #define SEM_DESTROY(sem)        sem_destroy(&sem)
  1952 #endif
  1952 #endif
  1953 
  1953 
  1954 class Semaphore : public StackObj {
  1954 class Semaphore : public StackObj {
  1955  public:
  1955  public:
  1956   Semaphore();
  1956   Semaphore();
  2085       ::SEM_WAIT(sig_sem);
  2085       ::SEM_WAIT(sig_sem);
  2086 
  2086 
  2087       // were we externally suspended while we were waiting?
  2087       // were we externally suspended while we were waiting?
  2088       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  2088       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  2089       if (threadIsSuspended) {
  2089       if (threadIsSuspended) {
  2090         //
       
  2091         // The semaphore has been incremented, but while we were waiting
  2090         // The semaphore has been incremented, but while we were waiting
  2092         // another thread suspended us. We don't want to continue running
  2091         // another thread suspended us. We don't want to continue running
  2093         // while suspended because that would surprise the thread that
  2092         // while suspended because that would surprise the thread that
  2094         // suspended us.
  2093         // suspended us.
  2095         //
       
  2096         ::SEM_POST(sig_sem);
  2094         ::SEM_POST(sig_sem);
  2097 
  2095 
  2098         thread->java_suspend_self();
  2096         thread->java_suspend_self();
  2099       }
  2097       }
  2100     } while (threadIsSuspended);
  2098     } while (threadIsSuspended);
  2391 
  2389 
  2392   key_t key = IPC_PRIVATE;
  2390   key_t key = IPC_PRIVATE;
  2393   char *addr;
  2391   char *addr;
  2394 
  2392 
  2395   bool warn_on_failure = UseLargePages &&
  2393   bool warn_on_failure = UseLargePages &&
  2396                         (!FLAG_IS_DEFAULT(UseLargePages) ||
  2394                          (!FLAG_IS_DEFAULT(UseLargePages) ||
  2397                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
  2395                           !FLAG_IS_DEFAULT(LargePageSizeInBytes));
  2398                         );
       
  2399 
  2396 
  2400   // Create a large shared memory region to attach to based on size.
  2397   // Create a large shared memory region to attach to based on size.
  2401   // Currently, size is the total size of the heap
  2398   // Currently, size is the total size of the heap
  2402   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2399   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
  2403   if (shmid == -1) {
  2400   if (shmid == -1) {
  2571 
  2568 
  2572   assert(ms < 1000, "Un-interruptable sleep, short time use only");
  2569   assert(ms < 1000, "Un-interruptable sleep, short time use only");
  2573   req.tv_sec = 0;
  2570   req.tv_sec = 0;
  2574   if (ms > 0) {
  2571   if (ms > 0) {
  2575     req.tv_nsec = (ms % 1000) * 1000000;
  2572     req.tv_nsec = (ms % 1000) * 1000000;
  2576   }
  2573   } else {
  2577   else {
       
  2578     req.tv_nsec = 1;
  2574     req.tv_nsec = 1;
  2579   }
  2575   }
  2580 
  2576 
  2581   nanosleep(&req, NULL);
  2577   nanosleep(&req, NULL);
  2582 
  2578 
  2635   31,              // 10 MaxPriority
  2631   31,              // 10 MaxPriority
  2636 
  2632 
  2637   31               // 11 CriticalPriority
  2633   31               // 11 CriticalPriority
  2638 };
  2634 };
  2639 #else
  2635 #else
  2640 /* Using Mach high-level priority assignments */
  2636 // Using Mach high-level priority assignments
  2641 int os::java_to_os_priority[CriticalPriority + 1] = {
  2637 int os::java_to_os_priority[CriticalPriority + 1] = {
  2642    0,              // 0 Entry should never be used (MINPRI_USER)
  2638    0,              // 0 Entry should never be used (MINPRI_USER)
  2643 
  2639 
  2644   27,              // 1 MinPriority
  2640   27,              // 1 MinPriority
  2645   28,              // 2
  2641   28,              // 2
  2688 #elif defined(__APPLE__) || defined(__NetBSD__)
  2684 #elif defined(__APPLE__) || defined(__NetBSD__)
  2689   struct sched_param sp;
  2685   struct sched_param sp;
  2690   int policy;
  2686   int policy;
  2691   pthread_t self = pthread_self();
  2687   pthread_t self = pthread_self();
  2692 
  2688 
  2693   if (pthread_getschedparam(self, &policy, &sp) != 0)
  2689   if (pthread_getschedparam(self, &policy, &sp) != 0) {
  2694     return OS_ERR;
  2690     return OS_ERR;
       
  2691   }
  2695 
  2692 
  2696   sp.sched_priority = newpri;
  2693   sp.sched_priority = newpri;
  2697   if (pthread_setschedparam(self, policy, &sp) != 0)
  2694   if (pthread_setschedparam(self, policy, &sp) != 0) {
  2698     return OS_ERR;
  2695     return OS_ERR;
       
  2696   }
  2699 
  2697 
  2700   return OS_OK;
  2698   return OS_OK;
  2701 #else
  2699 #else
  2702   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2700   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
  2703   return (ret == 0) ? OS_OK : OS_ERR;
  2701   return (ret == 0) ? OS_OK : OS_ERR;
  2749 //  - resume:
  2747 //  - resume:
  2750 //      - sets target osthread state to continue
  2748 //      - sets target osthread state to continue
  2751 //      - sends signal to end the sigsuspend loop in the SR_handler
  2749 //      - sends signal to end the sigsuspend loop in the SR_handler
  2752 //
  2750 //
  2753 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2751 //  Note that the SR_lock plays no role in this suspend/resume protocol.
  2754 //
       
  2755 
  2752 
  2756 static void resume_clear_context(OSThread *osthread) {
  2753 static void resume_clear_context(OSThread *osthread) {
  2757   osthread->set_ucontext(NULL);
  2754   osthread->set_ucontext(NULL);
  2758   osthread->set_siginfo(NULL);
  2755   osthread->set_siginfo(NULL);
  2759 }
  2756 }
  2761 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2758 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
  2762   osthread->set_ucontext(context);
  2759   osthread->set_ucontext(context);
  2763   osthread->set_siginfo(siginfo);
  2760   osthread->set_siginfo(siginfo);
  2764 }
  2761 }
  2765 
  2762 
  2766 //
       
  2767 // Handler function invoked when a thread's execution is suspended or
  2763 // Handler function invoked when a thread's execution is suspended or
  2768 // resumed. We have to be careful that only async-safe functions are
  2764 // resumed. We have to be careful that only async-safe functions are
  2769 // called here (Note: most pthread functions are not async safe and
  2765 // called here (Note: most pthread functions are not async safe and
  2770 // should be avoided.)
  2766 // should be avoided.)
  2771 //
  2767 //
  2833 
  2829 
  2834 
  2830 
  2835 static int SR_initialize() {
  2831 static int SR_initialize() {
  2836   struct sigaction act;
  2832   struct sigaction act;
  2837   char *s;
  2833   char *s;
  2838   /* Get signal number to use for suspend/resume */
  2834   // Get signal number to use for suspend/resume
  2839   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2835   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
  2840     int sig = ::strtol(s, 0, 10);
  2836     int sig = ::strtol(s, 0, 10);
  2841     if (sig > 0 || sig < NSIG) {
  2837     if (sig > 0 || sig < NSIG) {
  2842       SR_signum = sig;
  2838       SR_signum = sig;
  2843     }
  2839     }
  2847          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2843          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
  2848 
  2844 
  2849   sigemptyset(&SR_sigset);
  2845   sigemptyset(&SR_sigset);
  2850   sigaddset(&SR_sigset, SR_signum);
  2846   sigaddset(&SR_sigset, SR_signum);
  2851 
  2847 
  2852   /* Set up signal handler for suspend/resume */
  2848   // Set up signal handler for suspend/resume
  2853   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2849   act.sa_flags = SA_RESTART|SA_SIGINFO;
  2854   act.sa_handler = (void (*)(int)) SR_handler;
  2850   act.sa_handler = (void (*)(int)) SR_handler;
  2855 
  2851 
  2856   // SR_signum is blocked by default.
  2852   // SR_signum is blocked by default.
  2857   // 4528190 - We also need to block pthread restart signal (32 on all
  2853   // 4528190 - We also need to block pthread restart signal (32 on all
  2973 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2969 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  2974 //
  2970 //
  2975 // Note that the VM will print warnings if it detects conflicting signal
  2971 // Note that the VM will print warnings if it detects conflicting signal
  2976 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2972 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  2977 //
  2973 //
  2978 extern "C" JNIEXPORT int
  2974 extern "C" JNIEXPORT int JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2979 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
  2975                                                void* ucontext,
  2980                       void* ucontext, int abort_if_unrecognized);
  2976                                                int abort_if_unrecognized);
  2981 
  2977 
  2982 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2978 void signalHandler(int sig, siginfo_t* info, void* uc) {
  2983   assert(info != NULL && uc != NULL, "it must be old kernel");
  2979   assert(info != NULL && uc != NULL, "it must be old kernel");
  2984   int orig_errno = errno;  // Preserve errno value over signal handler.
  2980   int orig_errno = errno;  // Preserve errno value over signal handler.
  2985   JVM_handle_bsd_signal(sig, info, uc, true);
  2981   JVM_handle_bsd_signal(sig, info, uc, true);
  3241 // to indicate, that some special sort of signal
  3237 // to indicate, that some special sort of signal
  3242 // trampoline is used.
  3238 // trampoline is used.
  3243 // We will never set this flag, and we should
  3239 // We will never set this flag, and we should
  3244 // ignore this flag in our diagnostic
  3240 // ignore this flag in our diagnostic
  3245 #ifdef SIGNIFICANT_SIGNAL_MASK
  3241 #ifdef SIGNIFICANT_SIGNAL_MASK
  3246 #undef SIGNIFICANT_SIGNAL_MASK
  3242   #undef SIGNIFICANT_SIGNAL_MASK
  3247 #endif
  3243 #endif
  3248 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3244 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
  3249 
  3245 
  3250 static const char* get_signal_handler_name(address handler,
  3246 static const char* get_signal_handler_name(address handler,
  3251                                            char* buf, int buflen) {
  3247                                            char* buf, int buflen) {
  3313   }
  3309   }
  3314   st->cr();
  3310   st->cr();
  3315 }
  3311 }
  3316 
  3312 
  3317 
  3313 
  3318 #define DO_SIGNAL_CHECK(sig) \
  3314 #define DO_SIGNAL_CHECK(sig)                      \
  3319   if (!sigismember(&check_signal_done, sig)) \
  3315   do {                                            \
  3320     os::Bsd::check_signal_handler(sig)
  3316     if (!sigismember(&check_signal_done, sig)) {  \
       
  3317       os::Bsd::check_signal_handler(sig);         \
       
  3318     }                                             \
       
  3319   } while (0)
  3321 
  3320 
  3322 // This method is a periodic task to check for misbehaving JNI applications
  3321 // This method is a periodic task to check for misbehaving JNI applications
  3323 // under CheckJNI, we can add any periodic checks here
  3322 // under CheckJNI, we can add any periodic checks here
  3324 
  3323 
  3325 void os::run_periodic_checks() {
  3324 void os::run_periodic_checks() {
  3430   if (sigismember(&check_signal_done, sig)) {
  3429   if (sigismember(&check_signal_done, sig)) {
  3431     print_signal_handlers(tty, buf, O_BUFLEN);
  3430     print_signal_handlers(tty, buf, O_BUFLEN);
  3432   }
  3431   }
  3433 }
  3432 }
  3434 
  3433 
  3435 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
  3434 extern void report_error(char* file_name, int line_no, char* title,
       
  3435                          char* format, ...);
  3436 
  3436 
  3437 extern bool signal_name(int signo, char* buf, size_t len);
  3437 extern bool signal_name(int signo, char* buf, size_t len);
  3438 
  3438 
  3439 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3439 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  3440   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3440   if (0 < exception_code && exception_code <= SIGRTMAX) {
  3448   }
  3448   }
  3449 }
  3449 }
  3450 
  3450 
  3451 // this is called _before_ the most of global arguments have been parsed
  3451 // this is called _before_ the most of global arguments have been parsed
  3452 void os::init(void) {
  3452 void os::init(void) {
  3453   char dummy;   /* used to get a guess on initial stack address */
  3453   char dummy;   // used to get a guess on initial stack address
  3454 //  first_hrtime = gethrtime();
  3454 //  first_hrtime = gethrtime();
  3455 
  3455 
  3456   // With BsdThreads the JavaMain thread pid (primordial thread)
  3456   // With BsdThreads the JavaMain thread pid (primordial thread)
  3457   // is different than the pid of the java launcher thread.
  3457   // is different than the pid of the java launcher thread.
  3458   // So, on Bsd, the launcher thread pid is passed to the VM
  3458   // So, on Bsd, the launcher thread pid is passed to the VM
  3501     perfMemory_exit();
  3501     perfMemory_exit();
  3502   }
  3502   }
  3503 }
  3503 }
  3504 
  3504 
  3505 // this is called _after_ the global arguments have been parsed
  3505 // this is called _after_ the global arguments have been parsed
  3506 jint os::init_2(void)
  3506 jint os::init_2(void) {
  3507 {
       
  3508   // Allocate a single page and mark it as readable for safepoint polling
  3507   // Allocate a single page and mark it as readable for safepoint polling
  3509   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3508   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3510   guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page");
  3509   guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page");
  3511 
  3510 
  3512   os::set_polling_page(polling_page);
  3511   os::set_polling_page(polling_page);
  3513 
  3512 
  3514 #ifndef PRODUCT
  3513 #ifndef PRODUCT
  3515   if (Verbose && PrintMiscellaneous)
  3514   if (Verbose && PrintMiscellaneous) {
  3516     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  3515     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n",
       
  3516                (intptr_t)polling_page);
       
  3517   }
  3517 #endif
  3518 #endif
  3518 
  3519 
  3519   if (!UseMembar) {
  3520   if (!UseMembar) {
  3520     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3521     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  3521     guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3522     guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
  3522     os::set_memory_serialize_page(mem_serialize_page);
  3523     os::set_memory_serialize_page(mem_serialize_page);
  3523 
  3524 
  3524 #ifndef PRODUCT
  3525 #ifndef PRODUCT
  3525     if (Verbose && PrintMiscellaneous)
  3526     if (Verbose && PrintMiscellaneous) {
  3526       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  3527       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n",
       
  3528                  (intptr_t)mem_serialize_page);
       
  3529     }
  3527 #endif
  3530 #endif
  3528   }
  3531   }
  3529 
  3532 
  3530   // initialize suspend/resume support - must do this before signal_sets_init()
  3533   // initialize suspend/resume support - must do this before signal_sets_init()
  3531   if (SR_initialize() != 0) {
  3534   if (SR_initialize() != 0) {
  3563     // set the number of file descriptors to max. print out error
  3566     // set the number of file descriptors to max. print out error
  3564     // if getrlimit/setrlimit fails but continue regardless.
  3567     // if getrlimit/setrlimit fails but continue regardless.
  3565     struct rlimit nbr_files;
  3568     struct rlimit nbr_files;
  3566     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3569     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  3567     if (status != 0) {
  3570     if (status != 0) {
  3568       if (PrintMiscellaneous && (Verbose || WizardMode))
  3571       if (PrintMiscellaneous && (Verbose || WizardMode)) {
  3569         perror("os::init_2 getrlimit failed");
  3572         perror("os::init_2 getrlimit failed");
       
  3573       }
  3570     } else {
  3574     } else {
  3571       nbr_files.rlim_cur = nbr_files.rlim_max;
  3575       nbr_files.rlim_cur = nbr_files.rlim_max;
  3572 
  3576 
  3573 #ifdef __APPLE__
  3577 #ifdef __APPLE__
  3574       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3578       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
  3577       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3581       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
  3578 #endif
  3582 #endif
  3579 
  3583 
  3580       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3584       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  3581       if (status != 0) {
  3585       if (status != 0) {
  3582         if (PrintMiscellaneous && (Verbose || WizardMode))
  3586         if (PrintMiscellaneous && (Verbose || WizardMode)) {
  3583           perror("os::init_2 setrlimit failed");
  3587           perror("os::init_2 setrlimit failed");
       
  3588         }
  3584       }
  3589       }
  3585     }
  3590     }
  3586   }
  3591   }
  3587 
  3592 
  3588   // at-exit methods are called in the reverse order of their registration.
  3593   // at-exit methods are called in the reverse order of their registration.
  3621 // this is called at the end of vm_initialization
  3626 // this is called at the end of vm_initialization
  3622 void os::init_3(void) { }
  3627 void os::init_3(void) { }
  3623 
  3628 
  3624 // Mark the polling page as unreadable
  3629 // Mark the polling page as unreadable
  3625 void os::make_polling_page_unreadable(void) {
  3630 void os::make_polling_page_unreadable(void) {
  3626   if (!guard_memory((char*)_polling_page, Bsd::page_size()))
  3631   if (!guard_memory((char*)_polling_page, Bsd::page_size())) {
  3627     fatal("Could not disable polling page");
  3632     fatal("Could not disable polling page");
  3628 };
  3633   }
       
  3634 }
  3629 
  3635 
  3630 // Mark the polling page as readable
  3636 // Mark the polling page as readable
  3631 void os::make_polling_page_readable(void) {
  3637 void os::make_polling_page_readable(void) {
  3632   if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3638   if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
  3633     fatal("Could not enable polling page");
  3639     fatal("Could not enable polling page");
  3634   }
  3640   }
  3635 };
  3641 }
  3636 
  3642 
  3637 int os::active_processor_count() {
  3643 int os::active_processor_count() {
  3638   return _processor_count;
  3644   return _processor_count;
  3639 }
  3645 }
  3640 
  3646 
  3705   PcFetcher fetcher(thread);
  3711   PcFetcher fetcher(thread);
  3706   fetcher.run();
  3712   fetcher.run();
  3707   return fetcher.result();
  3713   return fetcher.result();
  3708 }
  3714 }
  3709 
  3715 
  3710 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
  3716 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond,
  3711 {
  3717                                  pthread_mutex_t *_mutex,
       
  3718                                  const struct timespec *_abstime) {
  3712   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3719   return pthread_cond_timedwait(_cond, _mutex, _abstime);
  3713 }
  3720 }
  3714 
  3721 
  3715 ////////////////////////////////////////////////////////////////////////////////
  3722 ////////////////////////////////////////////////////////////////////////////////
  3716 // debug support
  3723 // debug support
  3743       address       lowest = (address) dlinfo.dli_sname;
  3750       address       lowest = (address) dlinfo.dli_sname;
  3744       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3751       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  3745       if (begin < lowest)  begin = lowest;
  3752       if (begin < lowest)  begin = lowest;
  3746       Dl_info dlinfo2;
  3753       Dl_info dlinfo2;
  3747       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3754       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  3748           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  3755           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
  3749         end = (address) dlinfo2.dli_saddr;
  3756         end = (address) dlinfo2.dli_saddr;
       
  3757       }
  3750       Disassembler::decode(begin, end, st);
  3758       Disassembler::decode(begin, end, st);
  3751     }
  3759     }
  3752     return true;
  3760     return true;
  3753   }
  3761   }
  3754   return false;
  3762   return false;
  3758 // misc
  3766 // misc
  3759 
  3767 
  3760 // This does not do anything on Bsd. This is basically a hook for being
  3768 // This does not do anything on Bsd. This is basically a hook for being
  3761 // able to use structured exception handling (thread-local exception filters)
  3769 // able to use structured exception handling (thread-local exception filters)
  3762 // on, e.g., Win32.
  3770 // on, e.g., Win32.
  3763 void
  3771 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
  3764 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
  3772                               methodHandle* method, JavaCallArguments* args,
  3765                          JavaCallArguments* args, Thread* thread) {
  3773                               Thread* thread) {
  3766   f(value, method, args, thread);
  3774   f(value, method, args, thread);
  3767 }
  3775 }
  3768 
  3776 
  3769 void os::print_statistics() {
  3777 void os::print_statistics() {
  3770 }
  3778 }
  3801 bool os::check_heap(bool force) {
  3809 bool os::check_heap(bool force) {
  3802   return true;
  3810   return true;
  3803 }
  3811 }
  3804 
  3812 
  3805 ATTRIBUTE_PRINTF(3, 0)
  3813 ATTRIBUTE_PRINTF(3, 0)
  3806 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
  3814 int local_vsnprintf(char* buf, size_t count, const char* format,
       
  3815                     va_list args) {
  3807   return ::vsnprintf(buf, count, format, args);
  3816   return ::vsnprintf(buf, count, format, args);
  3808 }
  3817 }
  3809 
  3818 
  3810 // Is a (classpath) directory empty?
  3819 // Is a (classpath) directory empty?
  3811 bool os::dir_is_empty(const char* path) {
  3820 bool os::dir_is_empty(const char* path) {
  3813   struct dirent *ptr;
  3822   struct dirent *ptr;
  3814 
  3823 
  3815   dir = opendir(path);
  3824   dir = opendir(path);
  3816   if (dir == NULL) return true;
  3825   if (dir == NULL) return true;
  3817 
  3826 
  3818   /* Scan the directory */
  3827   // Scan the directory
  3819   bool result = true;
  3828   bool result = true;
  3820   char buf[sizeof(struct dirent) + MAX_PATH];
  3829   char buf[sizeof(struct dirent) + MAX_PATH];
  3821   while (result && (ptr = ::readdir(dir)) != NULL) {
  3830   while (result && (ptr = ::readdir(dir)) != NULL) {
  3822     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3831     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  3823       result = false;
  3832       result = false;
  3829 
  3838 
  3830 // This code originates from JDK's sysOpen and open64_w
  3839 // This code originates from JDK's sysOpen and open64_w
  3831 // from src/solaris/hpi/src/system_md.c
  3840 // from src/solaris/hpi/src/system_md.c
  3832 
  3841 
  3833 #ifndef O_DELETE
  3842 #ifndef O_DELETE
  3834 #define O_DELETE 0x10000
  3843   #define O_DELETE 0x10000
  3835 #endif
  3844 #endif
  3836 
  3845 
  3837 // Open a file. Unlink the file immediately after open returns
  3846 // Open a file. Unlink the file immediately after open returns
  3838 // if the specified oflag has the O_DELETE flag set.
  3847 // if the specified oflag has the O_DELETE flag set.
  3839 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3848 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  3840 
  3849 
  3841 int os::open(const char *path, int oflag, int mode) {
  3850 int os::open(const char *path, int oflag, int mode) {
  3842 
       
  3843   if (strlen(path) > MAX_PATH - 1) {
  3851   if (strlen(path) > MAX_PATH - 1) {
  3844     errno = ENAMETOOLONG;
  3852     errno = ENAMETOOLONG;
  3845     return -1;
  3853     return -1;
  3846   }
  3854   }
  3847   int fd;
  3855   int fd;
  3849   oflag = oflag & ~O_DELETE;
  3857   oflag = oflag & ~O_DELETE;
  3850 
  3858 
  3851   fd = ::open(path, oflag, mode);
  3859   fd = ::open(path, oflag, mode);
  3852   if (fd == -1) return -1;
  3860   if (fd == -1) return -1;
  3853 
  3861 
  3854   //If the open succeeded, the file might still be a directory
  3862   // If the open succeeded, the file might still be a directory
  3855   {
  3863   {
  3856     struct stat buf;
  3864     struct stat buf;
  3857     int ret = ::fstat(fd, &buf);
  3865     int ret = ::fstat(fd, &buf);
  3858     int st_mode = buf.st_mode;
  3866     int st_mode = buf.st_mode;
  3859 
  3867 
  3867       ::close(fd);
  3875       ::close(fd);
  3868       return -1;
  3876       return -1;
  3869     }
  3877     }
  3870   }
  3878   }
  3871 
  3879 
  3872     /*
  3880   // All file descriptors that are opened in the JVM and not
  3873      * All file descriptors that are opened in the JVM and not
  3881   // specifically destined for a subprocess should have the
  3874      * specifically destined for a subprocess should have the
  3882   // close-on-exec flag set.  If we don't set it, then careless 3rd
  3875      * close-on-exec flag set.  If we don't set it, then careless 3rd
  3883   // party native code might fork and exec without closing all
  3876      * party native code might fork and exec without closing all
  3884   // appropriate file descriptors (e.g. as we do in closeDescriptors in
  3877      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  3885   // UNIXProcess.c), and this in turn might:
  3878      * UNIXProcess.c), and this in turn might:
  3886   //
  3879      *
  3887   // - cause end-of-file to fail to be detected on some file
  3880      * - cause end-of-file to fail to be detected on some file
  3888   //   descriptors, resulting in mysterious hangs, or
  3881      *   descriptors, resulting in mysterious hangs, or
  3889   //
  3882      *
  3890   // - might cause an fopen in the subprocess to fail on a system
  3883      * - might cause an fopen in the subprocess to fail on a system
  3891   //   suffering from bug 1085341.
  3884      *   suffering from bug 1085341.
  3892   //
  3885      *
  3893   // (Yes, the default setting of the close-on-exec flag is a Unix
  3886      * (Yes, the default setting of the close-on-exec flag is a Unix
  3894   // design flaw)
  3887      * design flaw)
  3895   //
  3888      *
  3896   // See:
  3889      * See:
  3897   // 1085341: 32-bit stdio routines should support file descriptors >255
  3890      * 1085341: 32-bit stdio routines should support file descriptors >255
  3898   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3891      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  3899   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3892      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  3900   //
  3893      */
       
  3894 #ifdef FD_CLOEXEC
  3901 #ifdef FD_CLOEXEC
  3895   {
  3902   {
  3896     int flags = ::fcntl(fd, F_GETFD);
  3903     int flags = ::fcntl(fd, F_GETFD);
  3897     if (flags != -1)
  3904     if (flags != -1) {
  3898       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  3905       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
       
  3906     }
  3899   }
  3907   }
  3900 #endif
  3908 #endif
  3901 
  3909 
  3902   if (o_delete != 0) {
  3910   if (o_delete != 0) {
  3903     ::unlink(path);
  3911     ::unlink(path);
  3934   struct stat buf;
  3942   struct stat buf;
  3935 
  3943 
  3936   if (::fstat(fd, &buf) >= 0) {
  3944   if (::fstat(fd, &buf) >= 0) {
  3937     mode = buf.st_mode;
  3945     mode = buf.st_mode;
  3938     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3946     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  3939       /*
  3947       // XXX: is the following call interruptible? If so, this might
  3940       * XXX: is the following call interruptible? If so, this might
  3948       // need to go through the INTERRUPT_IO() wrapper as for other
  3941       * need to go through the INTERRUPT_IO() wrapper as for other
  3949       // blocking, interruptible calls in this file.
  3942       * blocking, interruptible calls in this file.
       
  3943       */
       
  3944       int n;
  3950       int n;
  3945       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3951       if (::ioctl(fd, FIONREAD, &n) >= 0) {
  3946         *bytes = n;
  3952         *bytes = n;
  3947         return 1;
  3953         return 1;
  3948       }
  3954       }
  3958   *bytes = end - cur;
  3964   *bytes = end - cur;
  3959   return 1;
  3965   return 1;
  3960 }
  3966 }
  3961 
  3967 
  3962 int os::socket_available(int fd, jint *pbytes) {
  3968 int os::socket_available(int fd, jint *pbytes) {
  3963   if (fd < 0)
  3969   if (fd < 0) {
  3964     return OS_OK;
  3970     return OS_OK;
       
  3971   }
  3965 
  3972 
  3966   int ret;
  3973   int ret;
  3967 
  3974 
  3968   RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3975   RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  3969 
  3976 
  4061   kern_return_t kr;
  4068   kern_return_t kr;
  4062   thread_t mach_thread;
  4069   thread_t mach_thread;
  4063 
  4070 
  4064   mach_thread = thread->osthread()->thread_id();
  4071   mach_thread = thread->osthread()->thread_id();
  4065   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4072   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
  4066   if (kr != KERN_SUCCESS)
  4073   if (kr != KERN_SUCCESS) {
  4067     return -1;
  4074     return -1;
       
  4075   }
  4068 
  4076 
  4069   if (user_sys_cpu_time) {
  4077   if (user_sys_cpu_time) {
  4070     jlong nanos;
  4078     jlong nanos;
  4071     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4079     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
  4072     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4080     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
  4193 // utility to compute the abstime argument to timedwait:
  4201 // utility to compute the abstime argument to timedwait:
  4194 // millis is the relative timeout time
  4202 // millis is the relative timeout time
  4195 // abstime will be the absolute timeout time
  4203 // abstime will be the absolute timeout time
  4196 // TODO: replace compute_abstime() with unpackTime()
  4204 // TODO: replace compute_abstime() with unpackTime()
  4197 
  4205 
  4198 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
  4206 static struct timespec* compute_abstime(struct timespec* abstime,
       
  4207                                         jlong millis) {
  4199   if (millis < 0)  millis = 0;
  4208   if (millis < 0)  millis = 0;
  4200   struct timeval now;
  4209   struct timeval now;
  4201   int status = gettimeofday(&now, NULL);
  4210   int status = gettimeofday(&now, NULL);
  4202   assert(status == 0, "gettimeofday");
  4211   assert(status == 0, "gettimeofday");
  4203   jlong seconds = millis / 1000;
  4212   jlong seconds = millis / 1000;
  4356 
  4365 
  4357 
  4366 
  4358 // JSR166
  4367 // JSR166
  4359 // -------------------------------------------------------
  4368 // -------------------------------------------------------
  4360 
  4369 
  4361 /*
  4370 // The solaris and bsd implementations of park/unpark are fairly
  4362  * The solaris and bsd implementations of park/unpark are fairly
  4371 // conservative for now, but can be improved. They currently use a
  4363  * conservative for now, but can be improved. They currently use a
  4372 // mutex/condvar pair, plus a a count.
  4364  * mutex/condvar pair, plus a a count.
  4373 // Park decrements count if > 0, else does a condvar wait.  Unpark
  4365  * Park decrements count if > 0, else does a condvar wait.  Unpark
  4374 // sets count to 1 and signals condvar.  Only one thread ever waits
  4366  * sets count to 1 and signals condvar.  Only one thread ever waits
  4375 // on the condvar. Contention seen when trying to park implies that someone
  4367  * on the condvar. Contention seen when trying to park implies that someone
  4376 // is unparking you, so don't wait. And spurious returns are fine, so there
  4368  * is unparking you, so don't wait. And spurious returns are fine, so there
  4377 // is no need to track notifications.
  4369  * is no need to track notifications.
       
  4370  */
       
  4371 
  4378 
  4372 #define MAX_SECS 100000000
  4379 #define MAX_SECS 100000000
  4373 /*
  4380 
  4374  * This code is common to bsd and solaris and will be moved to a
  4381 // This code is common to bsd and solaris and will be moved to a
  4375  * common place in dolphin.
  4382 // common place in dolphin.
  4376  *
  4383 //
  4377  * The passed in time value is either a relative time in nanoseconds
  4384 // The passed in time value is either a relative time in nanoseconds
  4378  * or an absolute time in milliseconds. Either way it has to be unpacked
  4385 // or an absolute time in milliseconds. Either way it has to be unpacked
  4379  * into suitable seconds and nanoseconds components and stored in the
  4386 // into suitable seconds and nanoseconds components and stored in the
  4380  * given timespec structure.
  4387 // given timespec structure.
  4381  * Given time is a 64-bit value and the time_t used in the timespec is only
  4388 // Given time is a 64-bit value and the time_t used in the timespec is only
  4382  * a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4389 // a signed-32-bit value (except on 64-bit Bsd) we have to watch for
  4383  * overflow if times way in the future are given. Further on Solaris versions
  4390 // overflow if times way in the future are given. Further on Solaris versions
  4384  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  4391 // prior to 10 there is a restriction (see cond_timedwait) that the specified
  4385  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  4392 // number of seconds, in abstime, is less than current_time  + 100,000,000.
  4386  * As it will be 28 years before "now + 100000000" will overflow we can
  4393 // As it will be 28 years before "now + 100000000" will overflow we can
  4387  * ignore overflow and just impose a hard-limit on seconds using the value
  4394 // ignore overflow and just impose a hard-limit on seconds using the value
  4388  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4395 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
  4389  * years from "now".
  4396 // years from "now".
  4390  */
       
  4391 
  4397 
  4392 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4398 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
  4393   assert(time > 0, "convertTime");
  4399   assert(time > 0, "convertTime");
  4394 
  4400 
  4395   struct timeval now;
  4401   struct timeval now;
  4400 
  4406 
  4401   if (isAbsolute) {
  4407   if (isAbsolute) {
  4402     jlong secs = time / 1000;
  4408     jlong secs = time / 1000;
  4403     if (secs > max_secs) {
  4409     if (secs > max_secs) {
  4404       absTime->tv_sec = max_secs;
  4410       absTime->tv_sec = max_secs;
  4405     }
  4411     } else {
  4406     else {
       
  4407       absTime->tv_sec = secs;
  4412       absTime->tv_sec = secs;
  4408     }
  4413     }
  4409     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4414     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  4410   }
  4415   } else {
  4411   else {
       
  4412     jlong secs = time / NANOSECS_PER_SEC;
  4416     jlong secs = time / NANOSECS_PER_SEC;
  4413     if (secs >= MAX_SECS) {
  4417     if (secs >= MAX_SECS) {
  4414       absTime->tv_sec = max_secs;
  4418       absTime->tv_sec = max_secs;
  4415       absTime->tv_nsec = 0;
  4419       absTime->tv_nsec = 0;
  4416     }
  4420     } else {
  4417     else {
       
  4418       absTime->tv_sec = now.tv_sec + secs;
  4421       absTime->tv_sec = now.tv_sec + secs;
  4419       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4422       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  4420       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4423       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  4421         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4424         absTime->tv_nsec -= NANOSECS_PER_SEC;
  4422         ++absTime->tv_sec; // note: this must be <= max_secs
  4425         ++absTime->tv_sec; // note: this must be <= max_secs
  4548     assert(status == 0, "invariant");
  4551     assert(status == 0, "invariant");
  4549   }
  4552   }
  4550 }
  4553 }
  4551 
  4554 
  4552 
  4555 
  4553 /* Darwin has no "environ" in a dynamic library. */
  4556 // Darwin has no "environ" in a dynamic library.
  4554 #ifdef __APPLE__
  4557 #ifdef __APPLE__
  4555 #include <crt_externs.h>
  4558   #include <crt_externs.h>
  4556 #define environ (*_NSGetEnviron())
  4559   #define environ (*_NSGetEnviron())
  4557 #else
  4560 #else
  4558 extern char** environ;
  4561 extern char** environ;
  4559 #endif
  4562 #endif
  4560 
  4563 
  4561 // Run the specified command in a separate process. Return its exit value,
  4564 // Run the specified command in a separate process. Return its exit value,
  4647   // Get path to libjvm.so
  4650   // Get path to libjvm.so
  4648   os::jvm_path(buf, sizeof(buf));
  4651   os::jvm_path(buf, sizeof(buf));
  4649 
  4652 
  4650   // Get rid of libjvm.so
  4653   // Get rid of libjvm.so
  4651   p = strrchr(buf, '/');
  4654   p = strrchr(buf, '/');
  4652   if (p == NULL) return false;
  4655   if (p == NULL) {
  4653   else *p = '\0';
  4656     return false;
       
  4657   } else {
       
  4658     *p = '\0';
       
  4659   }
  4654 
  4660 
  4655   // Get rid of client or server
  4661   // Get rid of client or server
  4656   p = strrchr(buf, '/');
  4662   p = strrchr(buf, '/');
  4657   if (p == NULL) return false;
  4663   if (p == NULL) {
  4658   else *p = '\0';
  4664     return false;
       
  4665   } else {
       
  4666     *p = '\0';
       
  4667   }
  4659 
  4668 
  4660   // check xawt/libmawt.so
  4669   // check xawt/libmawt.so
  4661   strcpy(libmawtpath, buf);
  4670   strcpy(libmawtpath, buf);
  4662   strcat(libmawtpath, xawtstr);
  4671   strcat(libmawtpath, xawtstr);
  4663   if (::stat(libmawtpath, &statbuf) == 0) return false;
  4672   if (::stat(libmawtpath, &statbuf) == 0) return false;