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