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