1 /*
   2  * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // no precompiled headers
  26 #include "classfile/classLoader.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/vtableStubs.hpp"
  31 #include "compiler/compileBroker.hpp"
  32 #include "compiler/disassembler.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "jvm_bsd.h"
  35 #include "logging/log.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/filemap.hpp"
  38 #include "mutex_bsd.inline.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "os_bsd.inline.hpp"
  41 #include "os_share_bsd.hpp"
  42 #include "prims/jniFastGetField.hpp"
  43 #include "prims/jvm.h"
  44 #include "prims/jvm_misc.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/atomic.inline.hpp"
  47 #include "runtime/extendedPC.hpp"
  48 #include "runtime/globals.hpp"
  49 #include "runtime/interfaceSupport.hpp"
  50 #include "runtime/java.hpp"
  51 #include "runtime/javaCalls.hpp"
  52 #include "runtime/mutexLocker.hpp"
  53 #include "runtime/objectMonitor.hpp"
  54 #include "runtime/orderAccess.inline.hpp"
  55 #include "runtime/osThread.hpp"
  56 #include "runtime/perfMemory.hpp"
  57 #include "runtime/sharedRuntime.hpp"
  58 #include "runtime/statSampler.hpp"
  59 #include "runtime/stubRoutines.hpp"
  60 #include "runtime/thread.inline.hpp"
  61 #include "runtime/threadCritical.hpp"
  62 #include "runtime/timer.hpp"
  63 #include "semaphore_bsd.hpp"
  64 #include "services/attachListener.hpp"
  65 #include "services/memTracker.hpp"
  66 #include "services/runtimeService.hpp"
  67 #include "utilities/decoder.hpp"
  68 #include "utilities/defaultStream.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/growableArray.hpp"
  71 #include "utilities/vmError.hpp"
  72 
  73 // put OS-includes here
  74 # include <sys/types.h>
  75 # include <sys/mman.h>
  76 # include <sys/stat.h>
  77 # include <sys/select.h>
  78 # include <pthread.h>
  79 # include <signal.h>
  80 # include <errno.h>
  81 # include <dlfcn.h>
  82 # include <stdio.h>
  83 # include <unistd.h>
  84 # include <sys/resource.h>
  85 # include <pthread.h>
  86 # include <sys/stat.h>
  87 # include <sys/time.h>
  88 # include <sys/times.h>
  89 # include <sys/utsname.h>
  90 # include <sys/socket.h>
  91 # include <sys/wait.h>
  92 # include <time.h>
  93 # include <pwd.h>
  94 # include <poll.h>
  95 # include <semaphore.h>
  96 # include <fcntl.h>
  97 # include <string.h>
  98 # include <sys/param.h>
  99 # include <sys/sysctl.h>
 100 # include <sys/ipc.h>
 101 # include <sys/shm.h>
 102 #ifndef __APPLE__
 103 # include <link.h>
 104 #endif
 105 # include <stdint.h>
 106 # include <inttypes.h>
 107 # include <sys/ioctl.h>
 108 # include <sys/syscall.h>
 109 
 110 #if defined(__FreeBSD__) || defined(__NetBSD__)
 111   #include <elf.h>
 112 #endif
 113 
 114 #ifdef __APPLE__
 115   #include <mach/mach.h> // semaphore_* API
 116   #include <mach-o/dyld.h>
 117   #include <sys/proc_info.h>
 118   #include <objc/objc-auto.h>
 119 #endif
 120 
 121 #ifndef MAP_ANONYMOUS
 122   #define MAP_ANONYMOUS MAP_ANON
 123 #endif
 124 
 125 #define MAX_PATH    (2 * K)
 126 
 127 // for timer info max values which include all bits
 128 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 129 
 130 #define LARGEPAGES_BIT (1 << 6)
 131 
 132 ////////////////////////////////////////////////////////////////////////////////
 133 // global variables
 134 julong os::Bsd::_physical_memory = 0;
 135 
 136 #ifdef __APPLE__
 137 mach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0};
 138 volatile uint64_t         os::Bsd::_max_abstime   = 0;
 139 #else
 140 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
 141 #endif
 142 pthread_t os::Bsd::_main_thread;
 143 int os::Bsd::_page_size = -1;
 144 
 145 static jlong initial_time_count=0;
 146 
 147 static int clock_tics_per_sec = 100;
 148 
 149 // For diagnostics to print a message once. see run_periodic_checks
 150 static sigset_t check_signal_done;
 151 static bool check_signals = true;
 152 
 153 static pid_t _initial_pid = 0;
 154 
 155 // Signal number used to suspend/resume a thread
 156 
 157 // do not use any signal number less than SIGSEGV, see 4355769
 158 static int SR_signum = SIGUSR2;
 159 sigset_t SR_sigset;
 160 
 161 
 162 ////////////////////////////////////////////////////////////////////////////////
 163 // utility functions
 164 
 165 static int SR_initialize();
 166 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
 167 
 168 julong os::available_memory() {
 169   return Bsd::available_memory();
 170 }
 171 
 172 // available here means free
 173 julong os::Bsd::available_memory() {
 174   uint64_t available = physical_memory() >> 2;
 175 #ifdef __APPLE__
 176   mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
 177   vm_statistics64_data_t vmstat;
 178   kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64,
 179                                          (host_info64_t)&vmstat, &count);
 180   assert(kerr == KERN_SUCCESS,
 181          "host_statistics64 failed - check mach_host_self() and count");
 182   if (kerr == KERN_SUCCESS) {
 183     available = vmstat.free_count * os::vm_page_size();
 184   }
 185 #endif
 186   return available;
 187 }
 188 
 189 julong os::physical_memory() {
 190   return Bsd::physical_memory();
 191 }
 192 
 193 // Return true if user is running as root.
 194 
 195 bool os::have_special_privileges() {
 196   static bool init = false;
 197   static bool privileges = false;
 198   if (!init) {
 199     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 200     init = true;
 201   }
 202   return privileges;
 203 }
 204 
 205 
 206 
 207 // Cpu architecture string
 208 #if   defined(ZERO)
 209 static char cpu_arch[] = ZERO_LIBARCH;
 210 #elif defined(IA64)
 211 static char cpu_arch[] = "ia64";
 212 #elif defined(IA32)
 213 static char cpu_arch[] = "i386";
 214 #elif defined(AMD64)
 215 static char cpu_arch[] = "amd64";
 216 #elif defined(ARM)
 217 static char cpu_arch[] = "arm";
 218 #elif defined(PPC32)
 219 static char cpu_arch[] = "ppc";
 220 #elif defined(SPARC)
 221   #ifdef _LP64
 222 static char cpu_arch[] = "sparcv9";
 223   #else
 224 static char cpu_arch[] = "sparc";
 225   #endif
 226 #else
 227   #error Add appropriate cpu_arch setting
 228 #endif
 229 
 230 // Compiler variant
 231 #ifdef COMPILER2
 232   #define COMPILER_VARIANT "server"
 233 #else
 234   #define COMPILER_VARIANT "client"
 235 #endif
 236 
 237 
 238 void os::Bsd::initialize_system_info() {
 239   int mib[2];
 240   size_t len;
 241   int cpu_val;
 242   julong mem_val;
 243 
 244   // get processors count via hw.ncpus sysctl
 245   mib[0] = CTL_HW;
 246   mib[1] = HW_NCPU;
 247   len = sizeof(cpu_val);
 248   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
 249     assert(len == sizeof(cpu_val), "unexpected data size");
 250     set_processor_count(cpu_val);
 251   } else {
 252     set_processor_count(1);   // fallback
 253   }
 254 
 255   // get physical memory via hw.memsize sysctl (hw.memsize is used
 256   // since it returns a 64 bit value)
 257   mib[0] = CTL_HW;
 258 
 259 #if defined (HW_MEMSIZE) // Apple
 260   mib[1] = HW_MEMSIZE;
 261 #elif defined(HW_PHYSMEM) // Most of BSD
 262   mib[1] = HW_PHYSMEM;
 263 #elif defined(HW_REALMEM) // Old FreeBSD
 264   mib[1] = HW_REALMEM;
 265 #else
 266   #error No ways to get physmem
 267 #endif
 268 
 269   len = sizeof(mem_val);
 270   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
 271     assert(len == sizeof(mem_val), "unexpected data size");
 272     _physical_memory = mem_val;
 273   } else {
 274     _physical_memory = 256 * 1024 * 1024;       // fallback (XXXBSD?)
 275   }
 276 
 277 #ifdef __OpenBSD__
 278   {
 279     // limit _physical_memory memory view on OpenBSD since
 280     // datasize rlimit restricts us anyway.
 281     struct rlimit limits;
 282     getrlimit(RLIMIT_DATA, &limits);
 283     _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
 284   }
 285 #endif
 286 }
 287 
 288 #ifdef __APPLE__
 289 static const char *get_home() {
 290   const char *home_dir = ::getenv("HOME");
 291   if ((home_dir == NULL) || (*home_dir == '\0')) {
 292     struct passwd *passwd_info = getpwuid(geteuid());
 293     if (passwd_info != NULL) {
 294       home_dir = passwd_info->pw_dir;
 295     }
 296   }
 297 
 298   return home_dir;
 299 }
 300 #endif
 301 
 302 void os::init_system_properties_values() {
 303   // The next steps are taken in the product version:
 304   //
 305   // Obtain the JAVA_HOME value from the location of libjvm.so.
 306   // This library should be located at:
 307   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
 308   //
 309   // If "/jre/lib/" appears at the right place in the path, then we
 310   // assume libjvm.so is installed in a JDK and we use this path.
 311   //
 312   // Otherwise exit with message: "Could not create the Java virtual machine."
 313   //
 314   // The following extra steps are taken in the debugging version:
 315   //
 316   // If "/jre/lib/" does NOT appear at the right place in the path
 317   // instead of exit check for $JAVA_HOME environment variable.
 318   //
 319   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 320   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 321   // it looks like libjvm.so is installed there
 322   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 323   //
 324   // Otherwise exit.
 325   //
 326   // Important note: if the location of libjvm.so changes this
 327   // code needs to be changed accordingly.
 328 
 329   // See ld(1):
 330   //      The linker uses the following search paths to locate required
 331   //      shared libraries:
 332   //        1: ...
 333   //        ...
 334   //        7: The default directories, normally /lib and /usr/lib.
 335 #ifndef DEFAULT_LIBPATH
 336   #define DEFAULT_LIBPATH "/lib:/usr/lib"
 337 #endif
 338 
 339 // Base path of extensions installed on the system.
 340 #define SYS_EXT_DIR     "/usr/java/packages"
 341 #define EXTENSIONS_DIR  "/lib/ext"
 342 
 343 #ifndef __APPLE__
 344 
 345   // Buffer that fits several sprintfs.
 346   // Note that the space for the colon and the trailing null are provided
 347   // by the nulls included by the sizeof operator.
 348   const size_t bufsize =
 349     MAX2((size_t)MAXPATHLEN,  // For dll_dir & friends.
 350          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 351   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 352 
 353   // sysclasspath, java_home, dll_dir
 354   {
 355     char *pslash;
 356     os::jvm_path(buf, bufsize);
 357 
 358     // Found the full path to libjvm.so.
 359     // Now cut the path to <java_home>/jre if we can.
 360     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 361     pslash = strrchr(buf, '/');
 362     if (pslash != NULL) {
 363       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 364     }
 365     Arguments::set_dll_dir(buf);
 366 
 367     if (pslash != NULL) {
 368       pslash = strrchr(buf, '/');
 369       if (pslash != NULL) {
 370         *pslash = '\0';          // Get rid of /<arch>.
 371         pslash = strrchr(buf, '/');
 372         if (pslash != NULL) {
 373           *pslash = '\0';        // Get rid of /lib.
 374         }
 375       }
 376     }
 377     Arguments::set_java_home(buf);
 378     set_boot_path('/', ':');
 379   }
 380 
 381   // Where to look for native libraries.
 382   //
 383   // Note: Due to a legacy implementation, most of the library path
 384   // is set in the launcher. This was to accomodate linking restrictions
 385   // on legacy Bsd implementations (which are no longer supported).
 386   // Eventually, all the library path setting will be done here.
 387   //
 388   // However, to prevent the proliferation of improperly built native
 389   // libraries, the new path component /usr/java/packages is added here.
 390   // Eventually, all the library path setting will be done here.
 391   {
 392     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 393     // should always exist (until the legacy problem cited above is
 394     // addressed).
 395     const char *v = ::getenv("LD_LIBRARY_PATH");
 396     const char *v_colon = ":";
 397     if (v == NULL) { v = ""; v_colon = ""; }
 398     // That's +1 for the colon and +1 for the trailing '\0'.
 399     char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
 400                                                      strlen(v) + 1 +
 401                                                      sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
 402                                                      mtInternal);
 403     sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
 404     Arguments::set_library_path(ld_library_path);
 405     FREE_C_HEAP_ARRAY(char, ld_library_path);
 406   }
 407 
 408   // Extensions directories.
 409   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 410   Arguments::set_ext_dirs(buf);
 411 
 412   FREE_C_HEAP_ARRAY(char, buf);
 413 
 414 #else // __APPLE__
 415 
 416   #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
 417   #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
 418 
 419   const char *user_home_dir = get_home();
 420   // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
 421   size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
 422     sizeof(SYS_EXTENSIONS_DIRS);
 423 
 424   // Buffer that fits several sprintfs.
 425   // Note that the space for the colon and the trailing null are provided
 426   // by the nulls included by the sizeof operator.
 427   const size_t bufsize =
 428     MAX2((size_t)MAXPATHLEN,  // for dll_dir & friends.
 429          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size); // extensions dir
 430   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 431 
 432   // sysclasspath, java_home, dll_dir
 433   {
 434     char *pslash;
 435     os::jvm_path(buf, bufsize);
 436 
 437     // Found the full path to libjvm.so.
 438     // Now cut the path to <java_home>/jre if we can.
 439     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 440     pslash = strrchr(buf, '/');
 441     if (pslash != NULL) {
 442       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 443     }
 444 #ifdef STATIC_BUILD
 445     strcat(buf, "/lib");
 446 #endif
 447 
 448     Arguments::set_dll_dir(buf);
 449 
 450     if (pslash != NULL) {
 451       pslash = strrchr(buf, '/');
 452       if (pslash != NULL) {
 453         *pslash = '\0';          // Get rid of /lib.
 454       }
 455     }
 456     Arguments::set_java_home(buf);
 457     set_boot_path('/', ':');
 458   }
 459 
 460   // Where to look for native libraries.
 461   //
 462   // Note: Due to a legacy implementation, most of the library path
 463   // is set in the launcher. This was to accomodate linking restrictions
 464   // on legacy Bsd implementations (which are no longer supported).
 465   // Eventually, all the library path setting will be done here.
 466   //
 467   // However, to prevent the proliferation of improperly built native
 468   // libraries, the new path component /usr/java/packages is added here.
 469   // Eventually, all the library path setting will be done here.
 470   {
 471     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 472     // should always exist (until the legacy problem cited above is
 473     // addressed).
 474     // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code
 475     // can specify a directory inside an app wrapper
 476     const char *l = ::getenv("JAVA_LIBRARY_PATH");
 477     const char *l_colon = ":";
 478     if (l == NULL) { l = ""; l_colon = ""; }
 479 
 480     const char *v = ::getenv("DYLD_LIBRARY_PATH");
 481     const char *v_colon = ":";
 482     if (v == NULL) { v = ""; v_colon = ""; }
 483 
 484     // Apple's Java6 has "." at the beginning of java.library.path.
 485     // OpenJDK on Windows has "." at the end of java.library.path.
 486     // OpenJDK on Linux and Solaris don't have "." in java.library.path
 487     // at all. To ease the transition from Apple's Java6 to OpenJDK7,
 488     // "." is appended to the end of java.library.path. Yes, this
 489     // could cause a change in behavior, but Apple's Java6 behavior
 490     // can be achieved by putting "." at the beginning of the
 491     // JAVA_LIBRARY_PATH environment variable.
 492     char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
 493                                                      strlen(v) + 1 + strlen(l) + 1 +
 494                                                      system_ext_size + 3,
 495                                                      mtInternal);
 496     sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",
 497             v, v_colon, l, l_colon, user_home_dir);
 498     Arguments::set_library_path(ld_library_path);
 499     FREE_C_HEAP_ARRAY(char, ld_library_path);
 500   }
 501 
 502   // Extensions directories.
 503   //
 504   // Note that the space for the colon and the trailing null are provided
 505   // by the nulls included by the sizeof operator (so actually one byte more
 506   // than necessary is allocated).
 507   sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,
 508           user_home_dir, Arguments::get_java_home());
 509   Arguments::set_ext_dirs(buf);
 510 
 511   FREE_C_HEAP_ARRAY(char, buf);
 512 
 513 #undef SYS_EXTENSIONS_DIR
 514 #undef SYS_EXTENSIONS_DIRS
 515 
 516 #endif // __APPLE__
 517 
 518 #undef SYS_EXT_DIR
 519 #undef EXTENSIONS_DIR
 520 }
 521 
 522 ////////////////////////////////////////////////////////////////////////////////
 523 // breakpoint support
 524 
 525 void os::breakpoint() {
 526   BREAKPOINT;
 527 }
 528 
 529 extern "C" void breakpoint() {
 530   // use debugger to set breakpoint here
 531 }
 532 
 533 ////////////////////////////////////////////////////////////////////////////////
 534 // signal support
 535 
 536 debug_only(static bool signal_sets_initialized = false);
 537 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
 538 
 539 bool os::Bsd::is_sig_ignored(int sig) {
 540   struct sigaction oact;
 541   sigaction(sig, (struct sigaction*)NULL, &oact);
 542   void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
 543                                  : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
 544   if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) {
 545     return true;
 546   } else {
 547     return false;
 548   }
 549 }
 550 
 551 void os::Bsd::signal_sets_init() {
 552   // Should also have an assertion stating we are still single-threaded.
 553   assert(!signal_sets_initialized, "Already initialized");
 554   // Fill in signals that are necessarily unblocked for all threads in
 555   // the VM. Currently, we unblock the following signals:
 556   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
 557   //                         by -Xrs (=ReduceSignalUsage));
 558   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
 559   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
 560   // the dispositions or masks wrt these signals.
 561   // Programs embedding the VM that want to use the above signals for their
 562   // own purposes must, at this time, use the "-Xrs" option to prevent
 563   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
 564   // (See bug 4345157, and other related bugs).
 565   // In reality, though, unblocking these signals is really a nop, since
 566   // these signals are not blocked by default.
 567   sigemptyset(&unblocked_sigs);
 568   sigemptyset(&allowdebug_blocked_sigs);
 569   sigaddset(&unblocked_sigs, SIGILL);
 570   sigaddset(&unblocked_sigs, SIGSEGV);
 571   sigaddset(&unblocked_sigs, SIGBUS);
 572   sigaddset(&unblocked_sigs, SIGFPE);
 573   sigaddset(&unblocked_sigs, SR_signum);
 574 
 575   if (!ReduceSignalUsage) {
 576     if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
 577       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
 578       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
 579     }
 580     if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
 581       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
 582       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
 583     }
 584     if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
 585       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
 586       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
 587     }
 588   }
 589   // Fill in signals that are blocked by all but the VM thread.
 590   sigemptyset(&vm_sigs);
 591   if (!ReduceSignalUsage) {
 592     sigaddset(&vm_sigs, BREAK_SIGNAL);
 593   }
 594   debug_only(signal_sets_initialized = true);
 595 
 596 }
 597 
 598 // These are signals that are unblocked while a thread is running Java.
 599 // (For some reason, they get blocked by default.)
 600 sigset_t* os::Bsd::unblocked_signals() {
 601   assert(signal_sets_initialized, "Not initialized");
 602   return &unblocked_sigs;
 603 }
 604 
 605 // These are the signals that are blocked while a (non-VM) thread is
 606 // running Java. Only the VM thread handles these signals.
 607 sigset_t* os::Bsd::vm_signals() {
 608   assert(signal_sets_initialized, "Not initialized");
 609   return &vm_sigs;
 610 }
 611 
 612 // These are signals that are blocked during cond_wait to allow debugger in
 613 sigset_t* os::Bsd::allowdebug_blocked_signals() {
 614   assert(signal_sets_initialized, "Not initialized");
 615   return &allowdebug_blocked_sigs;
 616 }
 617 
 618 void os::Bsd::hotspot_sigmask(Thread* thread) {
 619 
 620   //Save caller's signal mask before setting VM signal mask
 621   sigset_t caller_sigmask;
 622   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
 623 
 624   OSThread* osthread = thread->osthread();
 625   osthread->set_caller_sigmask(caller_sigmask);
 626 
 627   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
 628 
 629   if (!ReduceSignalUsage) {
 630     if (thread->is_VM_thread()) {
 631       // Only the VM thread handles BREAK_SIGNAL ...
 632       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
 633     } else {
 634       // ... all other threads block BREAK_SIGNAL
 635       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
 636     }
 637   }
 638 }
 639 
 640 
 641 //////////////////////////////////////////////////////////////////////////////
 642 // create new thread
 643 
 644 #ifdef __APPLE__
 645 // library handle for calling objc_registerThreadWithCollector()
 646 // without static linking to the libobjc library
 647   #define OBJC_LIB "/usr/lib/libobjc.dylib"
 648   #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
 649 typedef void (*objc_registerThreadWithCollector_t)();
 650 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
 651 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
 652 #endif
 653 
 654 #ifdef __APPLE__
 655 static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {
 656   // Additional thread_id used to correlate threads in SA
 657   thread_identifier_info_data_t     m_ident_info;
 658   mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
 659 
 660   thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,
 661               (thread_info_t) &m_ident_info, &count);
 662 
 663   return m_ident_info.thread_id;
 664 }
 665 #endif
 666 
 667 // Thread start routine for all newly created threads
 668 static void *java_start(Thread *thread) {
 669   // Try to randomize the cache line index of hot stack frames.
 670   // This helps when threads of the same stack traces evict each other's
 671   // cache lines. The threads can be either from the same JVM instance, or
 672   // from different JVM instances. The benefit is especially true for
 673   // processors with hyperthreading technology.
 674   static int counter = 0;
 675   int pid = os::current_process_id();
 676   alloca(((pid ^ counter++) & 7) * 128);
 677 
 678   thread->initialize_thread_current();
 679 
 680   OSThread* osthread = thread->osthread();
 681   Monitor* sync = osthread->startThread_lock();
 682 
 683   osthread->set_thread_id(os::Bsd::gettid());
 684 
 685   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 686     os::current_thread_id(), (uintx) pthread_self());
 687 
 688 #ifdef __APPLE__
 689   uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
 690   guarantee(unique_thread_id != 0, "unique thread id was not found");
 691   osthread->set_unique_thread_id(unique_thread_id);
 692 #endif
 693   // initialize signal mask for this thread
 694   os::Bsd::hotspot_sigmask(thread);
 695 
 696   // initialize floating point control register
 697   os::Bsd::init_thread_fpu_state();
 698 
 699 #ifdef __APPLE__
 700   // register thread with objc gc
 701   if (objc_registerThreadWithCollectorFunction != NULL) {
 702     objc_registerThreadWithCollectorFunction();
 703   }
 704 #endif
 705 
 706   // handshaking with parent thread
 707   {
 708     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
 709 
 710     // notify parent thread
 711     osthread->set_state(INITIALIZED);
 712     sync->notify_all();
 713 
 714     // wait until os::start_thread()
 715     while (osthread->get_state() == INITIALIZED) {
 716       sync->wait(Mutex::_no_safepoint_check_flag);
 717     }
 718   }
 719 
 720   // call one more level start routine
 721   thread->run();
 722 
 723   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 724     os::current_thread_id(), (uintx) pthread_self());
 725 
 726   return 0;
 727 }
 728 
 729 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
 730   assert(thread->osthread() == NULL, "caller responsible");
 731 
 732   // Allocate the OSThread object
 733   OSThread* osthread = new OSThread(NULL, NULL);
 734   if (osthread == NULL) {
 735     return false;
 736   }
 737 
 738   // set the correct thread state
 739   osthread->set_thread_type(thr_type);
 740 
 741   // Initial state is ALLOCATED but not INITIALIZED
 742   osthread->set_state(ALLOCATED);
 743 
 744   thread->set_osthread(osthread);
 745 
 746   // init thread attributes
 747   pthread_attr_t attr;
 748   pthread_attr_init(&attr);
 749   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 750 
 751   // calculate stack size if it's not specified by caller
 752   if (stack_size == 0) {
 753     stack_size = os::Bsd::default_stack_size(thr_type);
 754 
 755     switch (thr_type) {
 756     case os::java_thread:
 757       // Java threads use ThreadStackSize which default value can be
 758       // changed with the flag -Xss
 759       assert(JavaThread::stack_size_at_create() > 0, "this should be set");
 760       stack_size = JavaThread::stack_size_at_create();
 761       break;
 762     case os::compiler_thread:
 763       if (CompilerThreadStackSize > 0) {
 764         stack_size = (size_t)(CompilerThreadStackSize * K);
 765         break;
 766       } // else fall through:
 767         // use VMThreadStackSize if CompilerThreadStackSize is not defined
 768     case os::vm_thread:
 769     case os::pgc_thread:
 770     case os::cgc_thread:
 771     case os::watcher_thread:
 772       if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
 773       break;
 774     }
 775   }
 776 
 777   stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
 778   pthread_attr_setstacksize(&attr, stack_size);
 779 
 780   ThreadState state;
 781 
 782   {
 783     pthread_t tid;
 784     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
 785 
 786     char buf[64];
 787     if (ret == 0) {
 788       log_info(os, thread)("Thread started (pthread id: " UINTX_FORMAT ", attributes: %s). ",
 789         (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 790     } else {
 791       log_warning(os, thread)("Failed to start thread - pthread_create failed (%s) for attributes: %s.",
 792         os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 793     }
 794 
 795     pthread_attr_destroy(&attr);
 796 
 797     if (ret != 0) {
 798       // Need to clean up stuff we've allocated so far
 799       thread->set_osthread(NULL);
 800       delete osthread;
 801       return false;
 802     }
 803 
 804     // Store pthread info into the OSThread
 805     osthread->set_pthread_id(tid);
 806 
 807     // Wait until child thread is either initialized or aborted
 808     {
 809       Monitor* sync_with_child = osthread->startThread_lock();
 810       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 811       while ((state = osthread->get_state()) == ALLOCATED) {
 812         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
 813       }
 814     }
 815 
 816   }
 817 
 818   // Aborted due to thread limit being reached
 819   if (state == ZOMBIE) {
 820     thread->set_osthread(NULL);
 821     delete osthread;
 822     return false;
 823   }
 824 
 825   // The thread is returned suspended (in state INITIALIZED),
 826   // and is started higher up in the call chain
 827   assert(state == INITIALIZED, "race condition");
 828   return true;
 829 }
 830 
 831 /////////////////////////////////////////////////////////////////////////////
 832 // attach existing thread
 833 
 834 // bootstrap the main thread
 835 bool os::create_main_thread(JavaThread* thread) {
 836   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
 837   return create_attached_thread(thread);
 838 }
 839 
 840 bool os::create_attached_thread(JavaThread* thread) {
 841 #ifdef ASSERT
 842   thread->verify_not_published();
 843 #endif
 844 
 845   // Allocate the OSThread object
 846   OSThread* osthread = new OSThread(NULL, NULL);
 847 
 848   if (osthread == NULL) {
 849     return false;
 850   }
 851 
 852   osthread->set_thread_id(os::Bsd::gettid());
 853 
 854   // Store pthread info into the OSThread
 855 #ifdef __APPLE__
 856   uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
 857   guarantee(unique_thread_id != 0, "just checking");
 858   osthread->set_unique_thread_id(unique_thread_id);
 859 #endif
 860   osthread->set_pthread_id(::pthread_self());
 861 
 862   // initialize floating point control register
 863   os::Bsd::init_thread_fpu_state();
 864 
 865   // Initial thread state is RUNNABLE
 866   osthread->set_state(RUNNABLE);
 867 
 868   thread->set_osthread(osthread);
 869 
 870   // initialize signal mask for this thread
 871   // and save the caller's signal mask
 872   os::Bsd::hotspot_sigmask(thread);
 873 
 874   log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 875     os::current_thread_id(), (uintx) pthread_self());
 876 
 877   return true;
 878 }
 879 
 880 void os::pd_start_thread(Thread* thread) {
 881   OSThread * osthread = thread->osthread();
 882   assert(osthread->get_state() != INITIALIZED, "just checking");
 883   Monitor* sync_with_child = osthread->startThread_lock();
 884   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 885   sync_with_child->notify();
 886 }
 887 
 888 // Free Bsd resources related to the OSThread
 889 void os::free_thread(OSThread* osthread) {
 890   assert(osthread != NULL, "osthread not set");
 891 
 892   if (Thread::current()->osthread() == osthread) {
 893     // Restore caller's signal mask
 894     sigset_t sigmask = osthread->caller_sigmask();
 895     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
 896   }
 897 
 898   delete osthread;
 899 }
 900 
 901 ////////////////////////////////////////////////////////////////////////////////
 902 // time support
 903 
 904 // Time since start-up in seconds to a fine granularity.
 905 // Used by VMSelfDestructTimer and the MemProfiler.
 906 double os::elapsedTime() {
 907 
 908   return ((double)os::elapsed_counter()) / os::elapsed_frequency();
 909 }
 910 
 911 jlong os::elapsed_counter() {
 912   return javaTimeNanos() - initial_time_count;
 913 }
 914 
 915 jlong os::elapsed_frequency() {
 916   return NANOSECS_PER_SEC; // nanosecond resolution
 917 }
 918 
 919 bool os::supports_vtime() { return true; }
 920 bool os::enable_vtime()   { return false; }
 921 bool os::vtime_enabled()  { return false; }
 922 
 923 double os::elapsedVTime() {
 924   // better than nothing, but not much
 925   return elapsedTime();
 926 }
 927 
 928 jlong os::javaTimeMillis() {
 929   timeval time;
 930   int status = gettimeofday(&time, NULL);
 931   assert(status != -1, "bsd error");
 932   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
 933 }
 934 
 935 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
 936   timeval time;
 937   int status = gettimeofday(&time, NULL);
 938   assert(status != -1, "bsd error");
 939   seconds = jlong(time.tv_sec);
 940   nanos = jlong(time.tv_usec) * 1000;
 941 }
 942 
 943 #ifndef __APPLE__
 944   #ifndef CLOCK_MONOTONIC
 945     #define CLOCK_MONOTONIC (1)
 946   #endif
 947 #endif
 948 
 949 #ifdef __APPLE__
 950 void os::Bsd::clock_init() {
 951   mach_timebase_info(&_timebase_info);
 952 }
 953 #else
 954 void os::Bsd::clock_init() {
 955   struct timespec res;
 956   struct timespec tp;
 957   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
 958       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
 959     // yes, monotonic clock is supported
 960     _clock_gettime = ::clock_gettime;
 961   }
 962 }
 963 #endif
 964 
 965 
 966 
 967 #ifdef __APPLE__
 968 
 969 jlong os::javaTimeNanos() {
 970   const uint64_t tm = mach_absolute_time();
 971   const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;
 972   const uint64_t prev = Bsd::_max_abstime;
 973   if (now <= prev) {
 974     return prev;   // same or retrograde time;
 975   }
 976   const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev);
 977   assert(obsv >= prev, "invariant");   // Monotonicity
 978   // If the CAS succeeded then we're done and return "now".
 979   // If the CAS failed and the observed value "obsv" is >= now then
 980   // we should return "obsv".  If the CAS failed and now > obsv > prv then
 981   // some other thread raced this thread and installed a new value, in which case
 982   // we could either (a) retry the entire operation, (b) retry trying to install now
 983   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
 984   // we might discard a higher "now" value in deference to a slightly lower but freshly
 985   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
 986   // to (a) or (b) -- and greatly reduces coherence traffic.
 987   // We might also condition (c) on the magnitude of the delta between obsv and now.
 988   // Avoiding excessive CAS operations to hot RW locations is critical.
 989   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
 990   return (prev == obsv) ? now : obsv;
 991 }
 992 
 993 #else // __APPLE__
 994 
 995 jlong os::javaTimeNanos() {
 996   if (os::supports_monotonic_clock()) {
 997     struct timespec tp;
 998     int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp);
 999     assert(status == 0, "gettime error");
1000     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1001     return result;
1002   } else {
1003     timeval time;
1004     int status = gettimeofday(&time, NULL);
1005     assert(status != -1, "bsd error");
1006     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1007     return 1000 * usecs;
1008   }
1009 }
1010 
1011 #endif // __APPLE__
1012 
1013 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1014   if (os::supports_monotonic_clock()) {
1015     info_ptr->max_value = ALL_64_BITS;
1016 
1017     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1018     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
1019     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
1020   } else {
1021     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1022     info_ptr->max_value = ALL_64_BITS;
1023 
1024     // gettimeofday is a real time clock so it skips
1025     info_ptr->may_skip_backward = true;
1026     info_ptr->may_skip_forward = true;
1027   }
1028 
1029   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
1030 }
1031 
1032 // Return the real, user, and system times in seconds from an
1033 // arbitrary fixed point in the past.
1034 bool os::getTimesSecs(double* process_real_time,
1035                       double* process_user_time,
1036                       double* process_system_time) {
1037   struct tms ticks;
1038   clock_t real_ticks = times(&ticks);
1039 
1040   if (real_ticks == (clock_t) (-1)) {
1041     return false;
1042   } else {
1043     double ticks_per_second = (double) clock_tics_per_sec;
1044     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1045     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1046     *process_real_time = ((double) real_ticks) / ticks_per_second;
1047 
1048     return true;
1049   }
1050 }
1051 
1052 
1053 char * os::local_time_string(char *buf, size_t buflen) {
1054   struct tm t;
1055   time_t long_time;
1056   time(&long_time);
1057   localtime_r(&long_time, &t);
1058   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1059                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1060                t.tm_hour, t.tm_min, t.tm_sec);
1061   return buf;
1062 }
1063 
1064 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
1065   return localtime_r(clock, res);
1066 }
1067 
1068 ////////////////////////////////////////////////////////////////////////////////
1069 // runtime exit support
1070 
1071 // Note: os::shutdown() might be called very early during initialization, or
1072 // called from signal handler. Before adding something to os::shutdown(), make
1073 // sure it is async-safe and can handle partially initialized VM.
1074 void os::shutdown() {
1075 
1076   // allow PerfMemory to attempt cleanup of any persistent resources
1077   perfMemory_exit();
1078 
1079   // needs to remove object in file system
1080   AttachListener::abort();
1081 
1082   // flush buffered output, finish log files
1083   ostream_abort();
1084 
1085   // Check for abort hook
1086   abort_hook_t abort_hook = Arguments::abort_hook();
1087   if (abort_hook != NULL) {
1088     abort_hook();
1089   }
1090 
1091 }
1092 
1093 // Note: os::abort() might be called very early during initialization, or
1094 // called from signal handler. Before adding something to os::abort(), make
1095 // sure it is async-safe and can handle partially initialized VM.
1096 void os::abort(bool dump_core, void* siginfo, const void* context) {
1097   os::shutdown();
1098   if (dump_core) {
1099 #ifndef PRODUCT
1100     fdStream out(defaultStream::output_fd());
1101     out.print_raw("Current thread is ");
1102     char buf[16];
1103     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1104     out.print_raw_cr(buf);
1105     out.print_raw_cr("Dumping core ...");
1106 #endif
1107     ::abort(); // dump core
1108   }
1109 
1110   ::exit(1);
1111 }
1112 
1113 // Die immediately, no exit hook, no abort hook, no cleanup.
1114 void os::die() {
1115   // _exit() on BsdThreads only kills current thread
1116   ::abort();
1117 }
1118 
1119 // This method is a copy of JDK's sysGetLastErrorString
1120 // from src/solaris/hpi/src/system_md.c
1121 
1122 size_t os::lasterror(char *buf, size_t len) {
1123   if (errno == 0)  return 0;
1124 
1125   const char *s = os::strerror(errno);
1126   size_t n = ::strlen(s);
1127   if (n >= len) {
1128     n = len - 1;
1129   }
1130   ::strncpy(buf, s, n);
1131   buf[n] = '\0';
1132   return n;
1133 }
1134 
1135 // Information of current thread in variety of formats
1136 pid_t os::Bsd::gettid() {
1137   int retval = -1;
1138 
1139 #ifdef __APPLE__ //XNU kernel
1140   // despite the fact mach port is actually not a thread id use it
1141   // instead of syscall(SYS_thread_selfid) as it certainly fits to u4
1142   retval = ::pthread_mach_thread_np(::pthread_self());
1143   guarantee(retval != 0, "just checking");
1144   return retval;
1145 
1146 #else
1147   #ifdef __FreeBSD__
1148   retval = syscall(SYS_thr_self);
1149   #else
1150     #ifdef __OpenBSD__
1151   retval = syscall(SYS_getthrid);
1152     #else
1153       #ifdef __NetBSD__
1154   retval = (pid_t) syscall(SYS__lwp_self);
1155       #endif
1156     #endif
1157   #endif
1158 #endif
1159 
1160   if (retval == -1) {
1161     return getpid();
1162   }
1163 }
1164 
1165 intx os::current_thread_id() {
1166 #ifdef __APPLE__
1167   return (intx)::pthread_mach_thread_np(::pthread_self());
1168 #else
1169   return (intx)::pthread_self();
1170 #endif
1171 }
1172 
1173 int os::current_process_id() {
1174 
1175   // Under the old bsd thread library, bsd gives each thread
1176   // its own process id. Because of this each thread will return
1177   // a different pid if this method were to return the result
1178   // of getpid(2). Bsd provides no api that returns the pid
1179   // of the launcher thread for the vm. This implementation
1180   // returns a unique pid, the pid of the launcher thread
1181   // that starts the vm 'process'.
1182 
1183   // Under the NPTL, getpid() returns the same pid as the
1184   // launcher thread rather than a unique pid per thread.
1185   // Use gettid() if you want the old pre NPTL behaviour.
1186 
1187   // if you are looking for the result of a call to getpid() that
1188   // returns a unique pid for the calling thread, then look at the
1189   // OSThread::thread_id() method in osThread_bsd.hpp file
1190 
1191   return (int)(_initial_pid ? _initial_pid : getpid());
1192 }
1193 
1194 // DLL functions
1195 
1196 #define JNI_LIB_PREFIX "lib"
1197 #ifdef __APPLE__
1198   #define JNI_LIB_SUFFIX ".dylib"
1199 #else
1200   #define JNI_LIB_SUFFIX ".so"
1201 #endif
1202 
1203 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1204 
1205 // This must be hard coded because it's the system's temporary
1206 // directory not the java application's temp directory, ala java.io.tmpdir.
1207 #ifdef __APPLE__
1208 // macosx has a secure per-user temporary directory
1209 char temp_path_storage[PATH_MAX];
1210 const char* os::get_temp_directory() {
1211   static char *temp_path = NULL;
1212   if (temp_path == NULL) {
1213     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1214     if (pathSize == 0 || pathSize > PATH_MAX) {
1215       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1216     }
1217     temp_path = temp_path_storage;
1218   }
1219   return temp_path;
1220 }
1221 #else // __APPLE__
1222 const char* os::get_temp_directory() { return "/tmp"; }
1223 #endif // __APPLE__
1224 
1225 static bool file_exists(const char* filename) {
1226   struct stat statbuf;
1227   if (filename == NULL || strlen(filename) == 0) {
1228     return false;
1229   }
1230   return os::stat(filename, &statbuf) == 0;
1231 }
1232 
1233 bool os::dll_build_name(char* buffer, size_t buflen,
1234                         const char* pname, const char* fname) {
1235   bool retval = false;
1236   // Copied from libhpi
1237   const size_t pnamelen = pname ? strlen(pname) : 0;
1238 
1239   // Return error on buffer overflow.
1240   if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
1241     return retval;
1242   }
1243 
1244   if (pnamelen == 0) {
1245     snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
1246     retval = true;
1247   } else if (strchr(pname, *os::path_separator()) != NULL) {
1248     int n;
1249     char** pelements = split_path(pname, &n);
1250     if (pelements == NULL) {
1251       return false;
1252     }
1253     for (int i = 0; i < n; i++) {
1254       // Really shouldn't be NULL, but check can't hurt
1255       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1256         continue; // skip the empty path values
1257       }
1258       snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
1259                pelements[i], fname);
1260       if (file_exists(buffer)) {
1261         retval = true;
1262         break;
1263       }
1264     }
1265     // release the storage
1266     for (int i = 0; i < n; i++) {
1267       if (pelements[i] != NULL) {
1268         FREE_C_HEAP_ARRAY(char, pelements[i]);
1269       }
1270     }
1271     if (pelements != NULL) {
1272       FREE_C_HEAP_ARRAY(char*, pelements);
1273     }
1274   } else {
1275     snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
1276     retval = true;
1277   }
1278   return retval;
1279 }
1280 
1281 // check if addr is inside libjvm.so
1282 bool os::address_is_in_vm(address addr) {
1283   static address libjvm_base_addr;
1284   Dl_info dlinfo;
1285 
1286   if (libjvm_base_addr == NULL) {
1287     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1288       libjvm_base_addr = (address)dlinfo.dli_fbase;
1289     }
1290     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1291   }
1292 
1293   if (dladdr((void *)addr, &dlinfo) != 0) {
1294     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1295   }
1296 
1297   return false;
1298 }
1299 
1300 
1301 #define MACH_MAXSYMLEN 256
1302 
1303 bool os::dll_address_to_function_name(address addr, char *buf,
1304                                       int buflen, int *offset,
1305                                       bool demangle) {
1306   // buf is not optional, but offset is optional
1307   assert(buf != NULL, "sanity check");
1308 
1309   Dl_info dlinfo;
1310   char localbuf[MACH_MAXSYMLEN];
1311 
1312   if (dladdr((void*)addr, &dlinfo) != 0) {
1313     // see if we have a matching symbol
1314     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1315       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1316         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1317       }
1318       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1319       return true;
1320     }
1321     // no matching symbol so try for just file info
1322     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1323       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1324                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1325         return true;
1326       }
1327     }
1328 
1329     // Handle non-dynamic manually:
1330     if (dlinfo.dli_fbase != NULL &&
1331         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
1332                         dlinfo.dli_fbase)) {
1333       if (!(demangle && Decoder::demangle(localbuf, buf, buflen))) {
1334         jio_snprintf(buf, buflen, "%s", localbuf);
1335       }
1336       return true;
1337     }
1338   }
1339   buf[0] = '\0';
1340   if (offset != NULL) *offset = -1;
1341   return false;
1342 }
1343 
1344 // ported from solaris version
1345 bool os::dll_address_to_library_name(address addr, char* buf,
1346                                      int buflen, int* offset) {
1347   // buf is not optional, but offset is optional
1348   assert(buf != NULL, "sanity check");
1349 
1350   Dl_info dlinfo;
1351 
1352   if (dladdr((void*)addr, &dlinfo) != 0) {
1353     if (dlinfo.dli_fname != NULL) {
1354       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1355     }
1356     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1357       *offset = addr - (address)dlinfo.dli_fbase;
1358     }
1359     return true;
1360   }
1361 
1362   buf[0] = '\0';
1363   if (offset) *offset = -1;
1364   return false;
1365 }
1366 
1367 // Loads .dll/.so and
1368 // in case of error it checks if .dll/.so was built for the
1369 // same architecture as Hotspot is running on
1370 
1371 #ifdef __APPLE__
1372 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1373 #ifdef STATIC_BUILD
1374   return os::get_default_process_handle();
1375 #else
1376   void * result= ::dlopen(filename, RTLD_LAZY);
1377   if (result != NULL) {
1378     // Successful loading
1379     return result;
1380   }
1381 
1382   // Read system error message into ebuf
1383   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1384   ebuf[ebuflen-1]='\0';
1385 
1386   return NULL;
1387 #endif // STATIC_BUILD
1388 }
1389 #else
1390 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1391 #ifdef STATIC_BUILD
1392   return os::get_default_process_handle();
1393 #else
1394   void * result= ::dlopen(filename, RTLD_LAZY);
1395   if (result != NULL) {
1396     // Successful loading
1397     return result;
1398   }
1399 
1400   Elf32_Ehdr elf_head;
1401 
1402   // Read system error message into ebuf
1403   // It may or may not be overwritten below
1404   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1405   ebuf[ebuflen-1]='\0';
1406   int diag_msg_max_length=ebuflen-strlen(ebuf);
1407   char* diag_msg_buf=ebuf+strlen(ebuf);
1408 
1409   if (diag_msg_max_length==0) {
1410     // No more space in ebuf for additional diagnostics message
1411     return NULL;
1412   }
1413 
1414 
1415   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1416 
1417   if (file_descriptor < 0) {
1418     // Can't open library, report dlerror() message
1419     return NULL;
1420   }
1421 
1422   bool failed_to_read_elf_head=
1423     (sizeof(elf_head)!=
1424      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1425 
1426   ::close(file_descriptor);
1427   if (failed_to_read_elf_head) {
1428     // file i/o error - report dlerror() msg
1429     return NULL;
1430   }
1431 
1432   typedef struct {
1433     Elf32_Half  code;         // Actual value as defined in elf.h
1434     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1435     char        elf_class;    // 32 or 64 bit
1436     char        endianess;    // MSB or LSB
1437     char*       name;         // String representation
1438   } arch_t;
1439 
1440   #ifndef EM_486
1441     #define EM_486          6               /* Intel 80486 */
1442   #endif
1443 
1444   #ifndef EM_MIPS_RS3_LE
1445     #define EM_MIPS_RS3_LE  10              /* MIPS */
1446   #endif
1447 
1448   #ifndef EM_PPC64
1449     #define EM_PPC64        21              /* PowerPC64 */
1450   #endif
1451 
1452   #ifndef EM_S390
1453     #define EM_S390         22              /* IBM System/390 */
1454   #endif
1455 
1456   #ifndef EM_IA_64
1457     #define EM_IA_64        50              /* HP/Intel IA-64 */
1458   #endif
1459 
1460   #ifndef EM_X86_64
1461     #define EM_X86_64       62              /* AMD x86-64 */
1462   #endif
1463 
1464   static const arch_t arch_array[]={
1465     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1466     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1467     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1468     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1469     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1470     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1471     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1472     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1473     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1474     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1475     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1476     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1477     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1478     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1479     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1480     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1481   };
1482 
1483   #if  (defined IA32)
1484   static  Elf32_Half running_arch_code=EM_386;
1485   #elif   (defined AMD64)
1486   static  Elf32_Half running_arch_code=EM_X86_64;
1487   #elif  (defined IA64)
1488   static  Elf32_Half running_arch_code=EM_IA_64;
1489   #elif  (defined __sparc) && (defined _LP64)
1490   static  Elf32_Half running_arch_code=EM_SPARCV9;
1491   #elif  (defined __sparc) && (!defined _LP64)
1492   static  Elf32_Half running_arch_code=EM_SPARC;
1493   #elif  (defined __powerpc64__)
1494   static  Elf32_Half running_arch_code=EM_PPC64;
1495   #elif  (defined __powerpc__)
1496   static  Elf32_Half running_arch_code=EM_PPC;
1497   #elif  (defined ARM)
1498   static  Elf32_Half running_arch_code=EM_ARM;
1499   #elif  (defined S390)
1500   static  Elf32_Half running_arch_code=EM_S390;
1501   #elif  (defined ALPHA)
1502   static  Elf32_Half running_arch_code=EM_ALPHA;
1503   #elif  (defined MIPSEL)
1504   static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1505   #elif  (defined PARISC)
1506   static  Elf32_Half running_arch_code=EM_PARISC;
1507   #elif  (defined MIPS)
1508   static  Elf32_Half running_arch_code=EM_MIPS;
1509   #elif  (defined M68K)
1510   static  Elf32_Half running_arch_code=EM_68K;
1511   #else
1512     #error Method os::dll_load requires that one of following is defined:\
1513          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1514   #endif
1515 
1516   // Identify compatability class for VM's architecture and library's architecture
1517   // Obtain string descriptions for architectures
1518 
1519   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1520   int running_arch_index=-1;
1521 
1522   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1523     if (running_arch_code == arch_array[i].code) {
1524       running_arch_index    = i;
1525     }
1526     if (lib_arch.code == arch_array[i].code) {
1527       lib_arch.compat_class = arch_array[i].compat_class;
1528       lib_arch.name         = arch_array[i].name;
1529     }
1530   }
1531 
1532   assert(running_arch_index != -1,
1533          "Didn't find running architecture code (running_arch_code) in arch_array");
1534   if (running_arch_index == -1) {
1535     // Even though running architecture detection failed
1536     // we may still continue with reporting dlerror() message
1537     return NULL;
1538   }
1539 
1540   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1541     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1542     return NULL;
1543   }
1544 
1545 #ifndef S390
1546   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1547     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1548     return NULL;
1549   }
1550 #endif // !S390
1551 
1552   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1553     if (lib_arch.name!=NULL) {
1554       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1555                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1556                  lib_arch.name, arch_array[running_arch_index].name);
1557     } else {
1558       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1559                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1560                  lib_arch.code,
1561                  arch_array[running_arch_index].name);
1562     }
1563   }
1564 
1565   return NULL;
1566 #endif // STATIC_BUILD
1567 }
1568 #endif // !__APPLE__
1569 
1570 void* os::get_default_process_handle() {
1571 #ifdef __APPLE__
1572   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
1573   // to avoid finding unexpected symbols on second (or later)
1574   // loads of a library.
1575   return (void*)::dlopen(NULL, RTLD_FIRST);
1576 #else
1577   return (void*)::dlopen(NULL, RTLD_LAZY);
1578 #endif
1579 }
1580 
1581 // XXX: Do we need a lock around this as per Linux?
1582 void* os::dll_lookup(void* handle, const char* name) {
1583   return dlsym(handle, name);
1584 }
1585 
1586 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1587   outputStream * out = (outputStream *) param;
1588   out->print_cr(PTR_FORMAT " \t%s", base_address, name);
1589   return 0;
1590 }
1591 
1592 void os::print_dll_info(outputStream *st) {
1593   st->print_cr("Dynamic libraries:");
1594   if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1595     st->print_cr("Error: Cannot print dynamic libraries.");
1596   }
1597 }
1598 
1599 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1600 #ifdef RTLD_DI_LINKMAP
1601   Dl_info dli;
1602   void *handle;
1603   Link_map *map;
1604   Link_map *p;
1605 
1606   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
1607       dli.dli_fname == NULL) {
1608     return 1;
1609   }
1610   handle = dlopen(dli.dli_fname, RTLD_LAZY);
1611   if (handle == NULL) {
1612     return 1;
1613   }
1614   dlinfo(handle, RTLD_DI_LINKMAP, &map);
1615   if (map == NULL) {
1616     dlclose(handle);
1617     return 1;
1618   }
1619 
1620   while (map->l_prev != NULL)
1621     map = map->l_prev;
1622 
1623   while (map != NULL) {
1624     // Value for top_address is returned as 0 since we don't have any information about module size
1625     if (callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1626       dlclose(handle);
1627       return 1;
1628     }
1629     map = map->l_next;
1630   }
1631 
1632   dlclose(handle);
1633 #elif defined(__APPLE__)
1634   for (uint32_t i = 1; i < _dyld_image_count(); i++) {
1635     // Value for top_address is returned as 0 since we don't have any information about module size
1636     if (callback(_dyld_get_image_name(i), (address)_dyld_get_image_header(i), (address)0, param)) {
1637       return 1;
1638     }
1639   }
1640   return 0;
1641 #else
1642   return 1;
1643 #endif
1644 }
1645 
1646 void os::get_summary_os_info(char* buf, size_t buflen) {
1647   // These buffers are small because we want this to be brief
1648   // and not use a lot of stack while generating the hs_err file.
1649   char os[100];
1650   size_t size = sizeof(os);
1651   int mib_kern[] = { CTL_KERN, KERN_OSTYPE };
1652   if (sysctl(mib_kern, 2, os, &size, NULL, 0) < 0) {
1653 #ifdef __APPLE__
1654       strncpy(os, "Darwin", sizeof(os));
1655 #elif __OpenBSD__
1656       strncpy(os, "OpenBSD", sizeof(os));
1657 #else
1658       strncpy(os, "BSD", sizeof(os));
1659 #endif
1660   }
1661 
1662   char release[100];
1663   size = sizeof(release);
1664   int mib_release[] = { CTL_KERN, KERN_OSRELEASE };
1665   if (sysctl(mib_release, 2, release, &size, NULL, 0) < 0) {
1666       // if error, leave blank
1667       strncpy(release, "", sizeof(release));
1668   }
1669   snprintf(buf, buflen, "%s %s", os, release);
1670 }
1671 
1672 void os::print_os_info_brief(outputStream* st) {
1673   os::Posix::print_uname_info(st);
1674 }
1675 
1676 void os::print_os_info(outputStream* st) {
1677   st->print("OS:");
1678 
1679   os::Posix::print_uname_info(st);
1680 
1681   os::Posix::print_rlimit_info(st);
1682 
1683   os::Posix::print_load_average(st);
1684 }
1685 
1686 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1687   // Nothing to do for now.
1688 }
1689 
1690 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1691   unsigned int mhz;
1692   size_t size = sizeof(mhz);
1693   int mib[] = { CTL_HW, HW_CPU_FREQ };
1694   if (sysctl(mib, 2, &mhz, &size, NULL, 0) < 0) {
1695     mhz = 1;  // looks like an error but can be divided by
1696   } else {
1697     mhz /= 1000000;  // reported in millions
1698   }
1699 
1700   char model[100];
1701   size = sizeof(model);
1702   int mib_model[] = { CTL_HW, HW_MODEL };
1703   if (sysctl(mib_model, 2, model, &size, NULL, 0) < 0) {
1704     strncpy(model, cpu_arch, sizeof(model));
1705   }
1706 
1707   char machine[100];
1708   size = sizeof(machine);
1709   int mib_machine[] = { CTL_HW, HW_MACHINE };
1710   if (sysctl(mib_machine, 2, machine, &size, NULL, 0) < 0) {
1711       strncpy(machine, "", sizeof(machine));
1712   }
1713 
1714   snprintf(buf, buflen, "%s %s %d MHz", model, machine, mhz);
1715 }
1716 
1717 void os::print_memory_info(outputStream* st) {
1718 
1719   st->print("Memory:");
1720   st->print(" %dk page", os::vm_page_size()>>10);
1721 
1722   st->print(", physical " UINT64_FORMAT "k",
1723             os::physical_memory() >> 10);
1724   st->print("(" UINT64_FORMAT "k free)",
1725             os::available_memory() >> 10);
1726   st->cr();
1727 }
1728 
1729 static void print_signal_handler(outputStream* st, int sig,
1730                                  char* buf, size_t buflen);
1731 
1732 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1733   st->print_cr("Signal Handlers:");
1734   print_signal_handler(st, SIGSEGV, buf, buflen);
1735   print_signal_handler(st, SIGBUS , buf, buflen);
1736   print_signal_handler(st, SIGFPE , buf, buflen);
1737   print_signal_handler(st, SIGPIPE, buf, buflen);
1738   print_signal_handler(st, SIGXFSZ, buf, buflen);
1739   print_signal_handler(st, SIGILL , buf, buflen);
1740   print_signal_handler(st, SR_signum, buf, buflen);
1741   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1742   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1743   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1744   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1745 }
1746 
1747 static char saved_jvm_path[MAXPATHLEN] = {0};
1748 
1749 // Find the full path to the current module, libjvm
1750 void os::jvm_path(char *buf, jint buflen) {
1751   // Error checking.
1752   if (buflen < MAXPATHLEN) {
1753     assert(false, "must use a large-enough buffer");
1754     buf[0] = '\0';
1755     return;
1756   }
1757   // Lazy resolve the path to current module.
1758   if (saved_jvm_path[0] != 0) {
1759     strcpy(buf, saved_jvm_path);
1760     return;
1761   }
1762 
1763   char dli_fname[MAXPATHLEN];
1764   bool ret = dll_address_to_library_name(
1765                                          CAST_FROM_FN_PTR(address, os::jvm_path),
1766                                          dli_fname, sizeof(dli_fname), NULL);
1767   assert(ret, "cannot locate libjvm");
1768   char *rp = NULL;
1769   if (ret && dli_fname[0] != '\0') {
1770     rp = realpath(dli_fname, buf);
1771   }
1772   if (rp == NULL) {
1773     return;
1774   }
1775 
1776   if (Arguments::sun_java_launcher_is_altjvm()) {
1777     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
1778     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
1779     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
1780     // appears at the right place in the string, then assume we are
1781     // installed in a JDK and we're done. Otherwise, check for a
1782     // JAVA_HOME environment variable and construct a path to the JVM
1783     // being overridden.
1784 
1785     const char *p = buf + strlen(buf) - 1;
1786     for (int count = 0; p > buf && count < 5; ++count) {
1787       for (--p; p > buf && *p != '/'; --p)
1788         /* empty */ ;
1789     }
1790 
1791     if (strncmp(p, "/jre/lib/", 9) != 0) {
1792       // Look for JAVA_HOME in the environment.
1793       char* java_home_var = ::getenv("JAVA_HOME");
1794       if (java_home_var != NULL && java_home_var[0] != 0) {
1795         char* jrelib_p;
1796         int len;
1797 
1798         // Check the current module name "libjvm"
1799         p = strrchr(buf, '/');
1800         assert(strstr(p, "/libjvm") == p, "invalid library name");
1801 
1802         rp = realpath(java_home_var, buf);
1803         if (rp == NULL) {
1804           return;
1805         }
1806 
1807         // determine if this is a legacy image or modules image
1808         // modules image doesn't have "jre" subdirectory
1809         len = strlen(buf);
1810         assert(len < buflen, "Ran out of buffer space");
1811         jrelib_p = buf + len;
1812 
1813         // Add the appropriate library subdir
1814         snprintf(jrelib_p, buflen-len, "/jre/lib");
1815         if (0 != access(buf, F_OK)) {
1816           snprintf(jrelib_p, buflen-len, "/lib");
1817         }
1818 
1819         // Add the appropriate client or server subdir
1820         len = strlen(buf);
1821         jrelib_p = buf + len;
1822         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1823         if (0 != access(buf, F_OK)) {
1824           snprintf(jrelib_p, buflen-len, "%s", "");
1825         }
1826 
1827         // If the path exists within JAVA_HOME, add the JVM library name
1828         // to complete the path to JVM being overridden.  Otherwise fallback
1829         // to the path to the current library.
1830         if (0 == access(buf, F_OK)) {
1831           // Use current module name "libjvm"
1832           len = strlen(buf);
1833           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1834         } else {
1835           // Fall back to path of current library
1836           rp = realpath(dli_fname, buf);
1837           if (rp == NULL) {
1838             return;
1839           }
1840         }
1841       }
1842     }
1843   }
1844 
1845   strncpy(saved_jvm_path, buf, MAXPATHLEN);
1846   saved_jvm_path[MAXPATHLEN - 1] = '\0';
1847 }
1848 
1849 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1850   // no prefix required, not even "_"
1851 }
1852 
1853 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1854   // no suffix required
1855 }
1856 
1857 ////////////////////////////////////////////////////////////////////////////////
1858 // sun.misc.Signal support
1859 
1860 static volatile jint sigint_count = 0;
1861 
1862 static void UserHandler(int sig, void *siginfo, void *context) {
1863   // 4511530 - sem_post is serialized and handled by the manager thread. When
1864   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
1865   // don't want to flood the manager thread with sem_post requests.
1866   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) {
1867     return;
1868   }
1869 
1870   // Ctrl-C is pressed during error reporting, likely because the error
1871   // handler fails to abort. Let VM die immediately.
1872   if (sig == SIGINT && is_error_reported()) {
1873     os::die();
1874   }
1875 
1876   os::signal_notify(sig);
1877 }
1878 
1879 void* os::user_handler() {
1880   return CAST_FROM_FN_PTR(void*, UserHandler);
1881 }
1882 
1883 extern "C" {
1884   typedef void (*sa_handler_t)(int);
1885   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1886 }
1887 
1888 void* os::signal(int signal_number, void* handler) {
1889   struct sigaction sigAct, oldSigAct;
1890 
1891   sigfillset(&(sigAct.sa_mask));
1892   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
1893   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1894 
1895   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1896     // -1 means registration failed
1897     return (void *)-1;
1898   }
1899 
1900   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1901 }
1902 
1903 void os::signal_raise(int signal_number) {
1904   ::raise(signal_number);
1905 }
1906 
1907 // The following code is moved from os.cpp for making this
1908 // code platform specific, which it is by its very nature.
1909 
1910 // Will be modified when max signal is changed to be dynamic
1911 int os::sigexitnum_pd() {
1912   return NSIG;
1913 }
1914 
1915 // a counter for each possible signal value
1916 static volatile jint pending_signals[NSIG+1] = { 0 };
1917 
1918 // Bsd(POSIX) specific hand shaking semaphore.
1919 #ifdef __APPLE__
1920 typedef semaphore_t os_semaphore_t;
1921 
1922   #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
1923   #define SEM_WAIT(sem)           semaphore_wait(sem)
1924   #define SEM_POST(sem)           semaphore_signal(sem)
1925   #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
1926 #else
1927 typedef sem_t os_semaphore_t;
1928 
1929   #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
1930   #define SEM_WAIT(sem)           sem_wait(&sem)
1931   #define SEM_POST(sem)           sem_post(&sem)
1932   #define SEM_DESTROY(sem)        sem_destroy(&sem)
1933 #endif
1934 
1935 #ifdef __APPLE__
1936 // OS X doesn't support unamed POSIX semaphores, so the implementation in os_posix.cpp can't be used.
1937 
1938 static const char* sem_init_strerror(kern_return_t value) {
1939   switch (value) {
1940     case KERN_INVALID_ARGUMENT:  return "Invalid argument";
1941     case KERN_RESOURCE_SHORTAGE: return "Resource shortage";
1942     default:                     return "Unknown";
1943   }
1944 }
1945 
1946 OSXSemaphore::OSXSemaphore(uint value) {
1947   kern_return_t ret = SEM_INIT(_semaphore, value);
1948 
1949   guarantee(ret == KERN_SUCCESS, "Failed to create semaphore: %s", sem_init_strerror(ret));
1950 }
1951 
1952 OSXSemaphore::~OSXSemaphore() {
1953   SEM_DESTROY(_semaphore);
1954 }
1955 
1956 void OSXSemaphore::signal(uint count) {
1957   for (uint i = 0; i < count; i++) {
1958     kern_return_t ret = SEM_POST(_semaphore);
1959 
1960     assert(ret == KERN_SUCCESS, "Failed to signal semaphore");
1961   }
1962 }
1963 
1964 void OSXSemaphore::wait() {
1965   kern_return_t ret;
1966   while ((ret = SEM_WAIT(_semaphore)) == KERN_ABORTED) {
1967     // Semaphore was interrupted. Retry.
1968   }
1969   assert(ret == KERN_SUCCESS, "Failed to wait on semaphore");
1970 }
1971 
1972 jlong OSXSemaphore::currenttime() {
1973   struct timeval tv;
1974   gettimeofday(&tv, NULL);
1975   return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
1976 }
1977 
1978 bool OSXSemaphore::trywait() {
1979   return timedwait(0, 0);
1980 }
1981 
1982 bool OSXSemaphore::timedwait(unsigned int sec, int nsec) {
1983   kern_return_t kr = KERN_ABORTED;
1984   mach_timespec_t waitspec;
1985   waitspec.tv_sec = sec;
1986   waitspec.tv_nsec = nsec;
1987 
1988   jlong starttime = currenttime();
1989 
1990   kr = semaphore_timedwait(_semaphore, waitspec);
1991   while (kr == KERN_ABORTED) {
1992     jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
1993 
1994     jlong current = currenttime();
1995     jlong passedtime = current - starttime;
1996 
1997     if (passedtime >= totalwait) {
1998       waitspec.tv_sec = 0;
1999       waitspec.tv_nsec = 0;
2000     } else {
2001       jlong waittime = totalwait - (current - starttime);
2002       waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
2003       waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
2004     }
2005 
2006     kr = semaphore_timedwait(_semaphore, waitspec);
2007   }
2008 
2009   return kr == KERN_SUCCESS;
2010 }
2011 
2012 #else
2013 // Use POSIX implementation of semaphores.
2014 
2015 struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
2016   struct timespec ts;
2017   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2018 
2019   return ts;
2020 }
2021 
2022 #endif // __APPLE__
2023 
2024 static os_semaphore_t sig_sem;
2025 
2026 #ifdef __APPLE__
2027 static OSXSemaphore sr_semaphore;
2028 #else
2029 static PosixSemaphore sr_semaphore;
2030 #endif
2031 
2032 void os::signal_init_pd() {
2033   // Initialize signal structures
2034   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2035 
2036   // Initialize signal semaphore
2037   ::SEM_INIT(sig_sem, 0);
2038 }
2039 
2040 void os::signal_notify(int sig) {
2041   Atomic::inc(&pending_signals[sig]);
2042   ::SEM_POST(sig_sem);
2043 }
2044 
2045 static int check_pending_signals(bool wait) {
2046   Atomic::store(0, &sigint_count);
2047   for (;;) {
2048     for (int i = 0; i < NSIG + 1; i++) {
2049       jint n = pending_signals[i];
2050       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2051         return i;
2052       }
2053     }
2054     if (!wait) {
2055       return -1;
2056     }
2057     JavaThread *thread = JavaThread::current();
2058     ThreadBlockInVM tbivm(thread);
2059 
2060     bool threadIsSuspended;
2061     do {
2062       thread->set_suspend_equivalent();
2063       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2064       ::SEM_WAIT(sig_sem);
2065 
2066       // were we externally suspended while we were waiting?
2067       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2068       if (threadIsSuspended) {
2069         // The semaphore has been incremented, but while we were waiting
2070         // another thread suspended us. We don't want to continue running
2071         // while suspended because that would surprise the thread that
2072         // suspended us.
2073         ::SEM_POST(sig_sem);
2074 
2075         thread->java_suspend_self();
2076       }
2077     } while (threadIsSuspended);
2078   }
2079 }
2080 
2081 int os::signal_lookup() {
2082   return check_pending_signals(false);
2083 }
2084 
2085 int os::signal_wait() {
2086   return check_pending_signals(true);
2087 }
2088 
2089 ////////////////////////////////////////////////////////////////////////////////
2090 // Virtual Memory
2091 
2092 int os::vm_page_size() {
2093   // Seems redundant as all get out
2094   assert(os::Bsd::page_size() != -1, "must call os::init");
2095   return os::Bsd::page_size();
2096 }
2097 
2098 // Solaris allocates memory by pages.
2099 int os::vm_allocation_granularity() {
2100   assert(os::Bsd::page_size() != -1, "must call os::init");
2101   return os::Bsd::page_size();
2102 }
2103 
2104 // Rationale behind this function:
2105 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2106 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2107 //  samples for JITted code. Here we create private executable mapping over the code cache
2108 //  and then we can use standard (well, almost, as mapping can change) way to provide
2109 //  info for the reporting script by storing timestamp and location of symbol
2110 void bsd_wrap_code(char* base, size_t size) {
2111   static volatile jint cnt = 0;
2112 
2113   if (!UseOprofile) {
2114     return;
2115   }
2116 
2117   char buf[PATH_MAX + 1];
2118   int num = Atomic::add(1, &cnt);
2119 
2120   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
2121            os::get_temp_directory(), os::current_process_id(), num);
2122   unlink(buf);
2123 
2124   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2125 
2126   if (fd != -1) {
2127     off_t rv = ::lseek(fd, size-2, SEEK_SET);
2128     if (rv != (off_t)-1) {
2129       if (::write(fd, "", 1) == 1) {
2130         mmap(base, size,
2131              PROT_READ|PROT_WRITE|PROT_EXEC,
2132              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2133       }
2134     }
2135     ::close(fd);
2136     unlink(buf);
2137   }
2138 }
2139 
2140 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2141                                     int err) {
2142   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2143           ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
2144           os::errno_name(err), err);
2145 }
2146 
2147 // NOTE: Bsd kernel does not really reserve the pages for us.
2148 //       All it does is to check if there are enough free pages
2149 //       left at the time of mmap(). This could be a potential
2150 //       problem.
2151 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2152   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2153 #ifdef __OpenBSD__
2154   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2155   if (::mprotect(addr, size, prot) == 0) {
2156     return true;
2157   }
2158 #else
2159   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2160                                      MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2161   if (res != (uintptr_t) MAP_FAILED) {
2162     return true;
2163   }
2164 #endif
2165 
2166   // Warn about any commit errors we see in non-product builds just
2167   // in case mmap() doesn't work as described on the man page.
2168   NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
2169 
2170   return false;
2171 }
2172 
2173 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2174                           bool exec) {
2175   // alignment_hint is ignored on this OS
2176   return pd_commit_memory(addr, size, exec);
2177 }
2178 
2179 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2180                                   const char* mesg) {
2181   assert(mesg != NULL, "mesg must be specified");
2182   if (!pd_commit_memory(addr, size, exec)) {
2183     // add extra info in product mode for vm_exit_out_of_memory():
2184     PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
2185     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2186   }
2187 }
2188 
2189 void os::pd_commit_memory_or_exit(char* addr, size_t size,
2190                                   size_t alignment_hint, bool exec,
2191                                   const char* mesg) {
2192   // alignment_hint is ignored on this OS
2193   pd_commit_memory_or_exit(addr, size, exec, mesg);
2194 }
2195 
2196 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2197 }
2198 
2199 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2200   ::madvise(addr, bytes, MADV_DONTNEED);
2201 }
2202 
2203 void os::numa_make_global(char *addr, size_t bytes) {
2204 }
2205 
2206 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2207 }
2208 
2209 bool os::numa_topology_changed()   { return false; }
2210 
2211 size_t os::numa_get_groups_num() {
2212   return 1;
2213 }
2214 
2215 int os::numa_get_group_id() {
2216   return 0;
2217 }
2218 
2219 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2220   if (size > 0) {
2221     ids[0] = 0;
2222     return 1;
2223   }
2224   return 0;
2225 }
2226 
2227 bool os::get_page_info(char *start, page_info* info) {
2228   return false;
2229 }
2230 
2231 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2232   return end;
2233 }
2234 
2235 
2236 bool os::pd_uncommit_memory(char* addr, size_t size) {
2237 #ifdef __OpenBSD__
2238   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2239   return ::mprotect(addr, size, PROT_NONE) == 0;
2240 #else
2241   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2242                                      MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2243   return res  != (uintptr_t) MAP_FAILED;
2244 #endif
2245 }
2246 
2247 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2248   return os::commit_memory(addr, size, !ExecMem);
2249 }
2250 
2251 // If this is a growable mapping, remove the guard pages entirely by
2252 // munmap()ping them.  If not, just call uncommit_memory().
2253 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2254   return os::uncommit_memory(addr, size);
2255 }
2256 
2257 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2258 // at 'requested_addr'. If there are existing memory mappings at the same
2259 // location, however, they will be overwritten. If 'fixed' is false,
2260 // 'requested_addr' is only treated as a hint, the return value may or
2261 // may not start from the requested address. Unlike Bsd mmap(), this
2262 // function returns NULL to indicate failure.
2263 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2264   char * addr;
2265   int flags;
2266 
2267   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2268   if (fixed) {
2269     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2270     flags |= MAP_FIXED;
2271   }
2272 
2273   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
2274   // touch an uncommitted page. Otherwise, the read/write might
2275   // succeed if we have enough swap space to back the physical page.
2276   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
2277                        flags, -1, 0);
2278 
2279   return addr == MAP_FAILED ? NULL : addr;
2280 }
2281 
2282 static int anon_munmap(char * addr, size_t size) {
2283   return ::munmap(addr, size) == 0;
2284 }
2285 
2286 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2287                             size_t alignment_hint) {
2288   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2289 }
2290 
2291 bool os::pd_release_memory(char* addr, size_t size) {
2292   return anon_munmap(addr, size);
2293 }
2294 
2295 static bool bsd_mprotect(char* addr, size_t size, int prot) {
2296   // Bsd wants the mprotect address argument to be page aligned.
2297   char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size());
2298 
2299   // According to SUSv3, mprotect() should only be used with mappings
2300   // established by mmap(), and mmap() always maps whole pages. Unaligned
2301   // 'addr' likely indicates problem in the VM (e.g. trying to change
2302   // protection of malloc'ed or statically allocated memory). Check the
2303   // caller if you hit this assert.
2304   assert(addr == bottom, "sanity check");
2305 
2306   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2307   return ::mprotect(bottom, size, prot) == 0;
2308 }
2309 
2310 // Set protections specified
2311 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2312                         bool is_committed) {
2313   unsigned int p = 0;
2314   switch (prot) {
2315   case MEM_PROT_NONE: p = PROT_NONE; break;
2316   case MEM_PROT_READ: p = PROT_READ; break;
2317   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2318   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2319   default:
2320     ShouldNotReachHere();
2321   }
2322   // is_committed is unused.
2323   return bsd_mprotect(addr, bytes, p);
2324 }
2325 
2326 bool os::guard_memory(char* addr, size_t size) {
2327   return bsd_mprotect(addr, size, PROT_NONE);
2328 }
2329 
2330 bool os::unguard_memory(char* addr, size_t size) {
2331   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2332 }
2333 
2334 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2335   return false;
2336 }
2337 
2338 // Large page support
2339 
2340 static size_t _large_page_size = 0;
2341 
2342 void os::large_page_init() {
2343 }
2344 
2345 
2346 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
2347   fatal("This code is not used or maintained.");
2348 
2349   // "exec" is passed in but not used.  Creating the shared image for
2350   // the code cache doesn't have an SHM_X executable permission to check.
2351   assert(UseLargePages && UseSHM, "only for SHM large pages");
2352 
2353   key_t key = IPC_PRIVATE;
2354   char *addr;
2355 
2356   bool warn_on_failure = UseLargePages &&
2357                          (!FLAG_IS_DEFAULT(UseLargePages) ||
2358                           !FLAG_IS_DEFAULT(LargePageSizeInBytes));
2359 
2360   // Create a large shared memory region to attach to based on size.
2361   // Currently, size is the total size of the heap
2362   int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W);
2363   if (shmid == -1) {
2364     // Possible reasons for shmget failure:
2365     // 1. shmmax is too small for Java heap.
2366     //    > check shmmax value: cat /proc/sys/kernel/shmmax
2367     //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
2368     // 2. not enough large page memory.
2369     //    > check available large pages: cat /proc/meminfo
2370     //    > increase amount of large pages:
2371     //          echo new_value > /proc/sys/vm/nr_hugepages
2372     //      Note 1: different Bsd may use different name for this property,
2373     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
2374     //      Note 2: it's possible there's enough physical memory available but
2375     //            they are so fragmented after a long run that they can't
2376     //            coalesce into large pages. Try to reserve large pages when
2377     //            the system is still "fresh".
2378     if (warn_on_failure) {
2379       warning("Failed to reserve shared memory (errno = %d).", errno);
2380     }
2381     return NULL;
2382   }
2383 
2384   // attach to the region
2385   addr = (char*)shmat(shmid, req_addr, 0);
2386   int err = errno;
2387 
2388   // Remove shmid. If shmat() is successful, the actual shared memory segment
2389   // will be deleted when it's detached by shmdt() or when the process
2390   // terminates. If shmat() is not successful this will remove the shared
2391   // segment immediately.
2392   shmctl(shmid, IPC_RMID, NULL);
2393 
2394   if ((intptr_t)addr == -1) {
2395     if (warn_on_failure) {
2396       warning("Failed to attach shared memory (errno = %d).", err);
2397     }
2398     return NULL;
2399   }
2400 
2401   // The memory is committed
2402   MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);
2403 
2404   return addr;
2405 }
2406 
2407 bool os::release_memory_special(char* base, size_t bytes) {
2408   if (MemTracker::tracking_level() > NMT_minimal) {
2409     Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
2410     // detaching the SHM segment will also delete it, see reserve_memory_special()
2411     int rslt = shmdt(base);
2412     if (rslt == 0) {
2413       tkr.record((address)base, bytes);
2414       return true;
2415     } else {
2416       return false;
2417     }
2418   } else {
2419     return shmdt(base) == 0;
2420   }
2421 }
2422 
2423 size_t os::large_page_size() {
2424   return _large_page_size;
2425 }
2426 
2427 // HugeTLBFS allows application to commit large page memory on demand;
2428 // with SysV SHM the entire memory region must be allocated as shared
2429 // memory.
2430 bool os::can_commit_large_page_memory() {
2431   return UseHugeTLBFS;
2432 }
2433 
2434 bool os::can_execute_large_page_memory() {
2435   return UseHugeTLBFS;
2436 }
2437 
2438 // Reserve memory at an arbitrary address, only if that area is
2439 // available (and not reserved for something else).
2440 
2441 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2442   const int max_tries = 10;
2443   char* base[max_tries];
2444   size_t size[max_tries];
2445   const size_t gap = 0x000000;
2446 
2447   // Assert only that the size is a multiple of the page size, since
2448   // that's all that mmap requires, and since that's all we really know
2449   // about at this low abstraction level.  If we need higher alignment,
2450   // we can either pass an alignment to this method or verify alignment
2451   // in one of the methods further up the call chain.  See bug 5044738.
2452   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2453 
2454   // Repeatedly allocate blocks until the block is allocated at the
2455   // right spot.
2456 
2457   // Bsd mmap allows caller to pass an address as hint; give it a try first,
2458   // if kernel honors the hint then we can return immediately.
2459   char * addr = anon_mmap(requested_addr, bytes, false);
2460   if (addr == requested_addr) {
2461     return requested_addr;
2462   }
2463 
2464   if (addr != NULL) {
2465     // mmap() is successful but it fails to reserve at the requested address
2466     anon_munmap(addr, bytes);
2467   }
2468 
2469   int i;
2470   for (i = 0; i < max_tries; ++i) {
2471     base[i] = reserve_memory(bytes);
2472 
2473     if (base[i] != NULL) {
2474       // Is this the block we wanted?
2475       if (base[i] == requested_addr) {
2476         size[i] = bytes;
2477         break;
2478       }
2479 
2480       // Does this overlap the block we wanted? Give back the overlapped
2481       // parts and try again.
2482 
2483       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2484       if (top_overlap >= 0 && top_overlap < bytes) {
2485         unmap_memory(base[i], top_overlap);
2486         base[i] += top_overlap;
2487         size[i] = bytes - top_overlap;
2488       } else {
2489         size_t bottom_overlap = base[i] + bytes - requested_addr;
2490         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2491           unmap_memory(requested_addr, bottom_overlap);
2492           size[i] = bytes - bottom_overlap;
2493         } else {
2494           size[i] = bytes;
2495         }
2496       }
2497     }
2498   }
2499 
2500   // Give back the unused reserved pieces.
2501 
2502   for (int j = 0; j < i; ++j) {
2503     if (base[j] != NULL) {
2504       unmap_memory(base[j], size[j]);
2505     }
2506   }
2507 
2508   if (i < max_tries) {
2509     return requested_addr;
2510   } else {
2511     return NULL;
2512   }
2513 }
2514 
2515 size_t os::read(int fd, void *buf, unsigned int nBytes) {
2516   RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
2517 }
2518 
2519 size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {
2520   RESTARTABLE_RETURN_INT(::pread(fd, buf, nBytes, offset));
2521 }
2522 
2523 void os::naked_short_sleep(jlong ms) {
2524   struct timespec req;
2525 
2526   assert(ms < 1000, "Un-interruptable sleep, short time use only");
2527   req.tv_sec = 0;
2528   if (ms > 0) {
2529     req.tv_nsec = (ms % 1000) * 1000000;
2530   } else {
2531     req.tv_nsec = 1;
2532   }
2533 
2534   nanosleep(&req, NULL);
2535 
2536   return;
2537 }
2538 
2539 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2540 void os::infinite_sleep() {
2541   while (true) {    // sleep forever ...
2542     ::sleep(100);   // ... 100 seconds at a time
2543   }
2544 }
2545 
2546 // Used to convert frequent JVM_Yield() to nops
2547 bool os::dont_yield() {
2548   return DontYieldALot;
2549 }
2550 
2551 void os::naked_yield() {
2552   sched_yield();
2553 }
2554 
2555 ////////////////////////////////////////////////////////////////////////////////
2556 // thread priority support
2557 
2558 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2559 // only supports dynamic priority, static priority must be zero. For real-time
2560 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2561 // However, for large multi-threaded applications, SCHED_RR is not only slower
2562 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2563 // of 5 runs - Sep 2005).
2564 //
2565 // The following code actually changes the niceness of kernel-thread/LWP. It
2566 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2567 // not the entire user process, and user level threads are 1:1 mapped to kernel
2568 // threads. It has always been the case, but could change in the future. For
2569 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2570 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
2571 
2572 #if !defined(__APPLE__)
2573 int os::java_to_os_priority[CriticalPriority + 1] = {
2574   19,              // 0 Entry should never be used
2575 
2576    0,              // 1 MinPriority
2577    3,              // 2
2578    6,              // 3
2579 
2580   10,              // 4
2581   15,              // 5 NormPriority
2582   18,              // 6
2583 
2584   21,              // 7
2585   25,              // 8
2586   28,              // 9 NearMaxPriority
2587 
2588   31,              // 10 MaxPriority
2589 
2590   31               // 11 CriticalPriority
2591 };
2592 #else
2593 // Using Mach high-level priority assignments
2594 int os::java_to_os_priority[CriticalPriority + 1] = {
2595    0,              // 0 Entry should never be used (MINPRI_USER)
2596 
2597   27,              // 1 MinPriority
2598   28,              // 2
2599   29,              // 3
2600 
2601   30,              // 4
2602   31,              // 5 NormPriority (BASEPRI_DEFAULT)
2603   32,              // 6
2604 
2605   33,              // 7
2606   34,              // 8
2607   35,              // 9 NearMaxPriority
2608 
2609   36,              // 10 MaxPriority
2610 
2611   36               // 11 CriticalPriority
2612 };
2613 #endif
2614 
2615 static int prio_init() {
2616   if (ThreadPriorityPolicy == 1) {
2617     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
2618     // if effective uid is not root. Perhaps, a more elegant way of doing
2619     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
2620     if (geteuid() != 0) {
2621       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
2622         warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd");
2623       }
2624       ThreadPriorityPolicy = 0;
2625     }
2626   }
2627   if (UseCriticalJavaThreadPriority) {
2628     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2629   }
2630   return 0;
2631 }
2632 
2633 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2634   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
2635 
2636 #ifdef __OpenBSD__
2637   // OpenBSD pthread_setprio starves low priority threads
2638   return OS_OK;
2639 #elif defined(__FreeBSD__)
2640   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2641 #elif defined(__APPLE__) || defined(__NetBSD__)
2642   struct sched_param sp;
2643   int policy;
2644   pthread_t self = pthread_self();
2645 
2646   if (pthread_getschedparam(self, &policy, &sp) != 0) {
2647     return OS_ERR;
2648   }
2649 
2650   sp.sched_priority = newpri;
2651   if (pthread_setschedparam(self, policy, &sp) != 0) {
2652     return OS_ERR;
2653   }
2654 
2655   return OS_OK;
2656 #else
2657   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2658   return (ret == 0) ? OS_OK : OS_ERR;
2659 #endif
2660 }
2661 
2662 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2663   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
2664     *priority_ptr = java_to_os_priority[NormPriority];
2665     return OS_OK;
2666   }
2667 
2668   errno = 0;
2669 #if defined(__OpenBSD__) || defined(__FreeBSD__)
2670   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2671 #elif defined(__APPLE__) || defined(__NetBSD__)
2672   int policy;
2673   struct sched_param sp;
2674 
2675   pthread_getschedparam(pthread_self(), &policy, &sp);
2676   *priority_ptr = sp.sched_priority;
2677 #else
2678   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2679 #endif
2680   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2681 }
2682 
2683 // Hint to the underlying OS that a task switch would not be good.
2684 // Void return because it's a hint and can fail.
2685 void os::hint_no_preempt() {}
2686 
2687 ////////////////////////////////////////////////////////////////////////////////
2688 // suspend/resume support
2689 
2690 //  the low-level signal-based suspend/resume support is a remnant from the
2691 //  old VM-suspension that used to be for java-suspension, safepoints etc,
2692 //  within hotspot. Now there is a single use-case for this:
2693 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
2694 //      that runs in the watcher thread.
2695 //  The remaining code is greatly simplified from the more general suspension
2696 //  code that used to be used.
2697 //
2698 //  The protocol is quite simple:
2699 //  - suspend:
2700 //      - sends a signal to the target thread
2701 //      - polls the suspend state of the osthread using a yield loop
2702 //      - target thread signal handler (SR_handler) sets suspend state
2703 //        and blocks in sigsuspend until continued
2704 //  - resume:
2705 //      - sets target osthread state to continue
2706 //      - sends signal to end the sigsuspend loop in the SR_handler
2707 //
2708 //  Note that the SR_lock plays no role in this suspend/resume protocol.
2709 
2710 static void resume_clear_context(OSThread *osthread) {
2711   osthread->set_ucontext(NULL);
2712   osthread->set_siginfo(NULL);
2713 }
2714 
2715 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2716   osthread->set_ucontext(context);
2717   osthread->set_siginfo(siginfo);
2718 }
2719 
2720 // Handler function invoked when a thread's execution is suspended or
2721 // resumed. We have to be careful that only async-safe functions are
2722 // called here (Note: most pthread functions are not async safe and
2723 // should be avoided.)
2724 //
2725 // Note: sigwait() is a more natural fit than sigsuspend() from an
2726 // interface point of view, but sigwait() prevents the signal hander
2727 // from being run. libpthread would get very confused by not having
2728 // its signal handlers run and prevents sigwait()'s use with the
2729 // mutex granting granting signal.
2730 //
2731 // Currently only ever called on the VMThread or JavaThread
2732 //
2733 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2734   // Save and restore errno to avoid confusing native code with EINTR
2735   // after sigsuspend.
2736   int old_errno = errno;
2737 
2738   Thread* thread = Thread::current();
2739   OSThread* osthread = thread->osthread();
2740   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
2741 
2742   os::SuspendResume::State current = osthread->sr.state();
2743   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
2744     suspend_save_context(osthread, siginfo, context);
2745 
2746     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
2747     os::SuspendResume::State state = osthread->sr.suspended();
2748     if (state == os::SuspendResume::SR_SUSPENDED) {
2749       sigset_t suspend_set;  // signals for sigsuspend()
2750 
2751       // get current set of blocked signals and unblock resume signal
2752       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2753       sigdelset(&suspend_set, SR_signum);
2754 
2755       sr_semaphore.signal();
2756       // wait here until we are resumed
2757       while (1) {
2758         sigsuspend(&suspend_set);
2759 
2760         os::SuspendResume::State result = osthread->sr.running();
2761         if (result == os::SuspendResume::SR_RUNNING) {
2762           sr_semaphore.signal();
2763           break;
2764         } else if (result != os::SuspendResume::SR_SUSPENDED) {
2765           ShouldNotReachHere();
2766         }
2767       }
2768 
2769     } else if (state == os::SuspendResume::SR_RUNNING) {
2770       // request was cancelled, continue
2771     } else {
2772       ShouldNotReachHere();
2773     }
2774 
2775     resume_clear_context(osthread);
2776   } else if (current == os::SuspendResume::SR_RUNNING) {
2777     // request was cancelled, continue
2778   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
2779     // ignore
2780   } else {
2781     // ignore
2782   }
2783 
2784   errno = old_errno;
2785 }
2786 
2787 
2788 static int SR_initialize() {
2789   struct sigaction act;
2790   char *s;
2791   // Get signal number to use for suspend/resume
2792   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2793     int sig = ::strtol(s, 0, 10);
2794     if (sig > MAX2(SIGSEGV, SIGBUS) &&  // See 4355769.
2795         sig < NSIG) {                   // Must be legal signal and fit into sigflags[].
2796       SR_signum = sig;
2797     } else {
2798       warning("You set _JAVA_SR_SIGNUM=%d. It must be in range [%d, %d]. Using %d instead.",
2799               sig, MAX2(SIGSEGV, SIGBUS)+1, NSIG-1, SR_signum);
2800     }
2801   }
2802 
2803   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2804          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2805 
2806   sigemptyset(&SR_sigset);
2807   sigaddset(&SR_sigset, SR_signum);
2808 
2809   // Set up signal handler for suspend/resume
2810   act.sa_flags = SA_RESTART|SA_SIGINFO;
2811   act.sa_handler = (void (*)(int)) SR_handler;
2812 
2813   // SR_signum is blocked by default.
2814   // 4528190 - We also need to block pthread restart signal (32 on all
2815   // supported Bsd platforms). Note that BsdThreads need to block
2816   // this signal for all threads to work properly. So we don't have
2817   // to use hard-coded signal number when setting up the mask.
2818   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2819 
2820   if (sigaction(SR_signum, &act, 0) == -1) {
2821     return -1;
2822   }
2823 
2824   // Save signal flag
2825   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2826   return 0;
2827 }
2828 
2829 static int sr_notify(OSThread* osthread) {
2830   int status = pthread_kill(osthread->pthread_id(), SR_signum);
2831   assert_status(status == 0, status, "pthread_kill");
2832   return status;
2833 }
2834 
2835 // "Randomly" selected value for how long we want to spin
2836 // before bailing out on suspending a thread, also how often
2837 // we send a signal to a thread we want to resume
2838 static const int RANDOMLY_LARGE_INTEGER = 1000000;
2839 static const int RANDOMLY_LARGE_INTEGER2 = 100;
2840 
2841 // returns true on success and false on error - really an error is fatal
2842 // but this seems the normal response to library errors
2843 static bool do_suspend(OSThread* osthread) {
2844   assert(osthread->sr.is_running(), "thread should be running");
2845   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
2846 
2847   // mark as suspended and send signal
2848   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
2849     // failed to switch, state wasn't running?
2850     ShouldNotReachHere();
2851     return false;
2852   }
2853 
2854   if (sr_notify(osthread) != 0) {
2855     ShouldNotReachHere();
2856   }
2857 
2858   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
2859   while (true) {
2860     if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2861       break;
2862     } else {
2863       // timeout
2864       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
2865       if (cancelled == os::SuspendResume::SR_RUNNING) {
2866         return false;
2867       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
2868         // make sure that we consume the signal on the semaphore as well
2869         sr_semaphore.wait();
2870         break;
2871       } else {
2872         ShouldNotReachHere();
2873         return false;
2874       }
2875     }
2876   }
2877 
2878   guarantee(osthread->sr.is_suspended(), "Must be suspended");
2879   return true;
2880 }
2881 
2882 static void do_resume(OSThread* osthread) {
2883   assert(osthread->sr.is_suspended(), "thread should be suspended");
2884   assert(!sr_semaphore.trywait(), "invalid semaphore state");
2885 
2886   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
2887     // failed to switch to WAKEUP_REQUEST
2888     ShouldNotReachHere();
2889     return;
2890   }
2891 
2892   while (true) {
2893     if (sr_notify(osthread) == 0) {
2894       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
2895         if (osthread->sr.is_running()) {
2896           return;
2897         }
2898       }
2899     } else {
2900       ShouldNotReachHere();
2901     }
2902   }
2903 
2904   guarantee(osthread->sr.is_running(), "Must be running!");
2905 }
2906 
2907 ///////////////////////////////////////////////////////////////////////////////////
2908 // signal handling (except suspend/resume)
2909 
2910 // This routine may be used by user applications as a "hook" to catch signals.
2911 // The user-defined signal handler must pass unrecognized signals to this
2912 // routine, and if it returns true (non-zero), then the signal handler must
2913 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
2914 // routine will never retun false (zero), but instead will execute a VM panic
2915 // routine kill the process.
2916 //
2917 // If this routine returns false, it is OK to call it again.  This allows
2918 // the user-defined signal handler to perform checks either before or after
2919 // the VM performs its own checks.  Naturally, the user code would be making
2920 // a serious error if it tried to handle an exception (such as a null check
2921 // or breakpoint) that the VM was generating for its own correct operation.
2922 //
2923 // This routine may recognize any of the following kinds of signals:
2924 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
2925 // It should be consulted by handlers for any of those signals.
2926 //
2927 // The caller of this routine must pass in the three arguments supplied
2928 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
2929 // field of the structure passed to sigaction().  This routine assumes that
2930 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
2931 //
2932 // Note that the VM will print warnings if it detects conflicting signal
2933 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
2934 //
2935 extern "C" JNIEXPORT int JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
2936                                                void* ucontext,
2937                                                int abort_if_unrecognized);
2938 
2939 void signalHandler(int sig, siginfo_t* info, void* uc) {
2940   assert(info != NULL && uc != NULL, "it must be old kernel");
2941   int orig_errno = errno;  // Preserve errno value over signal handler.
2942   JVM_handle_bsd_signal(sig, info, uc, true);
2943   errno = orig_errno;
2944 }
2945 
2946 
2947 // This boolean allows users to forward their own non-matching signals
2948 // to JVM_handle_bsd_signal, harmlessly.
2949 bool os::Bsd::signal_handlers_are_installed = false;
2950 
2951 // For signal-chaining
2952 struct sigaction sigact[NSIG];
2953 uint32_t sigs = 0;
2954 #if (32 < NSIG-1)
2955 #error "Not all signals can be encoded in sigs. Adapt its type!"
2956 #endif
2957 bool os::Bsd::libjsig_is_loaded = false;
2958 typedef struct sigaction *(*get_signal_t)(int);
2959 get_signal_t os::Bsd::get_signal_action = NULL;
2960 
2961 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
2962   struct sigaction *actp = NULL;
2963 
2964   if (libjsig_is_loaded) {
2965     // Retrieve the old signal handler from libjsig
2966     actp = (*get_signal_action)(sig);
2967   }
2968   if (actp == NULL) {
2969     // Retrieve the preinstalled signal handler from jvm
2970     actp = get_preinstalled_handler(sig);
2971   }
2972 
2973   return actp;
2974 }
2975 
2976 static bool call_chained_handler(struct sigaction *actp, int sig,
2977                                  siginfo_t *siginfo, void *context) {
2978   // Call the old signal handler
2979   if (actp->sa_handler == SIG_DFL) {
2980     // It's more reasonable to let jvm treat it as an unexpected exception
2981     // instead of taking the default action.
2982     return false;
2983   } else if (actp->sa_handler != SIG_IGN) {
2984     if ((actp->sa_flags & SA_NODEFER) == 0) {
2985       // automaticlly block the signal
2986       sigaddset(&(actp->sa_mask), sig);
2987     }
2988 
2989     sa_handler_t hand;
2990     sa_sigaction_t sa;
2991     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
2992     // retrieve the chained handler
2993     if (siginfo_flag_set) {
2994       sa = actp->sa_sigaction;
2995     } else {
2996       hand = actp->sa_handler;
2997     }
2998 
2999     if ((actp->sa_flags & SA_RESETHAND) != 0) {
3000       actp->sa_handler = SIG_DFL;
3001     }
3002 
3003     // try to honor the signal mask
3004     sigset_t oset;
3005     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3006 
3007     // call into the chained handler
3008     if (siginfo_flag_set) {
3009       (*sa)(sig, siginfo, context);
3010     } else {
3011       (*hand)(sig);
3012     }
3013 
3014     // restore the signal mask
3015     pthread_sigmask(SIG_SETMASK, &oset, 0);
3016   }
3017   // Tell jvm's signal handler the signal is taken care of.
3018   return true;
3019 }
3020 
3021 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3022   bool chained = false;
3023   // signal-chaining
3024   if (UseSignalChaining) {
3025     struct sigaction *actp = get_chained_signal_action(sig);
3026     if (actp != NULL) {
3027       chained = call_chained_handler(actp, sig, siginfo, context);
3028     }
3029   }
3030   return chained;
3031 }
3032 
3033 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) {
3034   if ((((uint32_t)1 << (sig-1)) & sigs) != 0) {
3035     return &sigact[sig];
3036   }
3037   return NULL;
3038 }
3039 
3040 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
3041   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
3042   sigact[sig] = oldAct;
3043   sigs |= (uint32_t)1 << (sig-1);
3044 }
3045 
3046 // for diagnostic
3047 int sigflags[NSIG];
3048 
3049 int os::Bsd::get_our_sigflags(int sig) {
3050   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
3051   return sigflags[sig];
3052 }
3053 
3054 void os::Bsd::set_our_sigflags(int sig, int flags) {
3055   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
3056   if (sig > 0 && sig < NSIG) {
3057     sigflags[sig] = flags;
3058   }
3059 }
3060 
3061 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
3062   // Check for overwrite.
3063   struct sigaction oldAct;
3064   sigaction(sig, (struct sigaction*)NULL, &oldAct);
3065 
3066   void* oldhand = oldAct.sa_sigaction
3067                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
3068                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
3069   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3070       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3071       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
3072     if (AllowUserSignalHandlers || !set_installed) {
3073       // Do not overwrite; user takes responsibility to forward to us.
3074       return;
3075     } else if (UseSignalChaining) {
3076       // save the old handler in jvm
3077       save_preinstalled_handler(sig, oldAct);
3078       // libjsig also interposes the sigaction() call below and saves the
3079       // old sigaction on it own.
3080     } else {
3081       fatal("Encountered unexpected pre-existing sigaction handler "
3082             "%#lx for signal %d.", (long)oldhand, sig);
3083     }
3084   }
3085 
3086   struct sigaction sigAct;
3087   sigfillset(&(sigAct.sa_mask));
3088   sigAct.sa_handler = SIG_DFL;
3089   if (!set_installed) {
3090     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3091   } else {
3092     sigAct.sa_sigaction = signalHandler;
3093     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
3094   }
3095 #ifdef __APPLE__
3096   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
3097   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
3098   // if the signal handler declares it will handle it on alternate stack.
3099   // Notice we only declare we will handle it on alt stack, but we are not
3100   // actually going to use real alt stack - this is just a workaround.
3101   // Please see ux_exception.c, method catch_mach_exception_raise for details
3102   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
3103   if (sig == SIGSEGV) {
3104     sigAct.sa_flags |= SA_ONSTACK;
3105   }
3106 #endif
3107 
3108   // Save flags, which are set by ours
3109   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
3110   sigflags[sig] = sigAct.sa_flags;
3111 
3112   int ret = sigaction(sig, &sigAct, &oldAct);
3113   assert(ret == 0, "check");
3114 
3115   void* oldhand2  = oldAct.sa_sigaction
3116                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3117                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3118   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3119 }
3120 
3121 // install signal handlers for signals that HotSpot needs to
3122 // handle in order to support Java-level exception handling.
3123 
3124 void os::Bsd::install_signal_handlers() {
3125   if (!signal_handlers_are_installed) {
3126     signal_handlers_are_installed = true;
3127 
3128     // signal-chaining
3129     typedef void (*signal_setting_t)();
3130     signal_setting_t begin_signal_setting = NULL;
3131     signal_setting_t end_signal_setting = NULL;
3132     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3133                                           dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
3134     if (begin_signal_setting != NULL) {
3135       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3136                                           dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
3137       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
3138                                          dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
3139       libjsig_is_loaded = true;
3140       assert(UseSignalChaining, "should enable signal-chaining");
3141     }
3142     if (libjsig_is_loaded) {
3143       // Tell libjsig jvm is setting signal handlers
3144       (*begin_signal_setting)();
3145     }
3146 
3147     set_signal_handler(SIGSEGV, true);
3148     set_signal_handler(SIGPIPE, true);
3149     set_signal_handler(SIGBUS, true);
3150     set_signal_handler(SIGILL, true);
3151     set_signal_handler(SIGFPE, true);
3152     set_signal_handler(SIGXFSZ, true);
3153 
3154 #if defined(__APPLE__)
3155     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
3156     // signals caught and handled by the JVM. To work around this, we reset the mach task
3157     // signal handler that's placed on our process by CrashReporter. This disables
3158     // CrashReporter-based reporting.
3159     //
3160     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
3161     // on caught fatal signals.
3162     //
3163     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
3164     // handlers. By replacing the existing task exception handler, we disable gdb's mach
3165     // exception handling, while leaving the standard BSD signal handlers functional.
3166     kern_return_t kr;
3167     kr = task_set_exception_ports(mach_task_self(),
3168                                   EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
3169                                   MACH_PORT_NULL,
3170                                   EXCEPTION_STATE_IDENTITY,
3171                                   MACHINE_THREAD_STATE);
3172 
3173     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
3174 #endif
3175 
3176     if (libjsig_is_loaded) {
3177       // Tell libjsig jvm finishes setting signal handlers
3178       (*end_signal_setting)();
3179     }
3180 
3181     // We don't activate signal checker if libjsig is in place, we trust ourselves
3182     // and if UserSignalHandler is installed all bets are off
3183     if (CheckJNICalls) {
3184       if (libjsig_is_loaded) {
3185         if (PrintJNIResolving) {
3186           tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
3187         }
3188         check_signals = false;
3189       }
3190       if (AllowUserSignalHandlers) {
3191         if (PrintJNIResolving) {
3192           tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
3193         }
3194         check_signals = false;
3195       }
3196     }
3197   }
3198 }
3199 
3200 
3201 /////
3202 // glibc on Bsd platform uses non-documented flag
3203 // to indicate, that some special sort of signal
3204 // trampoline is used.
3205 // We will never set this flag, and we should
3206 // ignore this flag in our diagnostic
3207 #ifdef SIGNIFICANT_SIGNAL_MASK
3208   #undef SIGNIFICANT_SIGNAL_MASK
3209 #endif
3210 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
3211 
3212 static const char* get_signal_handler_name(address handler,
3213                                            char* buf, int buflen) {
3214   int offset;
3215   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
3216   if (found) {
3217     // skip directory names
3218     const char *p1, *p2;
3219     p1 = buf;
3220     size_t len = strlen(os::file_separator());
3221     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
3222     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
3223   } else {
3224     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
3225   }
3226   return buf;
3227 }
3228 
3229 static void print_signal_handler(outputStream* st, int sig,
3230                                  char* buf, size_t buflen) {
3231   struct sigaction sa;
3232 
3233   sigaction(sig, NULL, &sa);
3234 
3235   // See comment for SIGNIFICANT_SIGNAL_MASK define
3236   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3237 
3238   st->print("%s: ", os::exception_name(sig, buf, buflen));
3239 
3240   address handler = (sa.sa_flags & SA_SIGINFO)
3241     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
3242     : CAST_FROM_FN_PTR(address, sa.sa_handler);
3243 
3244   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
3245     st->print("SIG_DFL");
3246   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
3247     st->print("SIG_IGN");
3248   } else {
3249     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
3250   }
3251 
3252   st->print(", sa_mask[0]=");
3253   os::Posix::print_signal_set_short(st, &sa.sa_mask);
3254 
3255   address rh = VMError::get_resetted_sighandler(sig);
3256   // May be, handler was resetted by VMError?
3257   if (rh != NULL) {
3258     handler = rh;
3259     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
3260   }
3261 
3262   st->print(", sa_flags=");
3263   os::Posix::print_sa_flags(st, sa.sa_flags);
3264 
3265   // Check: is it our handler?
3266   if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
3267       handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
3268     // It is our signal handler
3269     // check for flags, reset system-used one!
3270     if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3271       st->print(
3272                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
3273                 os::Bsd::get_our_sigflags(sig));
3274     }
3275   }
3276   st->cr();
3277 }
3278 
3279 
3280 #define DO_SIGNAL_CHECK(sig)                      \
3281   do {                                            \
3282     if (!sigismember(&check_signal_done, sig)) {  \
3283       os::Bsd::check_signal_handler(sig);         \
3284     }                                             \
3285   } while (0)
3286 
3287 // This method is a periodic task to check for misbehaving JNI applications
3288 // under CheckJNI, we can add any periodic checks here
3289 
3290 void os::run_periodic_checks() {
3291 
3292   if (check_signals == false) return;
3293 
3294   // SEGV and BUS if overridden could potentially prevent
3295   // generation of hs*.log in the event of a crash, debugging
3296   // such a case can be very challenging, so we absolutely
3297   // check the following for a good measure:
3298   DO_SIGNAL_CHECK(SIGSEGV);
3299   DO_SIGNAL_CHECK(SIGILL);
3300   DO_SIGNAL_CHECK(SIGFPE);
3301   DO_SIGNAL_CHECK(SIGBUS);
3302   DO_SIGNAL_CHECK(SIGPIPE);
3303   DO_SIGNAL_CHECK(SIGXFSZ);
3304 
3305 
3306   // ReduceSignalUsage allows the user to override these handlers
3307   // see comments at the very top and jvm_solaris.h
3308   if (!ReduceSignalUsage) {
3309     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3310     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3311     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3312     DO_SIGNAL_CHECK(BREAK_SIGNAL);
3313   }
3314 
3315   DO_SIGNAL_CHECK(SR_signum);
3316 }
3317 
3318 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3319 
3320 static os_sigaction_t os_sigaction = NULL;
3321 
3322 void os::Bsd::check_signal_handler(int sig) {
3323   char buf[O_BUFLEN];
3324   address jvmHandler = NULL;
3325 
3326 
3327   struct sigaction act;
3328   if (os_sigaction == NULL) {
3329     // only trust the default sigaction, in case it has been interposed
3330     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3331     if (os_sigaction == NULL) return;
3332   }
3333 
3334   os_sigaction(sig, (struct sigaction*)NULL, &act);
3335 
3336 
3337   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3338 
3339   address thisHandler = (act.sa_flags & SA_SIGINFO)
3340     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3341     : CAST_FROM_FN_PTR(address, act.sa_handler);
3342 
3343 
3344   switch (sig) {
3345   case SIGSEGV:
3346   case SIGBUS:
3347   case SIGFPE:
3348   case SIGPIPE:
3349   case SIGILL:
3350   case SIGXFSZ:
3351     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3352     break;
3353 
3354   case SHUTDOWN1_SIGNAL:
3355   case SHUTDOWN2_SIGNAL:
3356   case SHUTDOWN3_SIGNAL:
3357   case BREAK_SIGNAL:
3358     jvmHandler = (address)user_handler();
3359     break;
3360 
3361   default:
3362     if (sig == SR_signum) {
3363       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3364     } else {
3365       return;
3366     }
3367     break;
3368   }
3369 
3370   if (thisHandler != jvmHandler) {
3371     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3372     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3373     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3374     // No need to check this sig any longer
3375     sigaddset(&check_signal_done, sig);
3376     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
3377     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
3378       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
3379                     exception_name(sig, buf, O_BUFLEN));
3380     }
3381   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3382     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3383     tty->print("expected:");
3384     os::Posix::print_sa_flags(tty, os::Bsd::get_our_sigflags(sig));
3385     tty->cr();
3386     tty->print("  found:");
3387     os::Posix::print_sa_flags(tty, act.sa_flags);
3388     tty->cr();
3389     // No need to check this sig any longer
3390     sigaddset(&check_signal_done, sig);
3391   }
3392 
3393   // Dump all the signal
3394   if (sigismember(&check_signal_done, sig)) {
3395     print_signal_handlers(tty, buf, O_BUFLEN);
3396   }
3397 }
3398 
3399 extern void report_error(char* file_name, int line_no, char* title,
3400                          char* format, ...);
3401 
3402 // this is called _before_ the most of global arguments have been parsed
3403 void os::init(void) {
3404   char dummy;   // used to get a guess on initial stack address
3405 //  first_hrtime = gethrtime();
3406 
3407   // With BsdThreads the JavaMain thread pid (primordial thread)
3408   // is different than the pid of the java launcher thread.
3409   // So, on Bsd, the launcher thread pid is passed to the VM
3410   // via the sun.java.launcher.pid property.
3411   // Use this property instead of getpid() if it was correctly passed.
3412   // See bug 6351349.
3413   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
3414 
3415   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
3416 
3417   clock_tics_per_sec = CLK_TCK;
3418 
3419   init_random(1234567);
3420 
3421   ThreadCritical::initialize();
3422 
3423   Bsd::set_page_size(getpagesize());
3424   if (Bsd::page_size() == -1) {
3425     fatal("os_bsd.cpp: os::init: sysconf failed (%s)", os::strerror(errno));
3426   }
3427   init_page_sizes((size_t) Bsd::page_size());
3428 
3429   Bsd::initialize_system_info();
3430 
3431   // main_thread points to the aboriginal thread
3432   Bsd::_main_thread = pthread_self();
3433 
3434   Bsd::clock_init();
3435   initial_time_count = javaTimeNanos();
3436 
3437 #ifdef __APPLE__
3438   // XXXDARWIN
3439   // Work around the unaligned VM callbacks in hotspot's
3440   // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
3441   // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
3442   // alignment when doing symbol lookup. To work around this, we force early
3443   // binding of all symbols now, thus binding when alignment is known-good.
3444   _dyld_bind_fully_image_containing_address((const void *) &os::init);
3445 #endif
3446 }
3447 
3448 // To install functions for atexit system call
3449 extern "C" {
3450   static void perfMemory_exit_helper() {
3451     perfMemory_exit();
3452   }
3453 }
3454 
3455 // this is called _after_ the global arguments have been parsed
3456 jint os::init_2(void) {
3457   // Allocate a single page and mark it as readable for safepoint polling
3458   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3459   guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page");
3460 
3461   os::set_polling_page(polling_page);
3462   log_info(os)("SafePoint Polling address: " INTPTR_FORMAT, p2i(polling_page));
3463 
3464   if (!UseMembar) {
3465     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
3466     guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
3467     os::set_memory_serialize_page(mem_serialize_page);
3468     log_info(os)("Memory Serialize Page address: " INTPTR_FORMAT, p2i(mem_serialize_page));
3469   }
3470 
3471   // initialize suspend/resume support - must do this before signal_sets_init()
3472   if (SR_initialize() != 0) {
3473     perror("SR_initialize failed");
3474     return JNI_ERR;
3475   }
3476 
3477   Bsd::signal_sets_init();
3478   Bsd::install_signal_handlers();
3479 
3480   // Check minimum allowable stack size for thread creation and to initialize
3481   // the java system classes, including StackOverflowError - depends on page
3482   // size.  Add a page for compiler2 recursion in main thread.
3483   // Add in 2*BytesPerWord times page size to account for VM stack during
3484   // class initialization depending on 32 or 64 bit VM.
3485   os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed,
3486                                     JavaThread::stack_guard_zone_size() +
3487                                     JavaThread::stack_shadow_zone_size() +
3488                                     (2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size());
3489 
3490   size_t threadStackSizeInBytes = ThreadStackSize * K;
3491   if (threadStackSizeInBytes != 0 &&
3492       threadStackSizeInBytes < os::Bsd::min_stack_allowed) {
3493     tty->print_cr("\nThe stack size specified is too small, "
3494                   "Specify at least %dk",
3495                   os::Bsd::min_stack_allowed/ K);
3496     return JNI_ERR;
3497   }
3498 
3499   // Make the stack size a multiple of the page size so that
3500   // the yellow/red zones can be guarded.
3501   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
3502                                                 vm_page_size()));
3503 
3504   if (MaxFDLimit) {
3505     // set the number of file descriptors to max. print out error
3506     // if getrlimit/setrlimit fails but continue regardless.
3507     struct rlimit nbr_files;
3508     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3509     if (status != 0) {
3510       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
3511     } else {
3512       nbr_files.rlim_cur = nbr_files.rlim_max;
3513 
3514 #ifdef __APPLE__
3515       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3516       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3517       // be used instead
3518       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3519 #endif
3520 
3521       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3522       if (status != 0) {
3523         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
3524       }
3525     }
3526   }
3527 
3528   // at-exit methods are called in the reverse order of their registration.
3529   // atexit functions are called on return from main or as a result of a
3530   // call to exit(3C). There can be only 32 of these functions registered
3531   // and atexit() does not set errno.
3532 
3533   if (PerfAllowAtExitRegistration) {
3534     // only register atexit functions if PerfAllowAtExitRegistration is set.
3535     // atexit functions can be delayed until process exit time, which
3536     // can be problematic for embedded VM situations. Embedded VMs should
3537     // call DestroyJavaVM() to assure that VM resources are released.
3538 
3539     // note: perfMemory_exit_helper atexit function may be removed in
3540     // the future if the appropriate cleanup code can be added to the
3541     // VM_Exit VMOperation's doit method.
3542     if (atexit(perfMemory_exit_helper) != 0) {
3543       warning("os::init2 atexit(perfMemory_exit_helper) failed");
3544     }
3545   }
3546 
3547   // initialize thread priority policy
3548   prio_init();
3549 
3550 #ifdef __APPLE__
3551   // dynamically link to objective c gc registration
3552   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3553   if (handleLibObjc != NULL) {
3554     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3555   }
3556 #endif
3557 
3558   return JNI_OK;
3559 }
3560 
3561 // Mark the polling page as unreadable
3562 void os::make_polling_page_unreadable(void) {
3563   if (!guard_memory((char*)_polling_page, Bsd::page_size())) {
3564     fatal("Could not disable polling page");
3565   }
3566 }
3567 
3568 // Mark the polling page as readable
3569 void os::make_polling_page_readable(void) {
3570   if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) {
3571     fatal("Could not enable polling page");
3572   }
3573 }
3574 
3575 int os::active_processor_count() {
3576   return _processor_count;
3577 }
3578 
3579 void os::set_native_thread_name(const char *name) {
3580 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3581   // This is only supported in Snow Leopard and beyond
3582   if (name != NULL) {
3583     // Add a "Java: " prefix to the name
3584     char buf[MAXTHREADNAMESIZE];
3585     snprintf(buf, sizeof(buf), "Java: %s", name);
3586     pthread_setname_np(buf);
3587   }
3588 #endif
3589 }
3590 
3591 bool os::distribute_processes(uint length, uint* distribution) {
3592   // Not yet implemented.
3593   return false;
3594 }
3595 
3596 bool os::bind_to_processor(uint processor_id) {
3597   // Not yet implemented.
3598   return false;
3599 }
3600 
3601 void os::SuspendedThreadTask::internal_do_task() {
3602   if (do_suspend(_thread->osthread())) {
3603     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3604     do_task(context);
3605     do_resume(_thread->osthread());
3606   }
3607 }
3608 
3609 ///
3610 class PcFetcher : public os::SuspendedThreadTask {
3611  public:
3612   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3613   ExtendedPC result();
3614  protected:
3615   void do_task(const os::SuspendedThreadTaskContext& context);
3616  private:
3617   ExtendedPC _epc;
3618 };
3619 
3620 ExtendedPC PcFetcher::result() {
3621   guarantee(is_done(), "task is not done yet.");
3622   return _epc;
3623 }
3624 
3625 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3626   Thread* thread = context.thread();
3627   OSThread* osthread = thread->osthread();
3628   if (osthread->ucontext() != NULL) {
3629     _epc = os::Bsd::ucontext_get_pc((const ucontext_t *) context.ucontext());
3630   } else {
3631     // NULL context is unexpected, double-check this is the VMThread
3632     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3633   }
3634 }
3635 
3636 // Suspends the target using the signal mechanism and then grabs the PC before
3637 // resuming the target. Used by the flat-profiler only
3638 ExtendedPC os::get_thread_pc(Thread* thread) {
3639   // Make sure that it is called by the watcher for the VMThread
3640   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
3641   assert(thread->is_VM_thread(), "Can only be called for VMThread");
3642 
3643   PcFetcher fetcher(thread);
3644   fetcher.run();
3645   return fetcher.result();
3646 }
3647 
3648 ////////////////////////////////////////////////////////////////////////////////
3649 // debug support
3650 
3651 bool os::find(address addr, outputStream* st) {
3652   Dl_info dlinfo;
3653   memset(&dlinfo, 0, sizeof(dlinfo));
3654   if (dladdr(addr, &dlinfo) != 0) {
3655     st->print(PTR_FORMAT ": ", addr);
3656     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
3657       st->print("%s+%#x", dlinfo.dli_sname,
3658                 addr - (intptr_t)dlinfo.dli_saddr);
3659     } else if (dlinfo.dli_fbase != NULL) {
3660       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
3661     } else {
3662       st->print("<absolute address>");
3663     }
3664     if (dlinfo.dli_fname != NULL) {
3665       st->print(" in %s", dlinfo.dli_fname);
3666     }
3667     if (dlinfo.dli_fbase != NULL) {
3668       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
3669     }
3670     st->cr();
3671 
3672     if (Verbose) {
3673       // decode some bytes around the PC
3674       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
3675       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
3676       address       lowest = (address) dlinfo.dli_sname;
3677       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
3678       if (begin < lowest)  begin = lowest;
3679       Dl_info dlinfo2;
3680       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
3681           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
3682         end = (address) dlinfo2.dli_saddr;
3683       }
3684       Disassembler::decode(begin, end, st);
3685     }
3686     return true;
3687   }
3688   return false;
3689 }
3690 
3691 ////////////////////////////////////////////////////////////////////////////////
3692 // misc
3693 
3694 // This does not do anything on Bsd. This is basically a hook for being
3695 // able to use structured exception handling (thread-local exception filters)
3696 // on, e.g., Win32.
3697 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
3698                               const methodHandle& method, JavaCallArguments* args,
3699                               Thread* thread) {
3700   f(value, method, args, thread);
3701 }
3702 
3703 void os::print_statistics() {
3704 }
3705 
3706 bool os::message_box(const char* title, const char* message) {
3707   int i;
3708   fdStream err(defaultStream::error_fd());
3709   for (i = 0; i < 78; i++) err.print_raw("=");
3710   err.cr();
3711   err.print_raw_cr(title);
3712   for (i = 0; i < 78; i++) err.print_raw("-");
3713   err.cr();
3714   err.print_raw_cr(message);
3715   for (i = 0; i < 78; i++) err.print_raw("=");
3716   err.cr();
3717 
3718   char buf[16];
3719   // Prevent process from exiting upon "read error" without consuming all CPU
3720   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3721 
3722   return buf[0] == 'y' || buf[0] == 'Y';
3723 }
3724 
3725 int os::stat(const char *path, struct stat *sbuf) {
3726   char pathbuf[MAX_PATH];
3727   if (strlen(path) > MAX_PATH - 1) {
3728     errno = ENAMETOOLONG;
3729     return -1;
3730   }
3731   os::native_path(strcpy(pathbuf, path));
3732   return ::stat(pathbuf, sbuf);
3733 }
3734 
3735 static inline struct timespec get_mtime(const char* filename) {
3736   struct stat st;
3737   int ret = os::stat(filename, &st);
3738   assert(ret == 0, "failed to stat() file '%s': %s", filename, strerror(errno));
3739 #ifdef __APPLE__
3740   return st.st_mtimespec;
3741 #else
3742   return st.st_mtim;
3743 #endif
3744 }
3745 
3746 int os::compare_file_modified_times(const char* file1, const char* file2) {
3747   struct timespec filetime1 = get_mtime(file1);
3748   struct timespec filetime2 = get_mtime(file2);
3749   int diff = filetime1.tv_sec - filetime2.tv_sec;
3750   if (diff == 0) {
3751     return filetime1.tv_nsec - filetime2.tv_nsec;
3752   }
3753   return diff;
3754 }
3755 
3756 
3757 bool os::check_heap(bool force) {
3758   return true;
3759 }
3760 
3761 // Is a (classpath) directory empty?
3762 bool os::dir_is_empty(const char* path) {
3763   DIR *dir = NULL;
3764   struct dirent *ptr;
3765 
3766   dir = opendir(path);
3767   if (dir == NULL) return true;
3768 
3769   // Scan the directory
3770   bool result = true;
3771   char buf[sizeof(struct dirent) + MAX_PATH];
3772   while (result && (ptr = ::readdir(dir)) != NULL) {
3773     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3774       result = false;
3775     }
3776   }
3777   closedir(dir);
3778   return result;
3779 }
3780 
3781 // This code originates from JDK's sysOpen and open64_w
3782 // from src/solaris/hpi/src/system_md.c
3783 
3784 int os::open(const char *path, int oflag, int mode) {
3785   if (strlen(path) > MAX_PATH - 1) {
3786     errno = ENAMETOOLONG;
3787     return -1;
3788   }
3789   int fd;
3790 
3791   fd = ::open(path, oflag, mode);
3792   if (fd == -1) return -1;
3793 
3794   // If the open succeeded, the file might still be a directory
3795   {
3796     struct stat buf;
3797     int ret = ::fstat(fd, &buf);
3798     int st_mode = buf.st_mode;
3799 
3800     if (ret != -1) {
3801       if ((st_mode & S_IFMT) == S_IFDIR) {
3802         errno = EISDIR;
3803         ::close(fd);
3804         return -1;
3805       }
3806     } else {
3807       ::close(fd);
3808       return -1;
3809     }
3810   }
3811 
3812   // All file descriptors that are opened in the JVM and not
3813   // specifically destined for a subprocess should have the
3814   // close-on-exec flag set.  If we don't set it, then careless 3rd
3815   // party native code might fork and exec without closing all
3816   // appropriate file descriptors (e.g. as we do in closeDescriptors in
3817   // UNIXProcess.c), and this in turn might:
3818   //
3819   // - cause end-of-file to fail to be detected on some file
3820   //   descriptors, resulting in mysterious hangs, or
3821   //
3822   // - might cause an fopen in the subprocess to fail on a system
3823   //   suffering from bug 1085341.
3824   //
3825   // (Yes, the default setting of the close-on-exec flag is a Unix
3826   // design flaw)
3827   //
3828   // See:
3829   // 1085341: 32-bit stdio routines should support file descriptors >255
3830   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3831   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3832   //
3833 #ifdef FD_CLOEXEC
3834   {
3835     int flags = ::fcntl(fd, F_GETFD);
3836     if (flags != -1) {
3837       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3838     }
3839   }
3840 #endif
3841 
3842   return fd;
3843 }
3844 
3845 
3846 // create binary file, rewriting existing file if required
3847 int os::create_binary_file(const char* path, bool rewrite_existing) {
3848   int oflags = O_WRONLY | O_CREAT;
3849   if (!rewrite_existing) {
3850     oflags |= O_EXCL;
3851   }
3852   return ::open(path, oflags, S_IREAD | S_IWRITE);
3853 }
3854 
3855 // return current position of file pointer
3856 jlong os::current_file_offset(int fd) {
3857   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
3858 }
3859 
3860 // move file pointer to the specified offset
3861 jlong os::seek_to_file_offset(int fd, jlong offset) {
3862   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
3863 }
3864 
3865 // This code originates from JDK's sysAvailable
3866 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
3867 
3868 int os::available(int fd, jlong *bytes) {
3869   jlong cur, end;
3870   int mode;
3871   struct stat buf;
3872 
3873   if (::fstat(fd, &buf) >= 0) {
3874     mode = buf.st_mode;
3875     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
3876       int n;
3877       if (::ioctl(fd, FIONREAD, &n) >= 0) {
3878         *bytes = n;
3879         return 1;
3880       }
3881     }
3882   }
3883   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
3884     return 0;
3885   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
3886     return 0;
3887   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
3888     return 0;
3889   }
3890   *bytes = end - cur;
3891   return 1;
3892 }
3893 
3894 // Map a block of memory.
3895 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
3896                         char *addr, size_t bytes, bool read_only,
3897                         bool allow_exec) {
3898   int prot;
3899   int flags;
3900 
3901   if (read_only) {
3902     prot = PROT_READ;
3903     flags = MAP_SHARED;
3904   } else {
3905     prot = PROT_READ | PROT_WRITE;
3906     flags = MAP_PRIVATE;
3907   }
3908 
3909   if (allow_exec) {
3910     prot |= PROT_EXEC;
3911   }
3912 
3913   if (addr != NULL) {
3914     flags |= MAP_FIXED;
3915   }
3916 
3917   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
3918                                      fd, file_offset);
3919   if (mapped_address == MAP_FAILED) {
3920     return NULL;
3921   }
3922   return mapped_address;
3923 }
3924 
3925 
3926 // Remap a block of memory.
3927 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
3928                           char *addr, size_t bytes, bool read_only,
3929                           bool allow_exec) {
3930   // same as map_memory() on this OS
3931   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
3932                         allow_exec);
3933 }
3934 
3935 
3936 // Unmap a block of memory.
3937 bool os::pd_unmap_memory(char* addr, size_t bytes) {
3938   return munmap(addr, bytes) == 0;
3939 }
3940 
3941 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
3942 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
3943 // of a thread.
3944 //
3945 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
3946 // the fast estimate available on the platform.
3947 
3948 jlong os::current_thread_cpu_time() {
3949 #ifdef __APPLE__
3950   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
3951 #else
3952   Unimplemented();
3953   return 0;
3954 #endif
3955 }
3956 
3957 jlong os::thread_cpu_time(Thread* thread) {
3958 #ifdef __APPLE__
3959   return os::thread_cpu_time(thread, true /* user + sys */);
3960 #else
3961   Unimplemented();
3962   return 0;
3963 #endif
3964 }
3965 
3966 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
3967 #ifdef __APPLE__
3968   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
3969 #else
3970   Unimplemented();
3971   return 0;
3972 #endif
3973 }
3974 
3975 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
3976 #ifdef __APPLE__
3977   struct thread_basic_info tinfo;
3978   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
3979   kern_return_t kr;
3980   thread_t mach_thread;
3981 
3982   mach_thread = thread->osthread()->thread_id();
3983   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
3984   if (kr != KERN_SUCCESS) {
3985     return -1;
3986   }
3987 
3988   if (user_sys_cpu_time) {
3989     jlong nanos;
3990     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
3991     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
3992     return nanos;
3993   } else {
3994     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
3995   }
3996 #else
3997   Unimplemented();
3998   return 0;
3999 #endif
4000 }
4001 
4002 
4003 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4004   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
4005   info_ptr->may_skip_backward = false;     // elapsed time not wall time
4006   info_ptr->may_skip_forward = false;      // elapsed time not wall time
4007   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
4008 }
4009 
4010 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4011   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
4012   info_ptr->may_skip_backward = false;     // elapsed time not wall time
4013   info_ptr->may_skip_forward = false;      // elapsed time not wall time
4014   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
4015 }
4016 
4017 bool os::is_thread_cpu_time_supported() {
4018 #ifdef __APPLE__
4019   return true;
4020 #else
4021   return false;
4022 #endif
4023 }
4024 
4025 // System loadavg support.  Returns -1 if load average cannot be obtained.
4026 // Bsd doesn't yet have a (official) notion of processor sets,
4027 // so just return the system wide load average.
4028 int os::loadavg(double loadavg[], int nelem) {
4029   return ::getloadavg(loadavg, nelem);
4030 }
4031 
4032 void os::pause() {
4033   char filename[MAX_PATH];
4034   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4035     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4036   } else {
4037     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4038   }
4039 
4040   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4041   if (fd != -1) {
4042     struct stat buf;
4043     ::close(fd);
4044     while (::stat(filename, &buf) == 0) {
4045       (void)::poll(NULL, 0, 100);
4046     }
4047   } else {
4048     jio_fprintf(stderr,
4049                 "Could not open pause file '%s', continuing immediately.\n", filename);
4050   }
4051 }
4052 
4053 
4054 // Refer to the comments in os_solaris.cpp park-unpark. The next two
4055 // comment paragraphs are worth repeating here:
4056 //
4057 // Assumption:
4058 //    Only one parker can exist on an event, which is why we allocate
4059 //    them per-thread. Multiple unparkers can coexist.
4060 //
4061 // _Event serves as a restricted-range semaphore.
4062 //   -1 : thread is blocked, i.e. there is a waiter
4063 //    0 : neutral: thread is running or ready,
4064 //        could have been signaled after a wait started
4065 //    1 : signaled - thread is running or ready
4066 //
4067 
4068 // utility to compute the abstime argument to timedwait:
4069 // millis is the relative timeout time
4070 // abstime will be the absolute timeout time
4071 // TODO: replace compute_abstime() with unpackTime()
4072 
4073 static struct timespec* compute_abstime(struct timespec* abstime,
4074                                         jlong millis) {
4075   if (millis < 0)  millis = 0;
4076   struct timeval now;
4077   int status = gettimeofday(&now, NULL);
4078   assert(status == 0, "gettimeofday");
4079   jlong seconds = millis / 1000;
4080   millis %= 1000;
4081   if (seconds > 50000000) { // see man cond_timedwait(3T)
4082     seconds = 50000000;
4083   }
4084   abstime->tv_sec = now.tv_sec  + seconds;
4085   long       usec = now.tv_usec + millis * 1000;
4086   if (usec >= 1000000) {
4087     abstime->tv_sec += 1;
4088     usec -= 1000000;
4089   }
4090   abstime->tv_nsec = usec * 1000;
4091   return abstime;
4092 }
4093 
4094 void os::PlatformEvent::park() {       // AKA "down()"
4095   // Transitions for _Event:
4096   //   -1 => -1 : illegal
4097   //    1 =>  0 : pass - return immediately
4098   //    0 => -1 : block; then set _Event to 0 before returning
4099 
4100   // Invariant: Only the thread associated with the Event/PlatformEvent
4101   // may call park().
4102   // TODO: assert that _Assoc != NULL or _Assoc == Self
4103   assert(_nParked == 0, "invariant");
4104 
4105   int v;
4106   for (;;) {
4107     v = _Event;
4108     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
4109   }
4110   guarantee(v >= 0, "invariant");
4111   if (v == 0) {
4112     // Do this the hard way by blocking ...
4113     int status = pthread_mutex_lock(_mutex);
4114     assert_status(status == 0, status, "mutex_lock");
4115     guarantee(_nParked == 0, "invariant");
4116     ++_nParked;
4117     while (_Event < 0) {
4118       status = pthread_cond_wait(_cond, _mutex);
4119       // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
4120       // Treat this the same as if the wait was interrupted
4121       if (status == ETIMEDOUT) { status = EINTR; }
4122       assert_status(status == 0 || status == EINTR, status, "cond_wait");
4123     }
4124     --_nParked;
4125 
4126     _Event = 0;
4127     status = pthread_mutex_unlock(_mutex);
4128     assert_status(status == 0, status, "mutex_unlock");
4129     // Paranoia to ensure our locked and lock-free paths interact
4130     // correctly with each other.
4131     OrderAccess::fence();
4132   }
4133   guarantee(_Event >= 0, "invariant");
4134 }
4135 
4136 int os::PlatformEvent::park(jlong millis) {
4137   // Transitions for _Event:
4138   //   -1 => -1 : illegal
4139   //    1 =>  0 : pass - return immediately
4140   //    0 => -1 : block; then set _Event to 0 before returning
4141 
4142   guarantee(_nParked == 0, "invariant");
4143 
4144   int v;
4145   for (;;) {
4146     v = _Event;
4147     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
4148   }
4149   guarantee(v >= 0, "invariant");
4150   if (v != 0) return OS_OK;
4151 
4152   // We do this the hard way, by blocking the thread.
4153   // Consider enforcing a minimum timeout value.
4154   struct timespec abst;
4155   compute_abstime(&abst, millis);
4156 
4157   int ret = OS_TIMEOUT;
4158   int status = pthread_mutex_lock(_mutex);
4159   assert_status(status == 0, status, "mutex_lock");
4160   guarantee(_nParked == 0, "invariant");
4161   ++_nParked;
4162 
4163   // Object.wait(timo) will return because of
4164   // (a) notification
4165   // (b) timeout
4166   // (c) thread.interrupt
4167   //
4168   // Thread.interrupt and object.notify{All} both call Event::set.
4169   // That is, we treat thread.interrupt as a special case of notification.
4170   // We ignore spurious OS wakeups unless FilterSpuriousWakeups is false.
4171   // We assume all ETIME returns are valid.
4172   //
4173   // TODO: properly differentiate simultaneous notify+interrupt.
4174   // In that case, we should propagate the notify to another waiter.
4175 
4176   while (_Event < 0) {
4177     status = pthread_cond_timedwait(_cond, _mutex, &abst);
4178     assert_status(status == 0 || status == EINTR ||
4179                   status == ETIMEDOUT,
4180                   status, "cond_timedwait");
4181     if (!FilterSpuriousWakeups) break;                 // previous semantics
4182     if (status == ETIMEDOUT) break;
4183     // We consume and ignore EINTR and spurious wakeups.
4184   }
4185   --_nParked;
4186   if (_Event >= 0) {
4187     ret = OS_OK;
4188   }
4189   _Event = 0;
4190   status = pthread_mutex_unlock(_mutex);
4191   assert_status(status == 0, status, "mutex_unlock");
4192   assert(_nParked == 0, "invariant");
4193   // Paranoia to ensure our locked and lock-free paths interact
4194   // correctly with each other.
4195   OrderAccess::fence();
4196   return ret;
4197 }
4198 
4199 void os::PlatformEvent::unpark() {
4200   // Transitions for _Event:
4201   //    0 => 1 : just return
4202   //    1 => 1 : just return
4203   //   -1 => either 0 or 1; must signal target thread
4204   //         That is, we can safely transition _Event from -1 to either
4205   //         0 or 1.
4206   // See also: "Semaphores in Plan 9" by Mullender & Cox
4207   //
4208   // Note: Forcing a transition from "-1" to "1" on an unpark() means
4209   // that it will take two back-to-back park() calls for the owning
4210   // thread to block. This has the benefit of forcing a spurious return
4211   // from the first park() call after an unpark() call which will help
4212   // shake out uses of park() and unpark() without condition variables.
4213 
4214   if (Atomic::xchg(1, &_Event) >= 0) return;
4215 
4216   // Wait for the thread associated with the event to vacate
4217   int status = pthread_mutex_lock(_mutex);
4218   assert_status(status == 0, status, "mutex_lock");
4219   int AnyWaiters = _nParked;
4220   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
4221   status = pthread_mutex_unlock(_mutex);
4222   assert_status(status == 0, status, "mutex_unlock");
4223   if (AnyWaiters != 0) {
4224     // Note that we signal() *after* dropping the lock for "immortal" Events.
4225     // This is safe and avoids a common class of  futile wakeups.  In rare
4226     // circumstances this can cause a thread to return prematurely from
4227     // cond_{timed}wait() but the spurious wakeup is benign and the victim
4228     // will simply re-test the condition and re-park itself.
4229     // This provides particular benefit if the underlying platform does not
4230     // provide wait morphing.
4231     status = pthread_cond_signal(_cond);
4232     assert_status(status == 0, status, "cond_signal");
4233   }
4234 }
4235 
4236 
4237 // JSR166
4238 // -------------------------------------------------------
4239 
4240 // The solaris and bsd implementations of park/unpark are fairly
4241 // conservative for now, but can be improved. They currently use a
4242 // mutex/condvar pair, plus a a count.
4243 // Park decrements count if > 0, else does a condvar wait.  Unpark
4244 // sets count to 1 and signals condvar.  Only one thread ever waits
4245 // on the condvar. Contention seen when trying to park implies that someone
4246 // is unparking you, so don't wait. And spurious returns are fine, so there
4247 // is no need to track notifications.
4248 
4249 #define MAX_SECS 100000000
4250 
4251 // This code is common to bsd and solaris and will be moved to a
4252 // common place in dolphin.
4253 //
4254 // The passed in time value is either a relative time in nanoseconds
4255 // or an absolute time in milliseconds. Either way it has to be unpacked
4256 // into suitable seconds and nanoseconds components and stored in the
4257 // given timespec structure.
4258 // Given time is a 64-bit value and the time_t used in the timespec is only
4259 // a signed-32-bit value (except on 64-bit Bsd) we have to watch for
4260 // overflow if times way in the future are given. Further on Solaris versions
4261 // prior to 10 there is a restriction (see cond_timedwait) that the specified
4262 // number of seconds, in abstime, is less than current_time  + 100,000,000.
4263 // As it will be 28 years before "now + 100000000" will overflow we can
4264 // ignore overflow and just impose a hard-limit on seconds using the value
4265 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
4266 // years from "now".
4267 
4268 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
4269   assert(time > 0, "convertTime");
4270 
4271   struct timeval now;
4272   int status = gettimeofday(&now, NULL);
4273   assert(status == 0, "gettimeofday");
4274 
4275   time_t max_secs = now.tv_sec + MAX_SECS;
4276 
4277   if (isAbsolute) {
4278     jlong secs = time / 1000;
4279     if (secs > max_secs) {
4280       absTime->tv_sec = max_secs;
4281     } else {
4282       absTime->tv_sec = secs;
4283     }
4284     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
4285   } else {
4286     jlong secs = time / NANOSECS_PER_SEC;
4287     if (secs >= MAX_SECS) {
4288       absTime->tv_sec = max_secs;
4289       absTime->tv_nsec = 0;
4290     } else {
4291       absTime->tv_sec = now.tv_sec + secs;
4292       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
4293       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
4294         absTime->tv_nsec -= NANOSECS_PER_SEC;
4295         ++absTime->tv_sec; // note: this must be <= max_secs
4296       }
4297     }
4298   }
4299   assert(absTime->tv_sec >= 0, "tv_sec < 0");
4300   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
4301   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
4302   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
4303 }
4304 
4305 void Parker::park(bool isAbsolute, jlong time) {
4306   // Ideally we'd do something useful while spinning, such
4307   // as calling unpackTime().
4308 
4309   // Optional fast-path check:
4310   // Return immediately if a permit is available.
4311   // We depend on Atomic::xchg() having full barrier semantics
4312   // since we are doing a lock-free update to _counter.
4313   if (Atomic::xchg(0, &_counter) > 0) return;
4314 
4315   Thread* thread = Thread::current();
4316   assert(thread->is_Java_thread(), "Must be JavaThread");
4317   JavaThread *jt = (JavaThread *)thread;
4318 
4319   // Optional optimization -- avoid state transitions if there's an interrupt pending.
4320   // Check interrupt before trying to wait
4321   if (Thread::is_interrupted(thread, false)) {
4322     return;
4323   }
4324 
4325   // Next, demultiplex/decode time arguments
4326   struct timespec absTime;
4327   if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
4328     return;
4329   }
4330   if (time > 0) {
4331     unpackTime(&absTime, isAbsolute, time);
4332   }
4333 
4334 
4335   // Enter safepoint region
4336   // Beware of deadlocks such as 6317397.
4337   // The per-thread Parker:: mutex is a classic leaf-lock.
4338   // In particular a thread must never block on the Threads_lock while
4339   // holding the Parker:: mutex.  If safepoints are pending both the
4340   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
4341   ThreadBlockInVM tbivm(jt);
4342 
4343   // Don't wait if cannot get lock since interference arises from
4344   // unblocking.  Also. check interrupt before trying wait
4345   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
4346     return;
4347   }
4348 
4349   int status;
4350   if (_counter > 0)  { // no wait needed
4351     _counter = 0;
4352     status = pthread_mutex_unlock(_mutex);
4353     assert_status(status == 0, status, "invariant");
4354     // Paranoia to ensure our locked and lock-free paths interact
4355     // correctly with each other and Java-level accesses.
4356     OrderAccess::fence();
4357     return;
4358   }
4359 
4360 #ifdef ASSERT
4361   // Don't catch signals while blocked; let the running threads have the signals.
4362   // (This allows a debugger to break into the running thread.)
4363   sigset_t oldsigs;
4364   sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals();
4365   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
4366 #endif
4367 
4368   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
4369   jt->set_suspend_equivalent();
4370   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
4371 
4372   if (time == 0) {
4373     status = pthread_cond_wait(_cond, _mutex);
4374   } else {
4375     status = pthread_cond_timedwait(_cond, _mutex, &absTime);
4376   }
4377   assert_status(status == 0 || status == EINTR ||
4378                 status == ETIMEDOUT,
4379                 status, "cond_timedwait");
4380 
4381 #ifdef ASSERT
4382   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
4383 #endif
4384 
4385   _counter = 0;
4386   status = pthread_mutex_unlock(_mutex);
4387   assert_status(status == 0, status, "invariant");
4388   // Paranoia to ensure our locked and lock-free paths interact
4389   // correctly with each other and Java-level accesses.
4390   OrderAccess::fence();
4391 
4392   // If externally suspended while waiting, re-suspend
4393   if (jt->handle_special_suspend_equivalent_condition()) {
4394     jt->java_suspend_self();
4395   }
4396 }
4397 
4398 void Parker::unpark() {
4399   int status = pthread_mutex_lock(_mutex);
4400   assert_status(status == 0, status, "invariant");
4401   const int s = _counter;
4402   _counter = 1;
4403   status = pthread_mutex_unlock(_mutex);
4404   assert_status(status == 0, status, "invariant");
4405   if (s < 1) {
4406     status = pthread_cond_signal(_cond);
4407     assert_status(status == 0, status, "invariant");
4408   }
4409 }
4410 
4411 
4412 // Darwin has no "environ" in a dynamic library.
4413 #ifdef __APPLE__
4414   #include <crt_externs.h>
4415   #define environ (*_NSGetEnviron())
4416 #else
4417 extern char** environ;
4418 #endif
4419 
4420 // Run the specified command in a separate process. Return its exit value,
4421 // or -1 on failure (e.g. can't fork a new process).
4422 // Unlike system(), this function can be called from signal handler. It
4423 // doesn't block SIGINT et al.
4424 int os::fork_and_exec(char* cmd) {
4425   const char * argv[4] = {"sh", "-c", cmd, NULL};
4426 
4427   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
4428   // pthread_atfork handlers and reset pthread library. All we need is a
4429   // separate process to execve. Make a direct syscall to fork process.
4430   // On IA64 there's no fork syscall, we have to use fork() and hope for
4431   // the best...
4432   pid_t pid = fork();
4433 
4434   if (pid < 0) {
4435     // fork failed
4436     return -1;
4437 
4438   } else if (pid == 0) {
4439     // child process
4440 
4441     // execve() in BsdThreads will call pthread_kill_other_threads_np()
4442     // first to kill every thread on the thread list. Because this list is
4443     // not reset by fork() (see notes above), execve() will instead kill
4444     // every thread in the parent process. We know this is the only thread
4445     // in the new process, so make a system call directly.
4446     // IA64 should use normal execve() from glibc to match the glibc fork()
4447     // above.
4448     execve("/bin/sh", (char* const*)argv, environ);
4449 
4450     // execve failed
4451     _exit(-1);
4452 
4453   } else  {
4454     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
4455     // care about the actual exit code, for now.
4456 
4457     int status;
4458 
4459     // Wait for the child process to exit.  This returns immediately if
4460     // the child has already exited. */
4461     while (waitpid(pid, &status, 0) < 0) {
4462       switch (errno) {
4463       case ECHILD: return 0;
4464       case EINTR: break;
4465       default: return -1;
4466       }
4467     }
4468 
4469     if (WIFEXITED(status)) {
4470       // The child exited normally; get its exit code.
4471       return WEXITSTATUS(status);
4472     } else if (WIFSIGNALED(status)) {
4473       // The child exited because of a signal
4474       // The best value to return is 0x80 + signal number,
4475       // because that is what all Unix shells do, and because
4476       // it allows callers to distinguish between process exit and
4477       // process death by signal.
4478       return 0x80 + WTERMSIG(status);
4479     } else {
4480       // Unknown exit code; pass it through
4481       return status;
4482     }
4483   }
4484 }
4485 
4486 // is_headless_jre()
4487 //
4488 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
4489 // in order to report if we are running in a headless jre
4490 //
4491 // Since JDK8 xawt/libmawt.so was moved into the same directory
4492 // as libawt.so, and renamed libawt_xawt.so
4493 //
4494 bool os::is_headless_jre() {
4495 #ifdef __APPLE__
4496   // We no longer build headless-only on Mac OS X
4497   return false;
4498 #else
4499   struct stat statbuf;
4500   char buf[MAXPATHLEN];
4501   char libmawtpath[MAXPATHLEN];
4502   const char *xawtstr  = "/xawt/libmawt" JNI_LIB_SUFFIX;
4503   const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX;
4504   char *p;
4505 
4506   // Get path to libjvm.so
4507   os::jvm_path(buf, sizeof(buf));
4508 
4509   // Get rid of libjvm.so
4510   p = strrchr(buf, '/');
4511   if (p == NULL) {
4512     return false;
4513   } else {
4514     *p = '\0';
4515   }
4516 
4517   // Get rid of client or server
4518   p = strrchr(buf, '/');
4519   if (p == NULL) {
4520     return false;
4521   } else {
4522     *p = '\0';
4523   }
4524 
4525   // check xawt/libmawt.so
4526   strcpy(libmawtpath, buf);
4527   strcat(libmawtpath, xawtstr);
4528   if (::stat(libmawtpath, &statbuf) == 0) return false;
4529 
4530   // check libawt_xawt.so
4531   strcpy(libmawtpath, buf);
4532   strcat(libmawtpath, new_xawtstr);
4533   if (::stat(libmawtpath, &statbuf) == 0) return false;
4534 
4535   return true;
4536 #endif
4537 }
4538 
4539 // Get the default path to the core file
4540 // Returns the length of the string
4541 int os::get_core_path(char* buffer, size_t bufferSize) {
4542   int n = jio_snprintf(buffer, bufferSize, "/cores/core.%d", current_process_id());
4543 
4544   // Truncate if theoretical string was longer than bufferSize
4545   n = MIN2(n, (int)bufferSize);
4546 
4547   return n;
4548 }
4549 
4550 #ifndef PRODUCT
4551 void TestReserveMemorySpecial_test() {
4552   // No tests available for this platform
4553 }
4554 #endif
4555 
4556 bool os::start_debugging(char *buf, int buflen) {
4557   int len = (int)strlen(buf);
4558   char *p = &buf[len];
4559 
4560   jio_snprintf(p, buflen-len,
4561              "\n\n"
4562              "Do you want to debug the problem?\n\n"
4563              "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " INTX_FORMAT " (" INTPTR_FORMAT ")\n"
4564              "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
4565              "Otherwise, press RETURN to abort...",
4566              os::current_process_id(), os::current_process_id(),
4567              os::current_thread_id(), os::current_thread_id());
4568 
4569   bool yes = os::message_box("Unexpected Error", buf);
4570 
4571   if (yes) {
4572     // yes, user asked VM to launch debugger
4573     jio_snprintf(buf, sizeof(buf), "gdb /proc/%d/exe %d",
4574                      os::current_process_id(), os::current_process_id());
4575 
4576     os::fork_and_exec(buf);
4577     yes = false;
4578   }
4579   return yes;
4580 }